]> code.delx.au - gnu-emacs/blob - lisp/progmodes/octave.el
Merge octave-mod.el and octave-inf.el into octave.el with some
[gnu-emacs] / lisp / progmodes / octave.el
1 ;;; octave.el --- editing octave source files under emacs
2
3 ;; Copyright (C) 1997, 2001-2013 Free Software Foundation, Inc.
4
5 ;; Author: Kurt Hornik <Kurt.Hornik@wu-wien.ac.at>
6 ;; John Eaton <jwe@octave.org>
7 ;; Maintainer: FSF
8 ;; Keywords: languages
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24
25 ;;; Commentary:
26
27 ;; This package provides emacs support for octave. It defines a major
28 ;; mode for editing octave code and contains code for interacting with
29 ;; an inferior octave process using comint.
30
31 ;; See the documentation of `octave-mode' and `run-octave' for further
32 ;; information on usage and customization.
33
34 ;;; Code:
35 (require 'comint)
36
37 (defgroup octave nil
38 "Editing Octave code."
39 :link '(custom-group-link :tag "Font Lock Faces group" font-lock-faces)
40 :group 'languages)
41
42 (defconst octave-maintainer-address
43 "Kurt Hornik <Kurt.Hornik@wu-wien.ac.at>, bug-gnu-emacs@gnu.org"
44 "Current maintainer of the Emacs Octave package.")
45
46 (define-abbrev-table 'octave-abbrev-table
47 (mapcar (lambda (e) (append e '(nil 0 t)))
48 '(("`a" "all_va_args")
49 ("`b" "break")
50 ("`cs" "case")
51 ("`ca" "catch")
52 ("`c" "continue")
53 ("`el" "else")
54 ("`eli" "elseif")
55 ("`et" "end_try_catch")
56 ("`eu" "end_unwind_protect")
57 ("`ef" "endfor")
58 ("`efu" "endfunction")
59 ("`ei" "endif")
60 ("`es" "endswitch")
61 ("`ew" "endwhile")
62 ("`f" "for")
63 ("`fu" "function")
64 ("`gl" "global")
65 ("`gp" "gplot")
66 ("`gs" "gsplot")
67 ("`if" "if ()")
68 ("`o" "otherwise")
69 ("`rp" "replot")
70 ("`r" "return")
71 ("`s" "switch")
72 ("`t" "try")
73 ("`u" "until ()")
74 ("`up" "unwind_protect")
75 ("`upc" "unwind_protect_cleanup")
76 ("`w" "while ()")))
77 "Abbrev table for Octave's reserved words.
78 Used in `octave-mode' and `inferior-octave-mode' buffers.
79 All Octave abbrevs start with a grave accent (`)."
80 :regexp "\\(?:[^`]\\|^\\)\\(\\(?:\\<\\|`\\)\\w+\\)\\W*")
81
82 (defvar octave-comment-char ?#
83 "Character to start an Octave comment.")
84 (defvar octave-comment-start
85 (string octave-comment-char ?\s)
86 "String to insert to start a new Octave in-line comment.")
87 (defvar octave-comment-start-skip "\\s<+\\s-*"
88 "Regexp to match the start of an Octave comment up to its body.")
89
90 (defvar octave-begin-keywords
91 '("do" "for" "function" "if" "switch" "try" "unwind_protect" "while"))
92 (defvar octave-else-keywords
93 '("case" "catch" "else" "elseif" "otherwise" "unwind_protect_cleanup"))
94 (defvar octave-end-keywords
95 '("endfor" "endfunction" "endif" "endswitch" "end_try_catch"
96 "end_unwind_protect" "endwhile" "until" "end"))
97
98 (defvar octave-reserved-words
99 (append octave-begin-keywords
100 octave-else-keywords
101 octave-end-keywords
102 '("break" "continue" "end" "global" "persistent" "return"))
103 "Reserved words in Octave.")
104
105 (defvar octave-text-functions
106 '("casesen" "cd" "chdir" "clear" "diary" "dir" "document" "echo"
107 "edit_history" "format" "help" "history" "hold"
108 "load" "ls" "more" "run_history" "save" "type"
109 "which" "who" "whos")
110 "Text functions in Octave.")
111
112 (defvar octave-variables
113 '("DEFAULT_EXEC_PATH" "DEFAULT_LOADPATH"
114 "EDITOR" "EXEC_PATH" "F_DUPFD" "F_GETFD" "F_GETFL" "F_SETFD"
115 "F_SETFL" "I" "IMAGE_PATH" "Inf" "J"
116 "NaN" "OCTAVE_VERSION" "O_APPEND" "O_CREAT" "O_EXCL"
117 "O_NONBLOCK" "O_RDONLY" "O_RDWR" "O_TRUNC" "O_WRONLY" "PAGER" "PS1"
118 "PS2" "PS4" "PWD" "SEEK_CUR" "SEEK_END" "SEEK_SET" "__F_DUPFD__"
119 "__F_GETFD__" "__F_GETFL__" "__F_SETFD__" "__F_SETFL__" "__I__"
120 "__Inf__" "__J__" "__NaN__" "__OCTAVE_VERSION__" "__O_APPEND__"
121 "__O_CREAT__" "__O_EXCL__" "__O_NONBLOCK__" "__O_RDONLY__"
122 "__O_RDWR__" "__O_TRUNC__" "__O_WRONLY__" "__PWD__" "__SEEK_CUR__"
123 "__SEEK_END__" "__SEEK_SET__" "__argv__" "__e__" "__eps__"
124 "__i__" "__inf__" "__j__" "__nan__" "__pi__"
125 "__program_invocation_name__" "__program_name__" "__realmax__"
126 "__realmin__" "__stderr__" "__stdin__" "__stdout__" "ans" "argv"
127 "beep_on_error" "completion_append_char"
128 "crash_dumps_octave_core" "default_save_format"
129 "e" "echo_executing_commands" "eps"
130 "error_text" "gnuplot_binary" "history_file"
131 "history_size" "ignore_function_time_stamp"
132 "inf" "nan" "nargin" "output_max_field_width" "output_precision"
133 "page_output_immediately" "page_screen_output" "pi"
134 "print_answer_id_name" "print_empty_dimensions"
135 "program_invocation_name" "program_name"
136 "realmax" "realmin" "return_last_computed_value" "save_precision"
137 "saving_history" "sighup_dumps_octave_core" "sigterm_dumps_octave_core"
138 "silent_functions" "split_long_rows" "stderr" "stdin" "stdout"
139 "string_fill_char" "struct_levels_to_print"
140 "suppress_verbose_help_message")
141 "Builtin variables in Octave.")
142
143 (defvar octave-function-header-regexp
144 (concat "^\\s-*\\_<\\(function\\)\\_>"
145 "\\([^=;\n]*=[ \t]*\\|[ \t]*\\)\\(\\(?:\\w\\|\\s_\\)+\\)\\_>")
146 "Regexp to match an Octave function header.
147 The string `function' and its name are given by the first and third
148 parenthetical grouping.")
149
150 \f
151 (defvar octave-font-lock-keywords
152 (list
153 ;; Fontify all builtin keywords.
154 (cons (concat "\\_<\\("
155 (regexp-opt (append octave-reserved-words
156 octave-text-functions))
157 "\\)\\_>")
158 'font-lock-keyword-face)
159 ;; Fontify all builtin operators.
160 (cons "\\(&\\||\\|<=\\|>=\\|==\\|<\\|>\\|!=\\|!\\)"
161 (if (boundp 'font-lock-builtin-face)
162 'font-lock-builtin-face
163 'font-lock-preprocessor-face))
164 ;; Fontify all builtin variables.
165 (cons (concat "\\_<" (regexp-opt octave-variables) "\\_>")
166 'font-lock-variable-name-face)
167 ;; Fontify all function declarations.
168 (list octave-function-header-regexp
169 '(1 font-lock-keyword-face)
170 '(3 font-lock-function-name-face nil t)))
171 "Additional Octave expressions to highlight.")
172
173 (defun octave-syntax-propertize-function (start end)
174 (goto-char start)
175 (octave-syntax-propertize-sqs end)
176 (funcall (syntax-propertize-rules
177 ;; Try to distinguish the string-quotes from the transpose-quotes.
178 ("[[({,; ]\\('\\)"
179 (1 (prog1 "\"'" (octave-syntax-propertize-sqs end)))))
180 (point) end))
181
182 (defun octave-syntax-propertize-sqs (end)
183 "Propertize the content/end of single-quote strings."
184 (when (eq (nth 3 (syntax-ppss)) ?\')
185 ;; A '..' string.
186 (when (re-search-forward
187 "\\(?:\\=\\|[^']\\)\\(?:''\\)*\\('\\)\\($\\|[^']\\)" end 'move)
188 (goto-char (match-beginning 2))
189 (when (eq (char-before (match-beginning 1)) ?\\)
190 ;; Backslash cannot escape a single quote.
191 (put-text-property (1- (match-beginning 1)) (match-beginning 1)
192 'syntax-table (string-to-syntax ".")))
193 (put-text-property (match-beginning 1) (match-end 1)
194 'syntax-table (string-to-syntax "\"'")))))
195
196 \f
197 (defvar octave-mode-map
198 (let ((map (make-sparse-keymap)))
199 (define-key map "`" 'octave-abbrev-start)
200 (define-key map "\e\n" 'octave-indent-new-comment-line)
201 (define-key map "\M-\C-q" 'octave-indent-defun)
202 (define-key map "\C-c\C-b" 'octave-submit-bug-report)
203 (define-key map "\C-c\C-p" 'octave-previous-code-line)
204 (define-key map "\C-c\C-n" 'octave-next-code-line)
205 (define-key map "\C-c\C-a" 'octave-beginning-of-line)
206 (define-key map "\C-c\C-e" 'octave-end-of-line)
207 (define-key map [remap down-list] 'smie-down-list)
208 (define-key map "\C-c\M-\C-h" 'octave-mark-block)
209 (define-key map "\C-c]" 'smie-close-block)
210 (define-key map "\C-c/" 'smie-close-block)
211 (define-key map "\C-c\C-f" 'octave-insert-defun)
212 (define-key map "\C-c\C-il" 'octave-send-line)
213 (define-key map "\C-c\C-ib" 'octave-send-block)
214 (define-key map "\C-c\C-if" 'octave-send-defun)
215 (define-key map "\C-c\C-ir" 'octave-send-region)
216 (define-key map "\C-c\C-is" 'octave-show-process-buffer)
217 (define-key map "\C-c\C-iq" 'octave-hide-process-buffer)
218 (define-key map "\C-c\C-ik" 'octave-kill-process)
219 (define-key map "\C-c\C-i\C-l" 'octave-send-line)
220 (define-key map "\C-c\C-i\C-b" 'octave-send-block)
221 (define-key map "\C-c\C-i\C-f" 'octave-send-defun)
222 (define-key map "\C-c\C-i\C-r" 'octave-send-region)
223 (define-key map "\C-c\C-i\C-s" 'octave-show-process-buffer)
224 (define-key map "\C-c\C-i\C-q" 'octave-hide-process-buffer)
225 (define-key map "\C-c\C-i\C-k" 'octave-kill-process)
226 map)
227 "Keymap used in Octave mode.")
228
229
230
231 (easy-menu-define octave-mode-menu octave-mode-map
232 "Menu for Octave mode."
233 '("Octave"
234 ("Lines"
235 ["Previous Code Line" octave-previous-code-line t]
236 ["Next Code Line" octave-next-code-line t]
237 ["Begin of Continuation" octave-beginning-of-line t]
238 ["End of Continuation" octave-end-of-line t]
239 ["Split Line at Point" octave-indent-new-comment-line t])
240 ("Blocks"
241 ["Mark Block" octave-mark-block t]
242 ["Close Block" smie-close-block t])
243 ("Functions"
244 ["Indent Function" octave-indent-defun t]
245 ["Insert Function" octave-insert-defun t])
246 "-"
247 ("Debug"
248 ["Send Current Line" octave-send-line t]
249 ["Send Current Block" octave-send-block t]
250 ["Send Current Function" octave-send-defun t]
251 ["Send Region" octave-send-region t]
252 ["Show Process Buffer" octave-show-process-buffer t]
253 ["Hide Process Buffer" octave-hide-process-buffer t]
254 ["Kill Process" octave-kill-process t])
255 "-"
256 ["Indent Line" indent-according-to-mode t]
257 ["Complete Symbol" completion-at-point t]
258 "-"
259 ["Toggle Abbrev Mode" abbrev-mode
260 :style toggle :selected abbrev-mode]
261 ["Toggle Auto-Fill Mode" auto-fill-mode
262 :style toggle :selected auto-fill-function]
263 "-"
264 ["Submit Bug Report" octave-submit-bug-report t]
265 "-"
266 ["Describe Octave Mode" describe-mode t]
267 ["Lookup Octave Index" info-lookup-symbol t]))
268
269 (defvar octave-mode-syntax-table
270 (let ((table (make-syntax-table)))
271 (modify-syntax-entry ?\r " " table)
272 (modify-syntax-entry ?+ "." table)
273 (modify-syntax-entry ?- "." table)
274 (modify-syntax-entry ?= "." table)
275 (modify-syntax-entry ?* "." table)
276 (modify-syntax-entry ?/ "." table)
277 (modify-syntax-entry ?> "." table)
278 (modify-syntax-entry ?< "." table)
279 (modify-syntax-entry ?& "." table)
280 (modify-syntax-entry ?| "." table)
281 (modify-syntax-entry ?! "." table)
282 (modify-syntax-entry ?\\ "\\" table)
283 (modify-syntax-entry ?\' "." table)
284 ;; Was "w" for abbrevs, but now that it's not necessary any more,
285 (modify-syntax-entry ?\` "." table)
286 (modify-syntax-entry ?\" "\"" table)
287 (modify-syntax-entry ?. "_" table)
288 (modify-syntax-entry ?_ "_" table)
289 ;; The "b" flag only applies to the second letter of the comstart
290 ;; and the first letter of the comend, i.e. the "4b" below is ineffective.
291 ;; If we try to put `b' on the single-line comments, we get a similar
292 ;; problem where the % and # chars appear as first chars of the 2-char
293 ;; comend, so the multi-line ender is also turned into style-b.
294 ;; So we need the new "c" comment style.
295 (modify-syntax-entry ?\% "< 13" table)
296 (modify-syntax-entry ?\# "< 13" table)
297 (modify-syntax-entry ?\{ "(} 2c" table)
298 (modify-syntax-entry ?\} "){ 4c" table)
299 (modify-syntax-entry ?\n ">" table)
300 table)
301 "Syntax table in use in `octave-mode' buffers.")
302
303 (defcustom octave-blink-matching-block t
304 "Control the blinking of matching Octave block keywords.
305 Non-nil means show matching begin of block when inserting a space,
306 newline or semicolon after an else or end keyword."
307 :type 'boolean
308 :group 'octave)
309
310 (defcustom octave-block-offset 2
311 "Extra indentation applied to statements in Octave block structures."
312 :type 'integer
313 :group 'octave)
314
315 (defvar octave-block-comment-start
316 (concat (make-string 2 octave-comment-char) " ")
317 "String to insert to start a new Octave comment on an empty line.")
318
319 (defcustom octave-continuation-offset 4
320 "Extra indentation applied to Octave continuation lines."
321 :type 'integer
322 :group 'octave)
323 (eval-and-compile
324 (defconst octave-continuation-marker-regexp "\\\\\\|\\.\\.\\."))
325 (defvar octave-continuation-regexp
326 (concat "[^#%\n]*\\(" octave-continuation-marker-regexp
327 "\\)\\s-*\\(\\s<.*\\)?$"))
328 (defcustom octave-continuation-string "\\"
329 "Character string used for Octave continuation lines. Normally \\."
330 :type 'string
331 :group 'octave)
332
333 (defvar octave-completion-alist nil
334 "Alist of Octave symbols for completion in Octave mode.
335 Each element looks like (VAR . VAR), where the car and cdr are the same
336 symbol (an Octave command or variable name).
337 Currently, only builtin variables can be completed.")
338
339 (defvar octave-mode-imenu-generic-expression
340 (list
341 ;; Functions
342 (list nil octave-function-header-regexp 3))
343 "Imenu expression for Octave mode. See `imenu-generic-expression'.")
344
345 (defcustom octave-mode-hook nil
346 "Hook to be run when Octave mode is started."
347 :type 'hook
348 :group 'octave)
349
350 (defcustom octave-send-show-buffer t
351 "Non-nil means display `inferior-octave-buffer' after sending to it."
352 :type 'boolean
353 :group 'octave)
354 (defcustom octave-send-line-auto-forward t
355 "Control auto-forward after sending to the inferior Octave process.
356 Non-nil means always go to the next Octave code line after sending."
357 :type 'boolean
358 :group 'octave)
359 (defcustom octave-send-echo-input t
360 "Non-nil means echo input sent to the inferior Octave process."
361 :type 'boolean
362 :group 'octave)
363
364 \f
365 ;;; SMIE indentation
366
367 (require 'smie)
368
369 (defconst octave-operator-table
370 '((assoc ";" "\n") (assoc ",") ; The doc claims they have equal precedence!?
371 (right "=" "+=" "-=" "*=" "/=")
372 (assoc "&&") (assoc "||") ; The doc claims they have equal precedence!?
373 (assoc "&") (assoc "|") ; The doc claims they have equal precedence!?
374 (nonassoc "<" "<=" "==" ">=" ">" "!=" "~=")
375 (nonassoc ":") ;No idea what this is.
376 (assoc "+" "-")
377 (assoc "*" "/" "\\" ".\\" ".*" "./")
378 (nonassoc "'" ".'")
379 (nonassoc "++" "--" "!" "~") ;And unary "+" and "-".
380 (right "^" "**" ".^" ".**")
381 ;; It's not really an operator, but for indentation purposes it
382 ;; could be convenient to treat it as one.
383 (assoc "...")))
384
385 (defconst octave-smie-bnf-table
386 '((atom)
387 ;; We can't distinguish the first element in a sequence with
388 ;; precedence grammars, so we can't distinguish the condition
389 ;; if the `if' from the subsequent body, for example.
390 ;; This has to be done later in the indentation rules.
391 (exp (exp "\n" exp)
392 ;; We need to mention at least one of the operators in this part
393 ;; of the grammar: if the BNF and the operator table have
394 ;; no overlap, SMIE can't know how they relate.
395 (exp ";" exp)
396 ("try" exp "catch" exp "end_try_catch")
397 ("try" exp "catch" exp "end")
398 ("unwind_protect" exp
399 "unwind_protect_cleanup" exp "end_unwind_protect")
400 ("unwind_protect" exp "unwind_protect_cleanup" exp "end")
401 ("for" exp "endfor")
402 ("for" exp "end")
403 ("do" exp "until" atom)
404 ("while" exp "endwhile")
405 ("while" exp "end")
406 ("if" exp "endif")
407 ("if" exp "else" exp "endif")
408 ("if" exp "elseif" exp "else" exp "endif")
409 ("if" exp "elseif" exp "elseif" exp "else" exp "endif")
410 ("if" exp "elseif" exp "elseif" exp "else" exp "end")
411 ("switch" exp "case" exp "endswitch")
412 ("switch" exp "case" exp "otherwise" exp "endswitch")
413 ("switch" exp "case" exp "case" exp "otherwise" exp "endswitch")
414 ("switch" exp "case" exp "case" exp "otherwise" exp "end")
415 ("function" exp "endfunction")
416 ("function" exp "end"))
417 ;; (fundesc (atom "=" atom))
418 ))
419
420 (defconst octave-smie-grammar
421 (smie-prec2->grammar
422 (smie-merge-prec2s
423 (smie-bnf->prec2 octave-smie-bnf-table
424 '((assoc "\n" ";")))
425
426 (smie-precs->prec2 octave-operator-table))))
427
428 ;; Tokenizing needs to be refined so that ";;" is treated as two
429 ;; tokens and also so as to recognize the \n separator (and
430 ;; corresponding continuation lines).
431
432 (defconst octave-operator-regexp
433 (regexp-opt (apply 'append (mapcar 'cdr octave-operator-table))))
434
435 (defun octave-smie-backward-token ()
436 (let ((pos (point)))
437 (forward-comment (- (point)))
438 (cond
439 ((and (not (eq (char-before) ?\;)) ;Coalesce ";" and "\n".
440 (> pos (line-end-position))
441 (if (looking-back octave-continuation-marker-regexp (- (point) 3))
442 (progn
443 (goto-char (match-beginning 0))
444 (forward-comment (- (point)))
445 nil)
446 t)
447 ;; Ignore it if it's within parentheses.
448 (let ((ppss (syntax-ppss)))
449 (not (and (nth 1 ppss)
450 (eq ?\( (char-after (nth 1 ppss)))))))
451 (skip-chars-forward " \t")
452 ;; Why bother distinguishing \n and ;?
453 ";") ;;"\n"
454 ((and (looking-back octave-operator-regexp (- (point) 3) 'greedy)
455 ;; Don't mistake a string quote for a transpose.
456 (not (looking-back "\\s\"" (1- (point)))))
457 (goto-char (match-beginning 0))
458 (match-string-no-properties 0))
459 (t
460 (smie-default-backward-token)))))
461
462 (defun octave-smie-forward-token ()
463 (skip-chars-forward " \t")
464 (when (looking-at (eval-when-compile
465 (concat "\\(" octave-continuation-marker-regexp
466 "\\)[ \t]*\\($\\|[%#]\\)")))
467 (goto-char (match-end 1))
468 (forward-comment 1))
469 (cond
470 ((and (looking-at "$\\|[%#]")
471 (not (smie-rule-bolp))
472 ;; Ignore it if it's within parentheses.
473 (prog1 (let ((ppss (syntax-ppss)))
474 (not (and (nth 1 ppss)
475 (eq ?\( (char-after (nth 1 ppss))))))
476 (forward-comment (point-max))))
477 ;; Why bother distinguishing \n and ;?
478 ";") ;;"\n"
479 ((looking-at ";[ \t]*\\($\\|[%#]\\)")
480 ;; Combine the ; with the subsequent \n.
481 (goto-char (match-beginning 1))
482 (forward-comment 1)
483 ";")
484 ((and (looking-at octave-operator-regexp)
485 ;; Don't mistake a string quote for a transpose.
486 (not (looking-at "\\s\"")))
487 (goto-char (match-end 0))
488 (match-string-no-properties 0))
489 (t
490 (smie-default-forward-token))))
491
492 (defun octave-smie-rules (kind token)
493 (pcase (cons kind token)
494 ;; We could set smie-indent-basic instead, but that would have two
495 ;; disadvantages:
496 ;; - changes to octave-block-offset wouldn't take effect immediately.
497 ;; - edebug wouldn't show the use of this variable.
498 (`(:elem . basic) octave-block-offset)
499 ;; Since "case" is in the same BNF rules as switch..end, SMIE by default
500 ;; aligns it with "switch".
501 (`(:before . "case") (if (not (smie-rule-sibling-p)) octave-block-offset))
502 (`(:after . ";")
503 (if (smie-rule-parent-p "function" "if" "while" "else" "elseif" "for"
504 "otherwise" "case" "try" "catch" "unwind_protect"
505 "unwind_protect_cleanup")
506 (smie-rule-parent octave-block-offset)
507 ;; For (invalid) code between switch and case.
508 ;; (if (smie-parent-p "switch") 4)
509 0))))
510
511 (defvar electric-layout-rules)
512
513 ;;;###autoload
514 (define-derived-mode octave-mode prog-mode "Octave"
515 "Major mode for editing Octave code.
516
517 This mode makes it easier to write Octave code by helping with
518 indentation, doing some of the typing for you (with Abbrev mode) and by
519 showing keywords, comments, strings, etc. in different faces (with
520 Font Lock mode on terminals that support it).
521
522 Octave itself is a high-level language, primarily intended for numerical
523 computations. It provides a convenient command line interface for
524 solving linear and nonlinear problems numerically. Function definitions
525 can also be stored in files, and it can be used in a batch mode (which
526 is why you need this mode!).
527
528 The latest released version of Octave is always available via anonymous
529 ftp from ftp.octave.org in the directory `/pub/octave'. Complete
530 source and binaries for several popular systems are available.
531
532 Type \\[list-abbrevs] to display the built-in abbrevs for Octave keywords.
533
534 Keybindings
535 ===========
536
537 \\{octave-mode-map}
538
539 Variables you can use to customize Octave mode
540 ==============================================
541
542 `octave-blink-matching-block'
543 Non-nil means show matching begin of block when inserting a space,
544 newline or semicolon after an else or end keyword. Default is t.
545
546 `octave-block-offset'
547 Extra indentation applied to statements in block structures.
548 Default is 2.
549
550 `octave-continuation-offset'
551 Extra indentation applied to Octave continuation lines.
552 Default is 4.
553
554 `octave-continuation-string'
555 String used for Octave continuation lines.
556 Default is a backslash.
557
558 `octave-send-echo-input'
559 Non-nil means always display `inferior-octave-buffer' after sending a
560 command to the inferior Octave process.
561
562 `octave-send-line-auto-forward'
563 Non-nil means always go to the next unsent line of Octave code after
564 sending a line to the inferior Octave process.
565
566 `octave-send-echo-input'
567 Non-nil means echo input sent to the inferior Octave process.
568
569 Turning on Octave mode runs the hook `octave-mode-hook'.
570
571 To begin using this mode for all `.m' files that you edit, add the
572 following lines to your init file:
573
574 (add-to-list 'auto-mode-alist '(\"\\\\.m\\\\'\" . octave-mode))
575
576 To automatically turn on the abbrev and auto-fill features,
577 add the following lines to your init file as well:
578
579 (add-hook 'octave-mode-hook
580 (lambda ()
581 (abbrev-mode 1)
582 (auto-fill-mode 1)))
583
584 To submit a problem report, enter \\[octave-submit-bug-report] from \
585 an Octave mode buffer.
586 This automatically sets up a mail buffer with version information
587 already added. You just need to add a description of the problem,
588 including a reproducible test case and send the message."
589 (setq local-abbrev-table octave-abbrev-table)
590
591 (smie-setup octave-smie-grammar #'octave-smie-rules
592 :forward-token #'octave-smie-forward-token
593 :backward-token #'octave-smie-backward-token)
594 (set (make-local-variable 'smie-indent-basic) 'octave-block-offset)
595
596 (set (make-local-variable 'smie-blink-matching-triggers)
597 (cons ?\; smie-blink-matching-triggers))
598 (unless octave-blink-matching-block
599 (remove-hook 'post-self-insert-hook #'smie-blink-matching-open 'local))
600
601 (set (make-local-variable 'electric-indent-chars)
602 (cons ?\; electric-indent-chars))
603 ;; IIUC matlab-mode takes the opposite approach: it makes RET insert
604 ;; a ";" at those places where it's correct (i.e. outside of parens).
605 (set (make-local-variable 'electric-layout-rules) '((?\; . after)))
606
607 (set (make-local-variable 'comment-start) octave-comment-start)
608 (set (make-local-variable 'comment-end) "")
609 ;; Don't set it here: it's not really a property of the language,
610 ;; just a personal preference of the author.
611 ;; (set (make-local-variable 'comment-column) 32)
612 (set (make-local-variable 'comment-start-skip) "\\s<+\\s-*")
613 (set (make-local-variable 'comment-add) 1)
614
615 (set (make-local-variable 'parse-sexp-ignore-comments) t)
616 (set (make-local-variable 'paragraph-start)
617 (concat "\\s-*$\\|" page-delimiter))
618 (set (make-local-variable 'paragraph-separate) paragraph-start)
619 (set (make-local-variable 'paragraph-ignore-fill-prefix) t)
620 (set (make-local-variable 'fill-paragraph-function) 'octave-fill-paragraph)
621 ;; FIXME: Why disable it?
622 ;; (set (make-local-variable 'adaptive-fill-regexp) nil)
623 ;; Again, this is not a property of the language, don't set it here.
624 ;; (set (make-local-variable 'fill-column) 72)
625 (set (make-local-variable 'normal-auto-fill-function) 'octave-auto-fill)
626
627 (set (make-local-variable 'font-lock-defaults)
628 '(octave-font-lock-keywords))
629
630 (set (make-local-variable 'syntax-propertize-function)
631 #'octave-syntax-propertize-function)
632
633 (set (make-local-variable 'imenu-generic-expression)
634 octave-mode-imenu-generic-expression)
635 (set (make-local-variable 'imenu-case-fold-search) nil)
636
637 (add-hook 'completion-at-point-functions
638 'octave-completion-at-point-function nil t)
639 (set (make-local-variable 'beginning-of-defun-function)
640 'octave-beginning-of-defun)
641
642 (easy-menu-add octave-mode-menu)
643 (octave-initialize-completions))
644
645 \f
646 (defcustom inferior-octave-program "octave"
647 "Program invoked by `inferior-octave'."
648 :type 'string
649 :group 'octave)
650
651 (defcustom inferior-octave-buffer "*Inferior Octave*"
652 "Name of buffer for running an inferior Octave process."
653 :type 'string
654 :group 'octave)
655
656 (defcustom inferior-octave-prompt
657 "\\(^octave\\(\\|.bin\\|.exe\\)\\(-[.0-9]+\\)?\\(:[0-9]+\\)?\\|^debug\\|^\\)>+ "
658 "Regexp to match prompts for the inferior Octave process."
659 :type 'regexp
660 :group 'octave)
661
662 (defcustom inferior-octave-startup-file nil
663 "Name of the inferior Octave startup file.
664 The contents of this file are sent to the inferior Octave process on
665 startup."
666 :type '(choice (const :tag "None" nil)
667 file)
668 :group 'octave)
669
670 (defcustom inferior-octave-startup-args nil
671 "List of command line arguments for the inferior Octave process.
672 For example, for suppressing the startup message and using `traditional'
673 mode, set this to (\"-q\" \"--traditional\")."
674 :type '(repeat string)
675 :group 'octave)
676
677 (defcustom inferior-octave-mode-hook nil
678 "Hook to be run when Inferior Octave mode is started."
679 :type 'hook
680 :group 'octave)
681
682 (defvar inferior-octave-process nil)
683
684 (defvar inferior-octave-mode-map
685 (let ((map (make-sparse-keymap)))
686 (set-keymap-parent map comint-mode-map)
687 (define-key map "\t" 'comint-dynamic-complete)
688 (define-key map "\M-?" 'comint-dynamic-list-filename-completions)
689 (define-key map "\C-c\C-l" 'inferior-octave-dynamic-list-input-ring)
690 (define-key map [menu-bar inout list-history]
691 '("List Input History" . inferior-octave-dynamic-list-input-ring))
692 map)
693 "Keymap used in Inferior Octave mode.")
694
695 (defvar inferior-octave-mode-syntax-table
696 (let ((table (make-syntax-table octave-mode-syntax-table)))
697 table)
698 "Syntax table in use in inferior-octave-mode buffers.")
699
700 (defvar inferior-octave-font-lock-keywords
701 (list
702 (cons inferior-octave-prompt 'font-lock-type-face))
703 ;; Could certainly do more font locking in inferior Octave ...
704 "Additional expressions to highlight in Inferior Octave mode.")
705
706
707 ;;; Compatibility functions
708 (if (not (fboundp 'comint-line-beginning-position))
709 ;; comint-line-beginning-position is defined in Emacs 21
710 (defun comint-line-beginning-position ()
711 "Returns the buffer position of the beginning of the line, after any prompt.
712 The prompt is assumed to be any text at the beginning of the line matching
713 the regular expression `comint-prompt-regexp', a buffer local variable."
714 (save-excursion (comint-bol nil) (point))))
715
716
717 (defvar inferior-octave-output-list nil)
718 (defvar inferior-octave-output-string nil)
719 (defvar inferior-octave-receive-in-progress nil)
720
721 (defvar inferior-octave-startup-hook nil)
722
723 (defvar inferior-octave-complete-impossible nil
724 "Non-nil means that `inferior-octave-complete' is impossible.")
725
726 (defvar inferior-octave-has-built-in-variables nil
727 "Non-nil means that Octave has built-in variables.")
728
729 (defvar inferior-octave-dynamic-complete-functions
730 '(inferior-octave-completion-at-point comint-filename-completion)
731 "List of functions called to perform completion for inferior Octave.
732 This variable is used to initialize `comint-dynamic-complete-functions'
733 in the Inferior Octave buffer.")
734
735 (defvar info-lookup-mode)
736
737 (define-derived-mode inferior-octave-mode comint-mode "Inferior Octave"
738 "Major mode for interacting with an inferior Octave process.
739 Runs Octave as a subprocess of Emacs, with Octave I/O through an Emacs
740 buffer.
741
742 Entry to this mode successively runs the hooks `comint-mode-hook' and
743 `inferior-octave-mode-hook'."
744 (setq comint-prompt-regexp inferior-octave-prompt
745 mode-line-process '(":%s")
746 local-abbrev-table octave-abbrev-table)
747
748 (set (make-local-variable 'comment-start) octave-comment-start)
749 (set (make-local-variable 'comment-end) "")
750 (set (make-local-variable 'comment-column) 32)
751 (set (make-local-variable 'comment-start-skip) octave-comment-start-skip)
752
753 (set (make-local-variable 'font-lock-defaults)
754 '(inferior-octave-font-lock-keywords nil nil))
755
756 (set (make-local-variable 'info-lookup-mode) 'octave-mode)
757
758 (setq comint-input-ring-file-name
759 (or (getenv "OCTAVE_HISTFILE") "~/.octave_hist")
760 comint-input-ring-size (or (getenv "OCTAVE_HISTSIZE") 1024))
761 (set (make-local-variable 'comint-dynamic-complete-functions)
762 inferior-octave-dynamic-complete-functions)
763 (add-hook 'comint-input-filter-functions
764 'inferior-octave-directory-tracker nil t)
765 (comint-read-input-ring t))
766
767 ;;;###autoload
768 (defun inferior-octave (&optional arg)
769 "Run an inferior Octave process, I/O via `inferior-octave-buffer'.
770 This buffer is put in Inferior Octave mode. See `inferior-octave-mode'.
771
772 Unless ARG is non-nil, switches to this buffer.
773
774 The elements of the list `inferior-octave-startup-args' are sent as
775 command line arguments to the inferior Octave process on startup.
776
777 Additional commands to be executed on startup can be provided either in
778 the file specified by `inferior-octave-startup-file' or by the default
779 startup file, `~/.emacs-octave'."
780 (interactive "P")
781 (let ((buffer inferior-octave-buffer))
782 (get-buffer-create buffer)
783 (if (comint-check-proc buffer)
784 ()
785 (with-current-buffer buffer
786 (comint-mode)
787 (inferior-octave-startup)
788 (inferior-octave-mode)))
789 (if (not arg)
790 (pop-to-buffer buffer))))
791
792 ;;;###autoload
793 (defalias 'run-octave 'inferior-octave)
794
795 (defun inferior-octave-startup ()
796 "Start an inferior Octave process."
797 (let ((proc (comint-exec-1
798 (substring inferior-octave-buffer 1 -1)
799 inferior-octave-buffer
800 inferior-octave-program
801 (append (list "-i" "--no-line-editing")
802 inferior-octave-startup-args))))
803 (set-process-filter proc 'inferior-octave-output-digest)
804 (setq comint-ptyp process-connection-type
805 inferior-octave-process proc
806 inferior-octave-output-list nil
807 inferior-octave-output-string nil
808 inferior-octave-receive-in-progress t)
809
810 ;; This may look complicated ... However, we need to make sure that
811 ;; we additional startup code only AFTER Octave is ready (otherwise,
812 ;; output may be mixed up). Hence, we need to digest the Octave
813 ;; output to see when it issues a prompt.
814 (while inferior-octave-receive-in-progress
815 (accept-process-output inferior-octave-process))
816 (goto-char (point-max))
817 (set-marker (process-mark proc) (point))
818 (insert-before-markers
819 (concat
820 (if (not (bobp)) "\f\n")
821 (if inferior-octave-output-list
822 (concat (mapconcat
823 'identity inferior-octave-output-list "\n")
824 "\n"))))
825
826 ;; Find out whether Octave has built-in variables.
827 (inferior-octave-send-list-and-digest
828 (list "exist \"LOADPATH\"\n"))
829 (setq inferior-octave-has-built-in-variables
830 (string-match "101$" (car inferior-octave-output-list)))
831
832 ;; An empty secondary prompt, as e.g. obtained by '--braindead',
833 ;; means trouble.
834 (inferior-octave-send-list-and-digest (list "PS2\n"))
835 (if (string-match "\\(PS2\\|ans\\) = *$" (car inferior-octave-output-list))
836 (inferior-octave-send-list-and-digest
837 (list (if inferior-octave-has-built-in-variables
838 "PS2 = \"> \"\n"
839 "PS2 (\"> \");\n"))))
840
841 ;; O.k., now we are ready for the Inferior Octave startup commands.
842 (let* (commands
843 (program (file-name-nondirectory inferior-octave-program))
844 (file (or inferior-octave-startup-file
845 (concat "~/.emacs-" program))))
846 (setq commands
847 (list "more off;\n"
848 (if (not (string-equal
849 inferior-octave-output-string ">> "))
850 (if inferior-octave-has-built-in-variables
851 "PS1=\"\\\\s> \";\n"
852 "PS1 (\"\\\\s> \");\n"))
853 (if (file-exists-p file)
854 (format "source (\"%s\");\n" file))))
855 (inferior-octave-send-list-and-digest commands))
856 (insert-before-markers
857 (concat
858 (if inferior-octave-output-list
859 (concat (mapconcat
860 'identity inferior-octave-output-list "\n")
861 "\n"))
862 inferior-octave-output-string))
863 ;; Next, we check whether Octave supports `completion_matches' ...
864 (inferior-octave-send-list-and-digest
865 (list "exist \"completion_matches\"\n"))
866 (setq inferior-octave-complete-impossible
867 (not (string-match "5$" (car inferior-octave-output-list))))
868
869 ;; And finally, everything is back to normal.
870 (set-process-filter proc 'inferior-octave-output-filter)
871 (run-hooks 'inferior-octave-startup-hook)
872 (run-hooks 'inferior-octave-startup-hook)
873 ;; Just in case, to be sure a cd in the startup file
874 ;; won't have detrimental effects.
875 (inferior-octave-resync-dirs)))
876
877 (defun inferior-octave-completion-at-point ()
878 "Return the data to complete the Octave symbol at point."
879 (let* ((end (point))
880 (start
881 (save-excursion
882 (skip-syntax-backward "w_" (comint-line-beginning-position))
883 (point))))
884 (cond ((eq start end) nil)
885 (inferior-octave-complete-impossible
886 (message (concat
887 "Your Octave does not have `completion_matches'. "
888 "Please upgrade to version 2.X."))
889 nil)
890 (t
891 (list
892 start end
893 (completion-table-dynamic
894 (lambda (command)
895 (inferior-octave-send-list-and-digest
896 (list (concat "completion_matches (\"" command "\");\n")))
897 (sort (delete-dups inferior-octave-output-list)
898 'string-lessp))))))))
899
900 (define-obsolete-function-alias 'inferior-octave-complete
901 'completion-at-point "24.1")
902
903 (defun inferior-octave-dynamic-list-input-ring ()
904 "List the buffer's input history in a help buffer."
905 ;; We cannot use `comint-dynamic-list-input-ring', because it replaces
906 ;; "completion" by "history reference" ...
907 (interactive)
908 (if (or (not (ring-p comint-input-ring))
909 (ring-empty-p comint-input-ring))
910 (message "No history")
911 (let ((history nil)
912 (history-buffer " *Input History*")
913 (index (1- (ring-length comint-input-ring)))
914 (conf (current-window-configuration)))
915 ;; We have to build up a list ourselves from the ring vector.
916 (while (>= index 0)
917 (setq history (cons (ring-ref comint-input-ring index) history)
918 index (1- index)))
919 ;; Change "completion" to "history reference"
920 ;; to make the display accurate.
921 (with-output-to-temp-buffer history-buffer
922 (display-completion-list history)
923 (set-buffer history-buffer))
924 (message "Hit space to flush")
925 (let ((ch (read-event)))
926 (if (eq ch ?\ )
927 (set-window-configuration conf)
928 (setq unread-command-events (list ch)))))))
929
930 (defun inferior-octave-strip-ctrl-g (string)
931 "Strip leading `^G' character.
932 If STRING starts with a `^G', ring the bell and strip it."
933 (if (string-match "^\a" string)
934 (progn
935 (ding)
936 (setq string (substring string 1))))
937 string)
938
939 (defun inferior-octave-output-filter (proc string)
940 "Standard output filter for the inferior Octave process.
941 Ring Emacs bell if process output starts with an ASCII bell, and pass
942 the rest to `comint-output-filter'."
943 (comint-output-filter proc (inferior-octave-strip-ctrl-g string)))
944
945 (defun inferior-octave-output-digest (_proc string)
946 "Special output filter for the inferior Octave process.
947 Save all output between newlines into `inferior-octave-output-list', and
948 the rest to `inferior-octave-output-string'."
949 (setq string (concat inferior-octave-output-string string))
950 (while (string-match "\n" string)
951 (setq inferior-octave-output-list
952 (append inferior-octave-output-list
953 (list (substring string 0 (match-beginning 0))))
954 string (substring string (match-end 0))))
955 (if (string-match inferior-octave-prompt string)
956 (setq inferior-octave-receive-in-progress nil))
957 (setq inferior-octave-output-string string))
958
959 (defun inferior-octave-send-list-and-digest (list)
960 "Send LIST to the inferior Octave process and digest the output.
961 The elements of LIST have to be strings and are sent one by one. All
962 output is passed to the filter `inferior-octave-output-digest'."
963 (let* ((proc inferior-octave-process)
964 (filter (process-filter proc))
965 string)
966 (set-process-filter proc 'inferior-octave-output-digest)
967 (setq inferior-octave-output-list nil)
968 (unwind-protect
969 (while (setq string (car list))
970 (setq inferior-octave-output-string nil
971 inferior-octave-receive-in-progress t)
972 (comint-send-string proc string)
973 (while inferior-octave-receive-in-progress
974 (accept-process-output proc))
975 (setq list (cdr list)))
976 (set-process-filter proc filter))))
977
978 (defun inferior-octave-directory-tracker (string)
979 "Tracks `cd' commands issued to the inferior Octave process.
980 Use \\[inferior-octave-resync-dirs] to resync if Emacs gets confused."
981 (cond
982 ((string-match "^[ \t]*cd[ \t;]*$" string)
983 (cd "~"))
984 ((string-match "^[ \t]*cd[ \t]+\\([^ \t\n;]*\\)[ \t\n;]*" string)
985 (cd (substring string (match-beginning 1) (match-end 1))))))
986
987 (defun inferior-octave-resync-dirs ()
988 "Resync the buffer's idea of the current directory.
989 This command queries the inferior Octave process about its current
990 directory and makes this the current buffer's default directory."
991 (interactive)
992 (inferior-octave-send-list-and-digest '("disp (pwd ())\n"))
993 (cd (car inferior-octave-output-list)))
994
995 \f
996 ;;; Miscellaneous useful functions
997
998 (defsubst octave-in-comment-p ()
999 "Return t if point is inside an Octave comment."
1000 (nth 4 (syntax-ppss)))
1001
1002 (defsubst octave-in-string-p ()
1003 "Return t if point is inside an Octave string."
1004 (nth 3 (syntax-ppss)))
1005
1006 (defsubst octave-not-in-string-or-comment-p ()
1007 "Return t if point is not inside an Octave string or comment."
1008 (let ((pps (syntax-ppss)))
1009 (not (or (nth 3 pps) (nth 4 pps)))))
1010
1011
1012 (defun octave-looking-at-kw (regexp)
1013 "Like `looking-at', but sets `case-fold-search' nil."
1014 (let ((case-fold-search nil))
1015 (looking-at regexp)))
1016
1017 (defun octave-maybe-insert-continuation-string ()
1018 (if (or (octave-in-comment-p)
1019 (save-excursion
1020 (beginning-of-line)
1021 (looking-at octave-continuation-regexp)))
1022 nil
1023 (delete-horizontal-space)
1024 (insert (concat " " octave-continuation-string))))
1025 \f
1026 ;;; Indentation
1027
1028 (defun octave-indent-new-comment-line ()
1029 "Break Octave line at point, continuing comment if within one.
1030 If within code, insert `octave-continuation-string' before breaking the
1031 line. If within a string, signal an error.
1032 The new line is properly indented."
1033 (interactive)
1034 (delete-horizontal-space)
1035 (cond
1036 ((octave-in-comment-p)
1037 (indent-new-comment-line))
1038 ((octave-in-string-p)
1039 (error "Cannot split a code line inside a string"))
1040 (t
1041 (insert (concat " " octave-continuation-string))
1042 (reindent-then-newline-and-indent))))
1043
1044 (defun octave-indent-defun ()
1045 "Properly indent the Octave function which contains point."
1046 (interactive)
1047 (save-excursion
1048 (mark-defun)
1049 (message "Indenting function...")
1050 (indent-region (point) (mark) nil))
1051 (message "Indenting function...done."))
1052
1053 \f
1054 ;;; Motion
1055 (defun octave-next-code-line (&optional arg)
1056 "Move ARG lines of Octave code forward (backward if ARG is negative).
1057 Skips past all empty and comment lines. Default for ARG is 1.
1058
1059 On success, return 0. Otherwise, go as far as possible and return -1."
1060 (interactive "p")
1061 (or arg (setq arg 1))
1062 (beginning-of-line)
1063 (let ((n 0)
1064 (inc (if (> arg 0) 1 -1)))
1065 (while (and (/= arg 0) (= n 0))
1066 (setq n (forward-line inc))
1067 (while (and (= n 0)
1068 (looking-at "\\s-*\\($\\|\\s<\\)"))
1069 (setq n (forward-line inc)))
1070 (setq arg (- arg inc)))
1071 n))
1072
1073 (defun octave-previous-code-line (&optional arg)
1074 "Move ARG lines of Octave code backward (forward if ARG is negative).
1075 Skips past all empty and comment lines. Default for ARG is 1.
1076
1077 On success, return 0. Otherwise, go as far as possible and return -1."
1078 (interactive "p")
1079 (or arg (setq arg 1))
1080 (octave-next-code-line (- arg)))
1081
1082 (defun octave-beginning-of-line ()
1083 "Move point to beginning of current Octave line.
1084 If on an empty or comment line, go to the beginning of that line.
1085 Otherwise, move backward to the beginning of the first Octave code line
1086 which is not inside a continuation statement, i.e., which does not
1087 follow a code line ending in `...' or `\\', or is inside an open
1088 parenthesis list."
1089 (interactive)
1090 (beginning-of-line)
1091 (if (not (looking-at "\\s-*\\($\\|\\s<\\)"))
1092 (while (or (condition-case nil
1093 (progn
1094 (up-list -1)
1095 (beginning-of-line)
1096 t)
1097 (error nil))
1098 (and (or (looking-at "\\s-*\\($\\|\\s<\\)")
1099 (save-excursion
1100 (if (zerop (octave-previous-code-line))
1101 (looking-at octave-continuation-regexp))))
1102 (zerop (forward-line -1)))))))
1103
1104 (defun octave-end-of-line ()
1105 "Move point to end of current Octave line.
1106 If on an empty or comment line, go to the end of that line.
1107 Otherwise, move forward to the end of the first Octave code line which
1108 does not end in `...' or `\\' or is inside an open parenthesis list."
1109 (interactive)
1110 (end-of-line)
1111 (if (save-excursion
1112 (beginning-of-line)
1113 (looking-at "\\s-*\\($\\|\\s<\\)"))
1114 ()
1115 (while (or (condition-case nil
1116 (progn
1117 (up-list 1)
1118 (end-of-line)
1119 t)
1120 (error nil))
1121 (and (save-excursion
1122 (beginning-of-line)
1123 (or (looking-at "\\s-*\\($\\|\\s<\\)")
1124 (looking-at octave-continuation-regexp)))
1125 (zerop (forward-line 1)))))
1126 (end-of-line)))
1127
1128 (defun octave-mark-block ()
1129 "Put point at the beginning of this Octave block, mark at the end.
1130 The block marked is the one that contains point or follows point."
1131 (interactive)
1132 (if (and (looking-at "\\sw\\|\\s_")
1133 (looking-back "\\sw\\|\\s_" (1- (point))))
1134 (skip-syntax-forward "w_"))
1135 (unless (or (looking-at "\\s(")
1136 (save-excursion
1137 (let* ((token (funcall smie-forward-token-function))
1138 (level (assoc token smie-grammar)))
1139 (and level (not (numberp (cadr level)))))))
1140 (backward-up-list 1))
1141 (mark-sexp))
1142
1143 (defun octave-beginning-of-defun (&optional arg)
1144 "Move backward to the beginning of an Octave function.
1145 With positive ARG, do it that many times. Negative argument -N means
1146 move forward to Nth following beginning of a function.
1147 Returns t unless search stops at the beginning or end of the buffer."
1148 (let* ((arg (or arg 1))
1149 (inc (if (> arg 0) 1 -1))
1150 (found nil)
1151 (case-fold-search nil))
1152 (and (not (eobp))
1153 (not (and (> arg 0) (looking-at "\\_<function\\_>")))
1154 (skip-syntax-forward "w"))
1155 (while (and (/= arg 0)
1156 (setq found
1157 (re-search-backward "\\_<function\\_>" inc)))
1158 (if (octave-not-in-string-or-comment-p)
1159 (setq arg (- arg inc))))
1160 (if found
1161 (progn
1162 (and (< inc 0) (goto-char (match-beginning 0)))
1163 t))))
1164
1165 \f
1166 ;;; Filling
1167 (defun octave-auto-fill ()
1168 "Perform auto-fill in Octave mode.
1169 Returns nil if no feasible place to break the line could be found, and t
1170 otherwise."
1171 (let (fc give-up)
1172 (if (or (null (setq fc (current-fill-column)))
1173 (save-excursion
1174 (beginning-of-line)
1175 (and auto-fill-inhibit-regexp
1176 (octave-looking-at-kw auto-fill-inhibit-regexp))))
1177 nil ; Can't do anything
1178 (if (and (not (octave-in-comment-p))
1179 (> (current-column) fc))
1180 (setq fc (- fc (+ (length octave-continuation-string) 1))))
1181 (while (and (not give-up) (> (current-column) fc))
1182 (let* ((opoint (point))
1183 (fpoint
1184 (save-excursion
1185 (move-to-column (+ fc 1))
1186 (skip-chars-backward "^ \t\n")
1187 ;; If we're at the beginning of the line, break after
1188 ;; the first word
1189 (if (bolp)
1190 (re-search-forward "[ \t]" opoint t))
1191 ;; If we're in a comment line, don't break after the
1192 ;; comment chars
1193 (if (save-excursion
1194 (skip-syntax-backward " <")
1195 (bolp))
1196 (re-search-forward "[ \t]" (line-end-position)
1197 'move))
1198 ;; If we're not in a comment line and just ahead the
1199 ;; continuation string, don't break here.
1200 (if (and (not (octave-in-comment-p))
1201 (looking-at
1202 (concat "\\s-*"
1203 (regexp-quote
1204 octave-continuation-string)
1205 "\\s-*$")))
1206 (end-of-line))
1207 (skip-chars-backward " \t")
1208 (point))))
1209 (if (save-excursion
1210 (goto-char fpoint)
1211 (not (or (bolp) (eolp))))
1212 (let ((prev-column (current-column)))
1213 (if (save-excursion
1214 (skip-chars-backward " \t")
1215 (= (point) fpoint))
1216 (progn
1217 (octave-maybe-insert-continuation-string)
1218 (indent-new-comment-line t))
1219 (save-excursion
1220 (goto-char fpoint)
1221 (octave-maybe-insert-continuation-string)
1222 (indent-new-comment-line t)))
1223 (if (>= (current-column) prev-column)
1224 (setq give-up t)))
1225 (setq give-up t))))
1226 (not give-up))))
1227
1228 (defun octave-fill-paragraph (&optional _arg)
1229 "Fill paragraph of Octave code, handling Octave comments."
1230 ;; FIXME: difference with generic fill-paragraph:
1231 ;; - code lines are only split, never joined.
1232 ;; - \n that end comments are never removed.
1233 ;; - insert continuation marker when splitting code lines.
1234 (interactive "P")
1235 (save-excursion
1236 (let ((end (progn (forward-paragraph) (copy-marker (point) t)))
1237 (beg (progn
1238 (forward-paragraph -1)
1239 (skip-chars-forward " \t\n")
1240 (beginning-of-line)
1241 (point)))
1242 (cfc (current-fill-column))
1243 comment-prefix)
1244 (goto-char beg)
1245 (while (< (point) end)
1246 (condition-case nil
1247 (indent-according-to-mode)
1248 (error nil))
1249 (move-to-column cfc)
1250 ;; First check whether we need to combine non-empty comment lines
1251 (if (and (< (current-column) cfc)
1252 (octave-in-comment-p)
1253 (not (save-excursion
1254 (beginning-of-line)
1255 (looking-at "^\\s-*\\s<+\\s-*$"))))
1256 ;; This is a nonempty comment line which does not extend
1257 ;; past the fill column. If it is followed by a nonempty
1258 ;; comment line with the same comment prefix, try to
1259 ;; combine them, and repeat this until either we reach the
1260 ;; fill-column or there is nothing more to combine.
1261 (progn
1262 ;; Get the comment prefix
1263 (save-excursion
1264 (beginning-of-line)
1265 (while (and (re-search-forward "\\s<+")
1266 (not (octave-in-comment-p))))
1267 (setq comment-prefix (match-string 0)))
1268 ;; And keep combining ...
1269 (while (and (< (current-column) cfc)
1270 (save-excursion
1271 (forward-line 1)
1272 (and (looking-at
1273 (concat "^\\s-*"
1274 comment-prefix
1275 "\\S<"))
1276 (not (looking-at
1277 (concat "^\\s-*"
1278 comment-prefix
1279 "\\s-*$"))))))
1280 (delete-char 1)
1281 (re-search-forward comment-prefix)
1282 (delete-region (match-beginning 0) (match-end 0))
1283 (fixup-whitespace)
1284 (move-to-column cfc))))
1285 ;; We might also try to combine continued code lines> Perhaps
1286 ;; some other time ...
1287 (skip-chars-forward "^ \t\n")
1288 (delete-horizontal-space)
1289 (if (or (< (current-column) cfc)
1290 (and (= (current-column) cfc) (eolp)))
1291 (forward-line 1)
1292 (if (not (eolp)) (insert " "))
1293 (or (octave-auto-fill)
1294 (forward-line 1))))
1295 t)))
1296
1297 \f
1298 ;;; Completions
1299 (defun octave-initialize-completions ()
1300 "Create an alist for Octave completions."
1301 (if octave-completion-alist
1302 ()
1303 (setq octave-completion-alist
1304 (append octave-reserved-words
1305 octave-text-functions
1306 octave-variables))))
1307
1308 (defun octave-completion-at-point-function ()
1309 "Find the text to complete and the corresponding table."
1310 (let* ((beg (save-excursion (skip-syntax-backward "w_") (point)))
1311 (end (point)))
1312 (if (< beg (point))
1313 ;; Extend region past point, if applicable.
1314 (save-excursion (skip-syntax-forward "w_")
1315 (setq end (point))))
1316 (list beg end octave-completion-alist)))
1317
1318 (define-obsolete-function-alias 'octave-complete-symbol
1319 'completion-at-point "24.1")
1320 \f
1321 ;;; Electric characters && friends
1322
1323 (defun octave-abbrev-start ()
1324 "Start entering an Octave abbreviation.
1325 If Abbrev mode is turned on, typing ` (grave accent) followed by ? or
1326 \\[help-command] lists all Octave abbrevs. Any other key combination is
1327 executed normally.
1328 Note that all Octave mode abbrevs start with a grave accent."
1329 (interactive)
1330 (self-insert-command 1)
1331 (when abbrev-mode
1332 (set-temporary-overlay-map
1333 (let ((map (make-sparse-keymap)))
1334 (define-key map [??] 'list-abbrevs)
1335 (define-key map (vector help-char) 'list-abbrevs)
1336 map))))
1337
1338 (define-skeleton octave-insert-defun
1339 "Insert an Octave function skeleton.
1340 Prompt for the function's name, arguments and return values (to be
1341 entered without parens)."
1342 (let* ((defname (substring (buffer-name) 0 -2))
1343 (name (read-string (format "Function name (default %s): " defname)
1344 nil nil defname))
1345 (args (read-string "Arguments: "))
1346 (vals (read-string "Return values: ")))
1347 (format "%s%s (%s)"
1348 (cond
1349 ((string-equal vals "") vals)
1350 ((string-match "[ ,]" vals) (concat "[" vals "] = "))
1351 (t (concat vals " = ")))
1352 name
1353 args))
1354 \n "function " > str \n \n
1355 octave-block-comment-start "usage: " str \n
1356 octave-block-comment-start \n octave-block-comment-start
1357 \n _ \n
1358 "endfunction" > \n)
1359 \f
1360 ;;; Communication with the inferior Octave process
1361 (defun octave-kill-process ()
1362 "Kill inferior Octave process and its buffer."
1363 (interactive)
1364 (if inferior-octave-process
1365 (progn
1366 (process-send-string inferior-octave-process "quit;\n")
1367 (accept-process-output inferior-octave-process)))
1368 (if inferior-octave-buffer
1369 (kill-buffer inferior-octave-buffer)))
1370
1371 (defun octave-show-process-buffer ()
1372 "Make sure that `inferior-octave-buffer' is displayed."
1373 (interactive)
1374 (if (get-buffer inferior-octave-buffer)
1375 (display-buffer inferior-octave-buffer)
1376 (message "No buffer named %s" inferior-octave-buffer)))
1377
1378 (defun octave-hide-process-buffer ()
1379 "Delete all windows that display `inferior-octave-buffer'."
1380 (interactive)
1381 (if (get-buffer inferior-octave-buffer)
1382 (delete-windows-on inferior-octave-buffer)
1383 (message "No buffer named %s" inferior-octave-buffer)))
1384
1385 (defun octave-send-region (beg end)
1386 "Send current region to the inferior Octave process."
1387 (interactive "r")
1388 (inferior-octave t)
1389 (let ((proc inferior-octave-process)
1390 (string (buffer-substring-no-properties beg end))
1391 line)
1392 (with-current-buffer inferior-octave-buffer
1393 (setq inferior-octave-output-list nil)
1394 (while (not (string-equal string ""))
1395 (if (string-match "\n" string)
1396 (setq line (substring string 0 (match-beginning 0))
1397 string (substring string (match-end 0)))
1398 (setq line string string ""))
1399 (setq inferior-octave-receive-in-progress t)
1400 (inferior-octave-send-list-and-digest (list (concat line "\n")))
1401 (while inferior-octave-receive-in-progress
1402 (accept-process-output proc))
1403 (insert-before-markers
1404 (mapconcat 'identity
1405 (append
1406 (if octave-send-echo-input (list line) (list ""))
1407 (mapcar 'inferior-octave-strip-ctrl-g
1408 inferior-octave-output-list)
1409 (list inferior-octave-output-string))
1410 "\n")))))
1411 (if octave-send-show-buffer
1412 (display-buffer inferior-octave-buffer)))
1413
1414 (defun octave-send-block ()
1415 "Send current Octave block to the inferior Octave process."
1416 (interactive)
1417 (save-excursion
1418 (octave-mark-block)
1419 (octave-send-region (point) (mark))))
1420
1421 (defun octave-send-defun ()
1422 "Send current Octave function to the inferior Octave process."
1423 (interactive)
1424 (save-excursion
1425 (mark-defun)
1426 (octave-send-region (point) (mark))))
1427
1428 (defun octave-send-line (&optional arg)
1429 "Send current Octave code line to the inferior Octave process.
1430 With positive prefix ARG, send that many lines.
1431 If `octave-send-line-auto-forward' is non-nil, go to the next unsent
1432 code line."
1433 (interactive "P")
1434 (or arg (setq arg 1))
1435 (if (> arg 0)
1436 (let (beg end)
1437 (beginning-of-line)
1438 (setq beg (point))
1439 (octave-next-code-line (- arg 1))
1440 (end-of-line)
1441 (setq end (point))
1442 (if octave-send-line-auto-forward
1443 (octave-next-code-line 1))
1444 (octave-send-region beg end))))
1445
1446 (defun octave-eval-print-last-sexp ()
1447 "Evaluate Octave sexp before point and print value into current buffer."
1448 (interactive)
1449 (inferior-octave t)
1450 (let ((standard-output (current-buffer))
1451 (print-escape-newlines nil)
1452 (opoint (point)))
1453 (terpri)
1454 (prin1
1455 (save-excursion
1456 (forward-sexp -1)
1457 (inferior-octave-send-list-and-digest
1458 (list (concat (buffer-substring-no-properties (point) opoint)
1459 "\n")))
1460 (mapconcat 'identity inferior-octave-output-list "\n")))
1461 (terpri)))
1462 \f
1463 ;;; Bug reporting
1464 (defun octave-submit-bug-report ()
1465 "Submit a bug report on the Emacs Octave package via mail."
1466 (interactive)
1467 (require 'reporter)
1468 (and
1469 (y-or-n-p "Do you want to submit a bug report? ")
1470 (reporter-submit-bug-report
1471 octave-maintainer-address
1472 (concat "Emacs version " emacs-version)
1473 (list
1474 'octave-blink-matching-block
1475 'octave-block-offset
1476 'octave-comment-char
1477 'octave-continuation-offset
1478 'octave-continuation-string
1479 'octave-send-echo-input
1480 'octave-send-line-auto-forward
1481 'octave-send-show-buffer))))
1482
1483 (provide 'octave)
1484 ;;; octave.el ends here