* textmodes/reftex-vars.el
[bpt/emacs.git] / lisp / progmodes / octave-mod.el
1 ;;; octave-mod.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.
28 ;; It defines Octave mode, a major mode for editing
29 ;; Octave code.
30
31 ;; The file octave-inf.el contains code for interacting with an inferior
32 ;; Octave process using comint.
33
34 ;; See the documentation of `octave-mode' and
35 ;; `run-octave' for further information on usage and customization.
36
37 ;;; Code:
38 (require 'custom)
39
40 (defgroup octave nil
41 "Major mode for editing Octave source files."
42 :link '(custom-group-link :tag "Font Lock Faces group" font-lock-faces)
43 :group 'languages)
44
45 (defvar inferior-octave-output-list nil)
46 (defvar inferior-octave-output-string nil)
47 (defvar inferior-octave-receive-in-progress nil)
48
49 (declare-function inferior-octave-send-list-and-digest "octave-inf" (list))
50
51 (defconst octave-maintainer-address
52 "Kurt Hornik <Kurt.Hornik@wu-wien.ac.at>, bug-gnu-emacs@gnu.org"
53 "Current maintainer of the Emacs Octave package.")
54
55 (define-abbrev-table 'octave-abbrev-table
56 (mapcar (lambda (e) (append e '(nil 0 t)))
57 '(("`a" "all_va_args")
58 ("`b" "break")
59 ("`cs" "case")
60 ("`ca" "catch")
61 ("`c" "continue")
62 ("`el" "else")
63 ("`eli" "elseif")
64 ("`et" "end_try_catch")
65 ("`eu" "end_unwind_protect")
66 ("`ef" "endfor")
67 ("`efu" "endfunction")
68 ("`ei" "endif")
69 ("`es" "endswitch")
70 ("`ew" "endwhile")
71 ("`f" "for")
72 ("`fu" "function")
73 ("`gl" "global")
74 ("`gp" "gplot")
75 ("`gs" "gsplot")
76 ("`if" "if ()")
77 ("`o" "otherwise")
78 ("`rp" "replot")
79 ("`r" "return")
80 ("`s" "switch")
81 ("`t" "try")
82 ("`u" "until ()")
83 ("`up" "unwind_protect")
84 ("`upc" "unwind_protect_cleanup")
85 ("`w" "while ()")))
86 "Abbrev table for Octave's reserved words.
87 Used in `octave-mode' and inferior-octave-mode buffers.
88 All Octave abbrevs start with a grave accent (`)."
89 :regexp "\\(?:[^`]\\|^\\)\\(\\(?:\\<\\|`\\)\\w+\\)\\W*")
90
91 (defvar octave-comment-char ?#
92 "Character to start an Octave comment.")
93 (defvar octave-comment-start
94 (string octave-comment-char ?\s)
95 "String to insert to start a new Octave in-line comment.")
96 (defvar octave-comment-start-skip "\\s<+\\s-*"
97 "Regexp to match the start of an Octave comment up to its body.")
98
99 (defvar octave-begin-keywords
100 '("do" "for" "function" "if" "switch" "try" "unwind_protect" "while"))
101 (defvar octave-else-keywords
102 '("case" "catch" "else" "elseif" "otherwise" "unwind_protect_cleanup"))
103 (defvar octave-end-keywords
104 '("endfor" "endfunction" "endif" "endswitch" "end_try_catch"
105 "end_unwind_protect" "endwhile" "until" "end"))
106
107 (defvar octave-reserved-words
108 (append octave-begin-keywords
109 octave-else-keywords
110 octave-end-keywords
111 '("break" "continue" "end" "global" "persistent" "return"))
112 "Reserved words in Octave.")
113
114 (defvar octave-text-functions
115 '("casesen" "cd" "chdir" "clear" "diary" "dir" "document" "echo"
116 "edit_history" "format" "help" "history" "hold"
117 "load" "ls" "more" "run_history" "save" "type"
118 "which" "who" "whos")
119 "Text functions in Octave.")
120
121 (defvar octave-variables
122 '("DEFAULT_EXEC_PATH" "DEFAULT_LOADPATH"
123 "EDITOR" "EXEC_PATH" "F_DUPFD" "F_GETFD" "F_GETFL" "F_SETFD"
124 "F_SETFL" "I" "IMAGE_PATH" "Inf" "J"
125 "NaN" "OCTAVE_VERSION" "O_APPEND" "O_CREAT" "O_EXCL"
126 "O_NONBLOCK" "O_RDONLY" "O_RDWR" "O_TRUNC" "O_WRONLY" "PAGER" "PS1"
127 "PS2" "PS4" "PWD" "SEEK_CUR" "SEEK_END" "SEEK_SET" "__F_DUPFD__"
128 "__F_GETFD__" "__F_GETFL__" "__F_SETFD__" "__F_SETFL__" "__I__"
129 "__Inf__" "__J__" "__NaN__" "__OCTAVE_VERSION__" "__O_APPEND__"
130 "__O_CREAT__" "__O_EXCL__" "__O_NONBLOCK__" "__O_RDONLY__"
131 "__O_RDWR__" "__O_TRUNC__" "__O_WRONLY__" "__PWD__" "__SEEK_CUR__"
132 "__SEEK_END__" "__SEEK_SET__" "__argv__" "__e__" "__eps__"
133 "__i__" "__inf__" "__j__" "__nan__" "__pi__"
134 "__program_invocation_name__" "__program_name__" "__realmax__"
135 "__realmin__" "__stderr__" "__stdin__" "__stdout__" "ans" "argv"
136 "beep_on_error" "completion_append_char"
137 "crash_dumps_octave_core" "default_save_format"
138 "e" "echo_executing_commands" "eps"
139 "error_text" "gnuplot_binary" "history_file"
140 "history_size" "ignore_function_time_stamp"
141 "inf" "nan" "nargin" "output_max_field_width" "output_precision"
142 "page_output_immediately" "page_screen_output" "pi"
143 "print_answer_id_name" "print_empty_dimensions"
144 "program_invocation_name" "program_name"
145 "realmax" "realmin" "return_last_computed_value" "save_precision"
146 "saving_history" "sighup_dumps_octave_core" "sigterm_dumps_octave_core"
147 "silent_functions" "split_long_rows" "stderr" "stdin" "stdout"
148 "string_fill_char" "struct_levels_to_print"
149 "suppress_verbose_help_message")
150 "Builtin variables in Octave.")
151
152 (defvar octave-function-header-regexp
153 (concat "^\\s-*\\_<\\(function\\)\\_>"
154 "\\([^=;\n]*=[ \t]*\\|[ \t]*\\)\\(\\(?:\\w\\|\\s_\\)+\\)\\_>")
155 "Regexp to match an Octave function header.
156 The string `function' and its name are given by the first and third
157 parenthetical grouping.")
158
159 (defvar octave-font-lock-keywords
160 (list
161 ;; Fontify all builtin keywords.
162 (cons (concat "\\_<\\("
163 (regexp-opt (append octave-reserved-words
164 octave-text-functions))
165 "\\)\\_>")
166 'font-lock-keyword-face)
167 ;; Fontify all builtin operators.
168 (cons "\\(&\\||\\|<=\\|>=\\|==\\|<\\|>\\|!=\\|!\\)"
169 (if (boundp 'font-lock-builtin-face)
170 'font-lock-builtin-face
171 'font-lock-preprocessor-face))
172 ;; Fontify all builtin variables.
173 (cons (concat "\\_<" (regexp-opt octave-variables) "\\_>")
174 'font-lock-variable-name-face)
175 ;; Fontify all function declarations.
176 (list octave-function-header-regexp
177 '(1 font-lock-keyword-face)
178 '(3 font-lock-function-name-face nil t)))
179 "Additional Octave expressions to highlight.")
180
181 (defun octave-syntax-propertize-function (start end)
182 (goto-char start)
183 (octave-syntax-propertize-sqs end)
184 (funcall (syntax-propertize-rules
185 ;; Try to distinguish the string-quotes from the transpose-quotes.
186 ("[[({,; ]\\('\\)"
187 (1 (prog1 "\"'" (octave-syntax-propertize-sqs end)))))
188 (point) end))
189
190 (defun octave-syntax-propertize-sqs (end)
191 "Propertize the content/end of single-quote strings."
192 (when (eq (nth 3 (syntax-ppss)) ?\')
193 ;; A '..' string.
194 (when (re-search-forward
195 "\\(?:\\=\\|[^']\\)\\(?:''\\)*\\('\\)\\($\\|[^']\\)" end 'move)
196 (goto-char (match-beginning 2))
197 (when (eq (char-before (match-beginning 1)) ?\\)
198 ;; Backslash cannot escape a single quote.
199 (put-text-property (1- (match-beginning 1)) (match-beginning 1)
200 'syntax-table (string-to-syntax ".")))
201 (put-text-property (match-beginning 1) (match-end 1)
202 'syntax-table (string-to-syntax "\"'")))))
203
204 (defcustom inferior-octave-buffer "*Inferior Octave*"
205 "Name of buffer for running an inferior Octave process."
206 :type 'string
207 :group 'octave-inferior)
208
209 (defvar inferior-octave-process nil)
210 \f
211 (defvar octave-mode-map
212 (let ((map (make-sparse-keymap)))
213 (define-key map "`" 'octave-abbrev-start)
214 (define-key map "\e\n" 'octave-indent-new-comment-line)
215 (define-key map "\M-\C-q" 'octave-indent-defun)
216 (define-key map "\C-c\C-b" 'octave-submit-bug-report)
217 (define-key map "\C-c\C-p" 'octave-previous-code-line)
218 (define-key map "\C-c\C-n" 'octave-next-code-line)
219 (define-key map "\C-c\C-a" 'octave-beginning-of-line)
220 (define-key map "\C-c\C-e" 'octave-end-of-line)
221 (define-key map [remap down-list] 'smie-down-list)
222 (define-key map "\C-c\M-\C-h" 'octave-mark-block)
223 (define-key map "\C-c]" 'smie-close-block)
224 (define-key map "\C-c/" 'smie-close-block)
225 (define-key map "\C-c\C-f" 'octave-insert-defun)
226 (define-key map "\C-c\C-il" 'octave-send-line)
227 (define-key map "\C-c\C-ib" 'octave-send-block)
228 (define-key map "\C-c\C-if" 'octave-send-defun)
229 (define-key map "\C-c\C-ir" 'octave-send-region)
230 (define-key map "\C-c\C-is" 'octave-show-process-buffer)
231 (define-key map "\C-c\C-iq" 'octave-hide-process-buffer)
232 (define-key map "\C-c\C-ik" 'octave-kill-process)
233 (define-key map "\C-c\C-i\C-l" 'octave-send-line)
234 (define-key map "\C-c\C-i\C-b" 'octave-send-block)
235 (define-key map "\C-c\C-i\C-f" 'octave-send-defun)
236 (define-key map "\C-c\C-i\C-r" 'octave-send-region)
237 (define-key map "\C-c\C-i\C-s" 'octave-show-process-buffer)
238 (define-key map "\C-c\C-i\C-q" 'octave-hide-process-buffer)
239 (define-key map "\C-c\C-i\C-k" 'octave-kill-process)
240 map)
241 "Keymap used in Octave mode.")
242
243
244
245 (easy-menu-define octave-mode-menu octave-mode-map
246 "Menu for Octave mode."
247 '("Octave"
248 ("Lines"
249 ["Previous Code Line" octave-previous-code-line t]
250 ["Next Code Line" octave-next-code-line t]
251 ["Begin of Continuation" octave-beginning-of-line t]
252 ["End of Continuation" octave-end-of-line t]
253 ["Split Line at Point" octave-indent-new-comment-line t])
254 ("Blocks"
255 ["Mark Block" octave-mark-block t]
256 ["Close Block" smie-close-block t])
257 ("Functions"
258 ["Indent Function" octave-indent-defun t]
259 ["Insert Function" octave-insert-defun t])
260 "-"
261 ("Debug"
262 ["Send Current Line" octave-send-line t]
263 ["Send Current Block" octave-send-block t]
264 ["Send Current Function" octave-send-defun t]
265 ["Send Region" octave-send-region t]
266 ["Show Process Buffer" octave-show-process-buffer t]
267 ["Hide Process Buffer" octave-hide-process-buffer t]
268 ["Kill Process" octave-kill-process t])
269 "-"
270 ["Indent Line" indent-according-to-mode t]
271 ["Complete Symbol" completion-at-point t]
272 "-"
273 ["Toggle Abbrev Mode" abbrev-mode
274 :style toggle :selected abbrev-mode]
275 ["Toggle Auto-Fill Mode" auto-fill-mode
276 :style toggle :selected auto-fill-function]
277 "-"
278 ["Submit Bug Report" octave-submit-bug-report t]
279 "-"
280 ["Describe Octave Mode" describe-mode t]
281 ["Lookup Octave Index" info-lookup-symbol t]))
282
283 (defvar octave-mode-syntax-table
284 (let ((table (make-syntax-table)))
285 (modify-syntax-entry ?\r " " table)
286 (modify-syntax-entry ?+ "." table)
287 (modify-syntax-entry ?- "." table)
288 (modify-syntax-entry ?= "." table)
289 (modify-syntax-entry ?* "." table)
290 (modify-syntax-entry ?/ "." table)
291 (modify-syntax-entry ?> "." table)
292 (modify-syntax-entry ?< "." table)
293 (modify-syntax-entry ?& "." table)
294 (modify-syntax-entry ?| "." table)
295 (modify-syntax-entry ?! "." table)
296 (modify-syntax-entry ?\\ "\\" table)
297 (modify-syntax-entry ?\' "." table)
298 ;; Was "w" for abbrevs, but now that it's not necessary any more,
299 (modify-syntax-entry ?\` "." table)
300 (modify-syntax-entry ?\" "\"" table)
301 (modify-syntax-entry ?. "_" table)
302 (modify-syntax-entry ?_ "_" table)
303 ;; The "b" flag only applies to the second letter of the comstart
304 ;; and the first letter of the comend, i.e. the "4b" below is ineffective.
305 ;; If we try to put `b' on the single-line comments, we get a similar
306 ;; problem where the % and # chars appear as first chars of the 2-char
307 ;; comend, so the multi-line ender is also turned into style-b.
308 ;; So we need the new "c" comment style.
309 (modify-syntax-entry ?\% "< 13" table)
310 (modify-syntax-entry ?\# "< 13" table)
311 (modify-syntax-entry ?\{ "(} 2c" table)
312 (modify-syntax-entry ?\} "){ 4c" table)
313 (modify-syntax-entry ?\n ">" table)
314 table)
315 "Syntax table in use in `octave-mode' buffers.")
316
317 (defcustom octave-blink-matching-block t
318 "Control the blinking of matching Octave block keywords.
319 Non-nil means show matching begin of block when inserting a space,
320 newline or semicolon after an else or end keyword."
321 :type 'boolean
322 :group 'octave)
323
324 (defcustom octave-block-offset 2
325 "Extra indentation applied to statements in Octave block structures."
326 :type 'integer
327 :group 'octave)
328
329 (defvar octave-block-comment-start
330 (concat (make-string 2 octave-comment-char) " ")
331 "String to insert to start a new Octave comment on an empty line.")
332
333 (defcustom octave-continuation-offset 4
334 "Extra indentation applied to Octave continuation lines."
335 :type 'integer
336 :group 'octave)
337 (eval-and-compile
338 (defconst octave-continuation-marker-regexp "\\\\\\|\\.\\.\\."))
339 (defvar octave-continuation-regexp
340 (concat "[^#%\n]*\\(" octave-continuation-marker-regexp
341 "\\)\\s-*\\(\\s<.*\\)?$"))
342 (defcustom octave-continuation-string "\\"
343 "Character string used for Octave continuation lines. Normally \\."
344 :type 'string
345 :group 'octave)
346
347 (defvar octave-completion-alist nil
348 "Alist of Octave symbols for completion in Octave mode.
349 Each element looks like (VAR . VAR), where the car and cdr are the same
350 symbol (an Octave command or variable name).
351 Currently, only builtin variables can be completed.")
352
353 (defvar octave-mode-imenu-generic-expression
354 (list
355 ;; Functions
356 (list nil octave-function-header-regexp 3))
357 "Imenu expression for Octave mode. See `imenu-generic-expression'.")
358
359 (defcustom octave-mode-hook nil
360 "Hook to be run when Octave mode is started."
361 :type 'hook
362 :group 'octave)
363
364 (defcustom octave-send-show-buffer t
365 "Non-nil means display `inferior-octave-buffer' after sending to it."
366 :type 'boolean
367 :group 'octave)
368 (defcustom octave-send-line-auto-forward t
369 "Control auto-forward after sending to the inferior Octave process.
370 Non-nil means always go to the next Octave code line after sending."
371 :type 'boolean
372 :group 'octave)
373 (defcustom octave-send-echo-input t
374 "Non-nil means echo input sent to the inferior Octave process."
375 :type 'boolean
376 :group 'octave)
377
378 \f
379 ;;; SMIE indentation
380
381 (require 'smie)
382
383 (defconst octave-operator-table
384 '((assoc ";" "\n") (assoc ",") ; The doc claims they have equal precedence!?
385 (right "=" "+=" "-=" "*=" "/=")
386 (assoc "&&") (assoc "||") ; The doc claims they have equal precedence!?
387 (assoc "&") (assoc "|") ; The doc claims they have equal precedence!?
388 (nonassoc "<" "<=" "==" ">=" ">" "!=" "~=")
389 (nonassoc ":") ;No idea what this is.
390 (assoc "+" "-")
391 (assoc "*" "/" "\\" ".\\" ".*" "./")
392 (nonassoc "'" ".'")
393 (nonassoc "++" "--" "!" "~") ;And unary "+" and "-".
394 (right "^" "**" ".^" ".**")
395 ;; It's not really an operator, but for indentation purposes it
396 ;; could be convenient to treat it as one.
397 (assoc "...")))
398
399 (defconst octave-smie-bnf-table
400 '((atom)
401 ;; We can't distinguish the first element in a sequence with
402 ;; precedence grammars, so we can't distinguish the condition
403 ;; if the `if' from the subsequent body, for example.
404 ;; This has to be done later in the indentation rules.
405 (exp (exp "\n" exp)
406 ;; We need to mention at least one of the operators in this part
407 ;; of the grammar: if the BNF and the operator table have
408 ;; no overlap, SMIE can't know how they relate.
409 (exp ";" exp)
410 ("try" exp "catch" exp "end_try_catch")
411 ("try" exp "catch" exp "end")
412 ("unwind_protect" exp
413 "unwind_protect_cleanup" exp "end_unwind_protect")
414 ("unwind_protect" exp "unwind_protect_cleanup" exp "end")
415 ("for" exp "endfor")
416 ("for" exp "end")
417 ("do" exp "until" atom)
418 ("while" exp "endwhile")
419 ("while" exp "end")
420 ("if" exp "endif")
421 ("if" exp "else" exp "endif")
422 ("if" exp "elseif" exp "else" exp "endif")
423 ("if" exp "elseif" exp "elseif" exp "else" exp "endif")
424 ("if" exp "elseif" exp "elseif" exp "else" exp "end")
425 ("switch" exp "case" exp "endswitch")
426 ("switch" exp "case" exp "otherwise" exp "endswitch")
427 ("switch" exp "case" exp "case" exp "otherwise" exp "endswitch")
428 ("switch" exp "case" exp "case" exp "otherwise" exp "end")
429 ("function" exp "endfunction")
430 ("function" exp "end"))
431 ;; (fundesc (atom "=" atom))
432 ))
433
434 (defconst octave-smie-grammar
435 (smie-prec2->grammar
436 (smie-merge-prec2s
437 (smie-bnf->prec2 octave-smie-bnf-table
438 '((assoc "\n" ";")))
439
440 (smie-precs->prec2 octave-operator-table))))
441
442 ;; Tokenizing needs to be refined so that ";;" is treated as two
443 ;; tokens and also so as to recognize the \n separator (and
444 ;; corresponding continuation lines).
445
446 (defconst octave-operator-regexp
447 (regexp-opt (apply 'append (mapcar 'cdr octave-operator-table))))
448
449 (defun octave-smie-backward-token ()
450 (let ((pos (point)))
451 (forward-comment (- (point)))
452 (cond
453 ((and (not (eq (char-before) ?\;)) ;Coalesce ";" and "\n".
454 (> pos (line-end-position))
455 (if (looking-back octave-continuation-marker-regexp (- (point) 3))
456 (progn
457 (goto-char (match-beginning 0))
458 (forward-comment (- (point)))
459 nil)
460 t)
461 ;; Ignore it if it's within parentheses.
462 (let ((ppss (syntax-ppss)))
463 (not (and (nth 1 ppss)
464 (eq ?\( (char-after (nth 1 ppss)))))))
465 (skip-chars-forward " \t")
466 ;; Why bother distinguishing \n and ;?
467 ";") ;;"\n"
468 ((and (looking-back octave-operator-regexp (- (point) 3) 'greedy)
469 ;; Don't mistake a string quote for a transpose.
470 (not (looking-back "\\s\"" (1- (point)))))
471 (goto-char (match-beginning 0))
472 (match-string-no-properties 0))
473 (t
474 (smie-default-backward-token)))))
475
476 (defun octave-smie-forward-token ()
477 (skip-chars-forward " \t")
478 (when (looking-at (eval-when-compile
479 (concat "\\(" octave-continuation-marker-regexp
480 "\\)[ \t]*\\($\\|[%#]\\)")))
481 (goto-char (match-end 1))
482 (forward-comment 1))
483 (cond
484 ((and (looking-at "$\\|[%#]")
485 (not (smie-rule-bolp))
486 ;; Ignore it if it's within parentheses.
487 (prog1 (let ((ppss (syntax-ppss)))
488 (not (and (nth 1 ppss)
489 (eq ?\( (char-after (nth 1 ppss))))))
490 (forward-comment (point-max))))
491 ;; Why bother distinguishing \n and ;?
492 ";") ;;"\n"
493 ((looking-at ";[ \t]*\\($\\|[%#]\\)")
494 ;; Combine the ; with the subsequent \n.
495 (goto-char (match-beginning 1))
496 (forward-comment 1)
497 ";")
498 ((and (looking-at octave-operator-regexp)
499 ;; Don't mistake a string quote for a transpose.
500 (not (looking-at "\\s\"")))
501 (goto-char (match-end 0))
502 (match-string-no-properties 0))
503 (t
504 (smie-default-forward-token))))
505
506 (defun octave-smie-rules (kind token)
507 (pcase (cons kind token)
508 ;; We could set smie-indent-basic instead, but that would have two
509 ;; disadvantages:
510 ;; - changes to octave-block-offset wouldn't take effect immediately.
511 ;; - edebug wouldn't show the use of this variable.
512 (`(:elem . basic) octave-block-offset)
513 ;; Since "case" is in the same BNF rules as switch..end, SMIE by default
514 ;; aligns it with "switch".
515 (`(:before . "case") (if (not (smie-rule-sibling-p)) octave-block-offset))
516 (`(:after . ";")
517 (if (smie-rule-parent-p "function" "if" "while" "else" "elseif" "for"
518 "otherwise" "case" "try" "catch" "unwind_protect"
519 "unwind_protect_cleanup")
520 (smie-rule-parent octave-block-offset)
521 ;; For (invalid) code between switch and case.
522 ;; (if (smie-parent-p "switch") 4)
523 0))))
524
525 (defvar electric-layout-rules)
526
527 ;;;###autoload
528 (define-derived-mode octave-mode prog-mode "Octave"
529 "Major mode for editing Octave code.
530
531 This mode makes it easier to write Octave code by helping with
532 indentation, doing some of the typing for you (with Abbrev mode) and by
533 showing keywords, comments, strings, etc. in different faces (with
534 Font Lock mode on terminals that support it).
535
536 Octave itself is a high-level language, primarily intended for numerical
537 computations. It provides a convenient command line interface for
538 solving linear and nonlinear problems numerically. Function definitions
539 can also be stored in files, and it can be used in a batch mode (which
540 is why you need this mode!).
541
542 The latest released version of Octave is always available via anonymous
543 ftp from ftp.octave.org in the directory `/pub/octave'. Complete
544 source and binaries for several popular systems are available.
545
546 Type \\[list-abbrevs] to display the built-in abbrevs for Octave keywords.
547
548 Keybindings
549 ===========
550
551 \\{octave-mode-map}
552
553 Variables you can use to customize Octave mode
554 ==============================================
555
556 `octave-blink-matching-block'
557 Non-nil means show matching begin of block when inserting a space,
558 newline or semicolon after an else or end keyword. Default is t.
559
560 `octave-block-offset'
561 Extra indentation applied to statements in block structures.
562 Default is 2.
563
564 `octave-continuation-offset'
565 Extra indentation applied to Octave continuation lines.
566 Default is 4.
567
568 `octave-continuation-string'
569 String used for Octave continuation lines.
570 Default is a backslash.
571
572 `octave-send-echo-input'
573 Non-nil means always display `inferior-octave-buffer' after sending a
574 command to the inferior Octave process.
575
576 `octave-send-line-auto-forward'
577 Non-nil means always go to the next unsent line of Octave code after
578 sending a line to the inferior Octave process.
579
580 `octave-send-echo-input'
581 Non-nil means echo input sent to the inferior Octave process.
582
583 Turning on Octave mode runs the hook `octave-mode-hook'.
584
585 To begin using this mode for all `.m' files that you edit, add the
586 following lines to your init file:
587
588 (add-to-list 'auto-mode-alist '(\"\\\\.m\\\\'\" . octave-mode))
589
590 To automatically turn on the abbrev and auto-fill features,
591 add the following lines to your init file as well:
592
593 (add-hook 'octave-mode-hook
594 (lambda ()
595 (abbrev-mode 1)
596 (auto-fill-mode 1)))
597
598 To submit a problem report, enter \\[octave-submit-bug-report] from \
599 an Octave mode buffer.
600 This automatically sets up a mail buffer with version information
601 already added. You just need to add a description of the problem,
602 including a reproducible test case and send the message."
603 (setq local-abbrev-table octave-abbrev-table)
604
605 (smie-setup octave-smie-grammar #'octave-smie-rules
606 :forward-token #'octave-smie-forward-token
607 :backward-token #'octave-smie-backward-token)
608 (set (make-local-variable 'smie-indent-basic) 'octave-block-offset)
609
610 (set (make-local-variable 'smie-blink-matching-triggers)
611 (cons ?\; smie-blink-matching-triggers))
612 (unless octave-blink-matching-block
613 (remove-hook 'post-self-insert-hook #'smie-blink-matching-open 'local))
614
615 (set (make-local-variable 'electric-indent-chars)
616 (cons ?\; electric-indent-chars))
617 ;; IIUC matlab-mode takes the opposite approach: it makes RET insert
618 ;; a ";" at those places where it's correct (i.e. outside of parens).
619 (set (make-local-variable 'electric-layout-rules) '((?\; . after)))
620
621 (set (make-local-variable 'comment-start) octave-comment-start)
622 (set (make-local-variable 'comment-end) "")
623 ;; Don't set it here: it's not really a property of the language,
624 ;; just a personal preference of the author.
625 ;; (set (make-local-variable 'comment-column) 32)
626 (set (make-local-variable 'comment-start-skip) "\\s<+\\s-*")
627 (set (make-local-variable 'comment-add) 1)
628
629 (set (make-local-variable 'parse-sexp-ignore-comments) t)
630 (set (make-local-variable 'paragraph-start)
631 (concat "\\s-*$\\|" page-delimiter))
632 (set (make-local-variable 'paragraph-separate) paragraph-start)
633 (set (make-local-variable 'paragraph-ignore-fill-prefix) t)
634 (set (make-local-variable 'fill-paragraph-function) 'octave-fill-paragraph)
635 ;; FIXME: Why disable it?
636 ;; (set (make-local-variable 'adaptive-fill-regexp) nil)
637 ;; Again, this is not a property of the language, don't set it here.
638 ;; (set (make-local-variable 'fill-column) 72)
639 (set (make-local-variable 'normal-auto-fill-function) 'octave-auto-fill)
640
641 (set (make-local-variable 'font-lock-defaults)
642 '(octave-font-lock-keywords))
643
644 (set (make-local-variable 'syntax-propertize-function)
645 #'octave-syntax-propertize-function)
646
647 (set (make-local-variable 'imenu-generic-expression)
648 octave-mode-imenu-generic-expression)
649 (set (make-local-variable 'imenu-case-fold-search) nil)
650
651 (add-hook 'completion-at-point-functions
652 'octave-completion-at-point-function nil t)
653 (set (make-local-variable 'beginning-of-defun-function)
654 'octave-beginning-of-defun)
655
656 (easy-menu-add octave-mode-menu)
657 (octave-initialize-completions))
658 \f
659 ;;; Miscellaneous useful functions
660
661 (defsubst octave-in-comment-p ()
662 "Return t if point is inside an Octave comment."
663 (nth 4 (syntax-ppss)))
664
665 (defsubst octave-in-string-p ()
666 "Return t if point is inside an Octave string."
667 (nth 3 (syntax-ppss)))
668
669 (defsubst octave-not-in-string-or-comment-p ()
670 "Return t if point is not inside an Octave string or comment."
671 (let ((pps (syntax-ppss)))
672 (not (or (nth 3 pps) (nth 4 pps)))))
673
674
675 (defun octave-looking-at-kw (regexp)
676 "Like `looking-at', but sets `case-fold-search' nil."
677 (let ((case-fold-search nil))
678 (looking-at regexp)))
679
680 (defun octave-maybe-insert-continuation-string ()
681 (if (or (octave-in-comment-p)
682 (save-excursion
683 (beginning-of-line)
684 (looking-at octave-continuation-regexp)))
685 nil
686 (delete-horizontal-space)
687 (insert (concat " " octave-continuation-string))))
688 \f
689 ;;; Indentation
690
691 (defun octave-indent-new-comment-line ()
692 "Break Octave line at point, continuing comment if within one.
693 If within code, insert `octave-continuation-string' before breaking the
694 line. If within a string, signal an error.
695 The new line is properly indented."
696 (interactive)
697 (delete-horizontal-space)
698 (cond
699 ((octave-in-comment-p)
700 (indent-new-comment-line))
701 ((octave-in-string-p)
702 (error "Cannot split a code line inside a string"))
703 (t
704 (insert (concat " " octave-continuation-string))
705 (reindent-then-newline-and-indent))))
706
707 (defun octave-indent-defun ()
708 "Properly indent the Octave function which contains point."
709 (interactive)
710 (save-excursion
711 (mark-defun)
712 (message "Indenting function...")
713 (indent-region (point) (mark) nil))
714 (message "Indenting function...done."))
715
716 \f
717 ;;; Motion
718 (defun octave-next-code-line (&optional arg)
719 "Move ARG lines of Octave code forward (backward if ARG is negative).
720 Skips past all empty and comment lines. Default for ARG is 1.
721
722 On success, return 0. Otherwise, go as far as possible and return -1."
723 (interactive "p")
724 (or arg (setq arg 1))
725 (beginning-of-line)
726 (let ((n 0)
727 (inc (if (> arg 0) 1 -1)))
728 (while (and (/= arg 0) (= n 0))
729 (setq n (forward-line inc))
730 (while (and (= n 0)
731 (looking-at "\\s-*\\($\\|\\s<\\)"))
732 (setq n (forward-line inc)))
733 (setq arg (- arg inc)))
734 n))
735
736 (defun octave-previous-code-line (&optional arg)
737 "Move ARG lines of Octave code backward (forward if ARG is negative).
738 Skips past all empty and comment lines. Default for ARG is 1.
739
740 On success, return 0. Otherwise, go as far as possible and return -1."
741 (interactive "p")
742 (or arg (setq arg 1))
743 (octave-next-code-line (- arg)))
744
745 (defun octave-beginning-of-line ()
746 "Move point to beginning of current Octave line.
747 If on an empty or comment line, go to the beginning of that line.
748 Otherwise, move backward to the beginning of the first Octave code line
749 which is not inside a continuation statement, i.e., which does not
750 follow a code line ending in `...' or `\\', or is inside an open
751 parenthesis list."
752 (interactive)
753 (beginning-of-line)
754 (if (not (looking-at "\\s-*\\($\\|\\s<\\)"))
755 (while (or (condition-case nil
756 (progn
757 (up-list -1)
758 (beginning-of-line)
759 t)
760 (error nil))
761 (and (or (looking-at "\\s-*\\($\\|\\s<\\)")
762 (save-excursion
763 (if (zerop (octave-previous-code-line))
764 (looking-at octave-continuation-regexp))))
765 (zerop (forward-line -1)))))))
766
767 (defun octave-end-of-line ()
768 "Move point to end of current Octave line.
769 If on an empty or comment line, go to the end of that line.
770 Otherwise, move forward to the end of the first Octave code line which
771 does not end in `...' or `\\' or is inside an open parenthesis list."
772 (interactive)
773 (end-of-line)
774 (if (save-excursion
775 (beginning-of-line)
776 (looking-at "\\s-*\\($\\|\\s<\\)"))
777 ()
778 (while (or (condition-case nil
779 (progn
780 (up-list 1)
781 (end-of-line)
782 t)
783 (error nil))
784 (and (save-excursion
785 (beginning-of-line)
786 (or (looking-at "\\s-*\\($\\|\\s<\\)")
787 (looking-at octave-continuation-regexp)))
788 (zerop (forward-line 1)))))
789 (end-of-line)))
790
791 (defun octave-mark-block ()
792 "Put point at the beginning of this Octave block, mark at the end.
793 The block marked is the one that contains point or follows point."
794 (interactive)
795 (if (and (looking-at "\\sw\\|\\s_")
796 (looking-back "\\sw\\|\\s_" (1- (point))))
797 (skip-syntax-forward "w_"))
798 (unless (or (looking-at "\\s(")
799 (save-excursion
800 (let* ((token (funcall smie-forward-token-function))
801 (level (assoc token smie-grammar)))
802 (and level (not (numberp (cadr level)))))))
803 (backward-up-list 1))
804 (mark-sexp))
805
806 (defun octave-beginning-of-defun (&optional arg)
807 "Move backward to the beginning of an Octave function.
808 With positive ARG, do it that many times. Negative argument -N means
809 move forward to Nth following beginning of a function.
810 Returns t unless search stops at the beginning or end of the buffer."
811 (let* ((arg (or arg 1))
812 (inc (if (> arg 0) 1 -1))
813 (found nil)
814 (case-fold-search nil))
815 (and (not (eobp))
816 (not (and (> arg 0) (looking-at "\\_<function\\_>")))
817 (skip-syntax-forward "w"))
818 (while (and (/= arg 0)
819 (setq found
820 (re-search-backward "\\_<function\\_>" inc)))
821 (if (octave-not-in-string-or-comment-p)
822 (setq arg (- arg inc))))
823 (if found
824 (progn
825 (and (< inc 0) (goto-char (match-beginning 0)))
826 t))))
827
828 \f
829 ;;; Filling
830 (defun octave-auto-fill ()
831 "Perform auto-fill in Octave mode.
832 Returns nil if no feasible place to break the line could be found, and t
833 otherwise."
834 (let (fc give-up)
835 (if (or (null (setq fc (current-fill-column)))
836 (save-excursion
837 (beginning-of-line)
838 (and auto-fill-inhibit-regexp
839 (octave-looking-at-kw auto-fill-inhibit-regexp))))
840 nil ; Can't do anything
841 (if (and (not (octave-in-comment-p))
842 (> (current-column) fc))
843 (setq fc (- fc (+ (length octave-continuation-string) 1))))
844 (while (and (not give-up) (> (current-column) fc))
845 (let* ((opoint (point))
846 (fpoint
847 (save-excursion
848 (move-to-column (+ fc 1))
849 (skip-chars-backward "^ \t\n")
850 ;; If we're at the beginning of the line, break after
851 ;; the first word
852 (if (bolp)
853 (re-search-forward "[ \t]" opoint t))
854 ;; If we're in a comment line, don't break after the
855 ;; comment chars
856 (if (save-excursion
857 (skip-syntax-backward " <")
858 (bolp))
859 (re-search-forward "[ \t]" (line-end-position)
860 'move))
861 ;; If we're not in a comment line and just ahead the
862 ;; continuation string, don't break here.
863 (if (and (not (octave-in-comment-p))
864 (looking-at
865 (concat "\\s-*"
866 (regexp-quote
867 octave-continuation-string)
868 "\\s-*$")))
869 (end-of-line))
870 (skip-chars-backward " \t")
871 (point))))
872 (if (save-excursion
873 (goto-char fpoint)
874 (not (or (bolp) (eolp))))
875 (let ((prev-column (current-column)))
876 (if (save-excursion
877 (skip-chars-backward " \t")
878 (= (point) fpoint))
879 (progn
880 (octave-maybe-insert-continuation-string)
881 (indent-new-comment-line t))
882 (save-excursion
883 (goto-char fpoint)
884 (octave-maybe-insert-continuation-string)
885 (indent-new-comment-line t)))
886 (if (>= (current-column) prev-column)
887 (setq give-up t)))
888 (setq give-up t))))
889 (not give-up))))
890
891 (defun octave-fill-paragraph (&optional _arg)
892 "Fill paragraph of Octave code, handling Octave comments."
893 ;; FIXME: difference with generic fill-paragraph:
894 ;; - code lines are only split, never joined.
895 ;; - \n that end comments are never removed.
896 ;; - insert continuation marker when splitting code lines.
897 (interactive "P")
898 (save-excursion
899 (let ((end (progn (forward-paragraph) (copy-marker (point) t)))
900 (beg (progn
901 (forward-paragraph -1)
902 (skip-chars-forward " \t\n")
903 (beginning-of-line)
904 (point)))
905 (cfc (current-fill-column))
906 comment-prefix)
907 (goto-char beg)
908 (while (< (point) end)
909 (condition-case nil
910 (indent-according-to-mode)
911 (error nil))
912 (move-to-column cfc)
913 ;; First check whether we need to combine non-empty comment lines
914 (if (and (< (current-column) cfc)
915 (octave-in-comment-p)
916 (not (save-excursion
917 (beginning-of-line)
918 (looking-at "^\\s-*\\s<+\\s-*$"))))
919 ;; This is a nonempty comment line which does not extend
920 ;; past the fill column. If it is followed by a nonempty
921 ;; comment line with the same comment prefix, try to
922 ;; combine them, and repeat this until either we reach the
923 ;; fill-column or there is nothing more to combine.
924 (progn
925 ;; Get the comment prefix
926 (save-excursion
927 (beginning-of-line)
928 (while (and (re-search-forward "\\s<+")
929 (not (octave-in-comment-p))))
930 (setq comment-prefix (match-string 0)))
931 ;; And keep combining ...
932 (while (and (< (current-column) cfc)
933 (save-excursion
934 (forward-line 1)
935 (and (looking-at
936 (concat "^\\s-*"
937 comment-prefix
938 "\\S<"))
939 (not (looking-at
940 (concat "^\\s-*"
941 comment-prefix
942 "\\s-*$"))))))
943 (delete-char 1)
944 (re-search-forward comment-prefix)
945 (delete-region (match-beginning 0) (match-end 0))
946 (fixup-whitespace)
947 (move-to-column cfc))))
948 ;; We might also try to combine continued code lines> Perhaps
949 ;; some other time ...
950 (skip-chars-forward "^ \t\n")
951 (delete-horizontal-space)
952 (if (or (< (current-column) cfc)
953 (and (= (current-column) cfc) (eolp)))
954 (forward-line 1)
955 (if (not (eolp)) (insert " "))
956 (or (octave-auto-fill)
957 (forward-line 1))))
958 t)))
959
960 \f
961 ;;; Completions
962 (defun octave-initialize-completions ()
963 "Create an alist for Octave completions."
964 (if octave-completion-alist
965 ()
966 (setq octave-completion-alist
967 (append octave-reserved-words
968 octave-text-functions
969 octave-variables))))
970
971 (defun octave-completion-at-point-function ()
972 "Find the text to complete and the corresponding table."
973 (let* ((beg (save-excursion (skip-syntax-backward "w_") (point)))
974 (end (point)))
975 (if (< beg (point))
976 ;; Extend region past point, if applicable.
977 (save-excursion (skip-syntax-forward "w_")
978 (setq end (point))))
979 (list beg end octave-completion-alist)))
980
981 (define-obsolete-function-alias 'octave-complete-symbol
982 'completion-at-point "24.1")
983 \f
984 ;;; Electric characters && friends
985
986 (defun octave-abbrev-start ()
987 "Start entering an Octave abbreviation.
988 If Abbrev mode is turned on, typing ` (grave accent) followed by ? or
989 \\[help-command] lists all Octave abbrevs. Any other key combination is
990 executed normally.
991 Note that all Octave mode abbrevs start with a grave accent."
992 (interactive)
993 (self-insert-command 1)
994 (when abbrev-mode
995 (set-temporary-overlay-map
996 (let ((map (make-sparse-keymap)))
997 (define-key map [??] 'list-abbrevs)
998 (define-key map (vector help-char) 'list-abbrevs)
999 map))))
1000
1001 (define-skeleton octave-insert-defun
1002 "Insert an Octave function skeleton.
1003 Prompt for the function's name, arguments and return values (to be
1004 entered without parens)."
1005 (let* ((defname (substring (buffer-name) 0 -2))
1006 (name (read-string (format "Function name (default %s): " defname)
1007 nil nil defname))
1008 (args (read-string "Arguments: "))
1009 (vals (read-string "Return values: ")))
1010 (format "%s%s (%s)"
1011 (cond
1012 ((string-equal vals "") vals)
1013 ((string-match "[ ,]" vals) (concat "[" vals "] = "))
1014 (t (concat vals " = ")))
1015 name
1016 args))
1017 \n "function " > str \n \n
1018 octave-block-comment-start "usage: " str \n
1019 octave-block-comment-start \n octave-block-comment-start
1020 \n _ \n
1021 "endfunction" > \n)
1022 \f
1023 ;;; Communication with the inferior Octave process
1024 (defun octave-kill-process ()
1025 "Kill inferior Octave process and its buffer."
1026 (interactive)
1027 (if inferior-octave-process
1028 (progn
1029 (process-send-string inferior-octave-process "quit;\n")
1030 (accept-process-output inferior-octave-process)))
1031 (if inferior-octave-buffer
1032 (kill-buffer inferior-octave-buffer)))
1033
1034 (defun octave-show-process-buffer ()
1035 "Make sure that `inferior-octave-buffer' is displayed."
1036 (interactive)
1037 (if (get-buffer inferior-octave-buffer)
1038 (display-buffer inferior-octave-buffer)
1039 (message "No buffer named %s" inferior-octave-buffer)))
1040
1041 (defun octave-hide-process-buffer ()
1042 "Delete all windows that display `inferior-octave-buffer'."
1043 (interactive)
1044 (if (get-buffer inferior-octave-buffer)
1045 (delete-windows-on inferior-octave-buffer)
1046 (message "No buffer named %s" inferior-octave-buffer)))
1047
1048 (defun octave-send-region (beg end)
1049 "Send current region to the inferior Octave process."
1050 (interactive "r")
1051 (inferior-octave t)
1052 (let ((proc inferior-octave-process)
1053 (string (buffer-substring-no-properties beg end))
1054 line)
1055 (with-current-buffer inferior-octave-buffer
1056 (setq inferior-octave-output-list nil)
1057 (while (not (string-equal string ""))
1058 (if (string-match "\n" string)
1059 (setq line (substring string 0 (match-beginning 0))
1060 string (substring string (match-end 0)))
1061 (setq line string string ""))
1062 (setq inferior-octave-receive-in-progress t)
1063 (inferior-octave-send-list-and-digest (list (concat line "\n")))
1064 (while inferior-octave-receive-in-progress
1065 (accept-process-output proc))
1066 (insert-before-markers
1067 (mapconcat 'identity
1068 (append
1069 (if octave-send-echo-input (list line) (list ""))
1070 (mapcar 'inferior-octave-strip-ctrl-g
1071 inferior-octave-output-list)
1072 (list inferior-octave-output-string))
1073 "\n")))))
1074 (if octave-send-show-buffer
1075 (display-buffer inferior-octave-buffer)))
1076
1077 (defun octave-send-block ()
1078 "Send current Octave block to the inferior Octave process."
1079 (interactive)
1080 (save-excursion
1081 (octave-mark-block)
1082 (octave-send-region (point) (mark))))
1083
1084 (defun octave-send-defun ()
1085 "Send current Octave function to the inferior Octave process."
1086 (interactive)
1087 (save-excursion
1088 (mark-defun)
1089 (octave-send-region (point) (mark))))
1090
1091 (defun octave-send-line (&optional arg)
1092 "Send current Octave code line to the inferior Octave process.
1093 With positive prefix ARG, send that many lines.
1094 If `octave-send-line-auto-forward' is non-nil, go to the next unsent
1095 code line."
1096 (interactive "P")
1097 (or arg (setq arg 1))
1098 (if (> arg 0)
1099 (let (beg end)
1100 (beginning-of-line)
1101 (setq beg (point))
1102 (octave-next-code-line (- arg 1))
1103 (end-of-line)
1104 (setq end (point))
1105 (if octave-send-line-auto-forward
1106 (octave-next-code-line 1))
1107 (octave-send-region beg end))))
1108
1109 (defun octave-eval-print-last-sexp ()
1110 "Evaluate Octave sexp before point and print value into current buffer."
1111 (interactive)
1112 (inferior-octave t)
1113 (let ((standard-output (current-buffer))
1114 (print-escape-newlines nil)
1115 (opoint (point)))
1116 (terpri)
1117 (prin1
1118 (save-excursion
1119 (forward-sexp -1)
1120 (inferior-octave-send-list-and-digest
1121 (list (concat (buffer-substring-no-properties (point) opoint)
1122 "\n")))
1123 (mapconcat 'identity inferior-octave-output-list "\n")))
1124 (terpri)))
1125 \f
1126 ;;; Bug reporting
1127 (defun octave-submit-bug-report ()
1128 "Submit a bug report on the Emacs Octave package via mail."
1129 (interactive)
1130 (require 'reporter)
1131 (and
1132 (y-or-n-p "Do you want to submit a bug report? ")
1133 (reporter-submit-bug-report
1134 octave-maintainer-address
1135 (concat "Emacs version " emacs-version)
1136 (list
1137 'octave-blink-matching-block
1138 'octave-block-offset
1139 'octave-comment-char
1140 'octave-continuation-offset
1141 'octave-continuation-string
1142 'octave-send-echo-input
1143 'octave-send-line-auto-forward
1144 'octave-send-show-buffer))))
1145
1146 ;; provide ourself
1147
1148 (provide 'octave-mod)
1149
1150 ;;; octave-mod.el ends here