* lisp/progmodes/octave-mod.el (octave-in-comment-p, octave-in-string-p)
[emacs.git] / lisp / progmodes / octave-mod.el
blob8bf9ff299d08f3faf77156a96b6f23101bc20c3d
1 ;;; octave-mod.el --- editing Octave source files under Emacs
3 ;; Copyright (C) 1997, 2001-2011 Free Software Foundation, Inc.
5 ;; Author: Kurt Hornik <Kurt.Hornik@wu-wien.ac.at>
6 ;; Author: John Eaton <jwe@octave.org>
7 ;; Maintainer: Kurt Hornik <Kurt.Hornik@wu-wien.ac.at>
8 ;; Keywords: languages
10 ;; This file is part of GNU Emacs.
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.
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.
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/>.
25 ;;; Commentary:
27 ;; This package provides Emacs support for Octave.
28 ;; It defines Octave mode, a major mode for editing
29 ;; Octave code.
31 ;; The file octave-inf.el contains code for interacting with an inferior
32 ;; Octave process using comint.
34 ;; See the documentation of `octave-mode' and
35 ;; `run-octave' for further information on usage and customization.
37 ;;; Code:
38 (require 'custom)
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)
45 (defvar inferior-octave-output-list nil)
46 (defvar inferior-octave-output-string nil)
47 (defvar inferior-octave-receive-in-progress nil)
49 (declare-function inferior-octave-send-list-and-digest "octave-inf" (list))
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.")
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*")
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.")
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"))
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.")
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.")
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.")
152 (defvar octave-function-header-regexp
153 (concat "^\\s-*\\<\\(function\\)\\>"
154 "\\([^=;\n]*=[ \t]*\\|[ \t]*\\)\\(\\w+\\)\\>")
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.")
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.")
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))
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 "\"'")))))
204 (defcustom inferior-octave-buffer "*Inferior Octave*"
205 "Name of buffer for running an inferior Octave process."
206 :type 'string
207 :group 'octave-inferior)
209 (defvar inferior-octave-process nil)
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-h" 'octave-help)
227 (define-key map "\C-c\C-il" 'octave-send-line)
228 (define-key map "\C-c\C-ib" 'octave-send-block)
229 (define-key map "\C-c\C-if" 'octave-send-defun)
230 (define-key map "\C-c\C-ir" 'octave-send-region)
231 (define-key map "\C-c\C-is" 'octave-show-process-buffer)
232 (define-key map "\C-c\C-ih" 'octave-hide-process-buffer)
233 (define-key map "\C-c\C-ik" 'octave-kill-process)
234 (define-key map "\C-c\C-i\C-l" 'octave-send-line)
235 (define-key map "\C-c\C-i\C-b" 'octave-send-block)
236 (define-key map "\C-c\C-i\C-f" 'octave-send-defun)
237 (define-key map "\C-c\C-i\C-r" 'octave-send-region)
238 (define-key map "\C-c\C-i\C-s" 'octave-show-process-buffer)
239 (define-key map "\C-c\C-i\C-h" 'octave-hide-process-buffer)
240 (define-key map "\C-c\C-i\C-k" 'octave-kill-process)
241 map)
242 "Keymap used in Octave mode.")
246 (easy-menu-define octave-mode-menu octave-mode-map
247 "Menu for Octave mode."
248 '("Octave"
249 ("Lines"
250 ["Previous Code Line" octave-previous-code-line t]
251 ["Next Code Line" octave-next-code-line t]
252 ["Begin of Continuation" octave-beginning-of-line t]
253 ["End of Continuation" octave-end-of-line t]
254 ["Split Line at Point" octave-indent-new-comment-line t])
255 ("Blocks"
256 ["Mark Block" octave-mark-block t]
257 ["Close Block" smie-close-block t])
258 ("Functions"
259 ["Indent Function" octave-indent-defun t]
260 ["Insert Function" octave-insert-defun t])
262 ("Debug"
263 ["Send Current Line" octave-send-line t]
264 ["Send Current Block" octave-send-block t]
265 ["Send Current Function" octave-send-defun t]
266 ["Send Region" octave-send-region t]
267 ["Show Process Buffer" octave-show-process-buffer t]
268 ["Hide Process Buffer" octave-hide-process-buffer t]
269 ["Kill Process" octave-kill-process t])
271 ["Indent Line" indent-according-to-mode t]
272 ["Complete Symbol" completion-at-point t]
274 ["Toggle Abbrev Mode" abbrev-mode
275 :style toggle :selected abbrev-mode]
276 ["Toggle Auto-Fill Mode" auto-fill-mode
277 :style toggle :selected auto-fill-function]
279 ["Submit Bug Report" octave-submit-bug-report t]
281 ["Describe Octave Mode" describe-mode t]
282 ["Lookup Octave Index" info-lookup-symbol t]))
284 (defvar octave-mode-syntax-table
285 (let ((table (make-syntax-table)))
286 (modify-syntax-entry ?\r " " 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 (modify-syntax-entry ?\' "." table)
299 ;; Was "w" for abbrevs, but now that it's not necessary any more,
300 (modify-syntax-entry ?\` "." table)
301 (modify-syntax-entry ?\" "\"" table)
302 (modify-syntax-entry ?. "w" table)
303 (modify-syntax-entry ?_ "w" table)
304 ;; The "b" flag only applies to the second letter of the comstart
305 ;; and the first letter of the comend, i.e. the "4b" below is ineffective.
306 ;; If we try to put `b' on the single-line comments, we get a similar
307 ;; problem where the % and # chars appear as first chars of the 2-char
308 ;; comend, so the multi-line ender is also turned into style-b.
309 ;; So we need the new "c" comment style.
310 (modify-syntax-entry ?\% "< 13" table)
311 (modify-syntax-entry ?\# "< 13" table)
312 (modify-syntax-entry ?\{ "(} 2c" table)
313 (modify-syntax-entry ?\} "){ 4c" table)
314 (modify-syntax-entry ?\n ">" table)
315 table)
316 "Syntax table in use in `octave-mode' buffers.")
318 (defcustom octave-blink-matching-block t
319 "Control the blinking of matching Octave block keywords.
320 Non-nil means show matching begin of block when inserting a space,
321 newline or semicolon after an else or end keyword."
322 :type 'boolean
323 :group 'octave)
325 (defcustom octave-block-offset 2
326 "Extra indentation applied to statements in Octave block structures."
327 :type 'integer
328 :group 'octave)
330 (defvar octave-block-comment-start
331 (concat (make-string 2 octave-comment-char) " ")
332 "String to insert to start a new Octave comment on an empty line.")
334 (defcustom octave-continuation-offset 4
335 "Extra indentation applied to Octave continuation lines."
336 :type 'integer
337 :group 'octave)
338 (eval-and-compile
339 (defconst octave-continuation-marker-regexp "\\\\\\|\\.\\.\\."))
340 (defvar octave-continuation-regexp
341 (concat "[^#%\n]*\\(" octave-continuation-marker-regexp
342 "\\)\\s-*\\(\\s<.*\\)?$"))
343 (defcustom octave-continuation-string "\\"
344 "Character string used for Octave continuation lines. Normally \\."
345 :type 'string
346 :group 'octave)
348 (defvar octave-completion-alist nil
349 "Alist of Octave symbols for completion in Octave mode.
350 Each element looks like (VAR . VAR), where the car and cdr are the same
351 symbol (an Octave command or variable name).
352 Currently, only builtin variables can be completed.")
354 (defvar octave-mode-imenu-generic-expression
355 (list
356 ;; Functions
357 (list nil octave-function-header-regexp 3))
358 "Imenu expression for Octave mode. See `imenu-generic-expression'.")
360 (defcustom octave-mode-hook nil
361 "Hook to be run when Octave mode is started."
362 :type 'hook
363 :group 'octave)
365 (defcustom octave-send-show-buffer t
366 "Non-nil means display `inferior-octave-buffer' after sending to it."
367 :type 'boolean
368 :group 'octave)
369 (defcustom octave-send-line-auto-forward t
370 "Control auto-forward after sending to the inferior Octave process.
371 Non-nil means always go to the next Octave code line after sending."
372 :type 'boolean
373 :group 'octave)
374 (defcustom octave-send-echo-input t
375 "Non-nil means echo input sent to the inferior Octave process."
376 :type 'boolean
377 :group 'octave)
380 ;;; SMIE indentation
382 (require 'smie)
384 (defconst octave-operator-table
385 '((assoc ";" "\n") (assoc ",") ; The doc claims they have equal precedence!?
386 (right "=" "+=" "-=" "*=" "/=")
387 (assoc "&&") (assoc "||") ; The doc claims they have equal precedence!?
388 (assoc "&") (assoc "|") ; The doc claims they have equal precedence!?
389 (nonassoc "<" "<=" "==" ">=" ">" "!=" "~=")
390 (nonassoc ":") ;No idea what this is.
391 (assoc "+" "-")
392 (assoc "*" "/" "\\" ".\\" ".*" "./")
393 (nonassoc "'" ".'")
394 (nonassoc "++" "--" "!" "~") ;And unary "+" and "-".
395 (right "^" "**" ".^" ".**")
396 ;; It's not really an operator, but for indentation purposes it
397 ;; could be convenient to treat it as one.
398 (assoc "...")))
400 (defconst octave-smie-bnf-table
401 '((atom)
402 ;; We can't distinguish the first element in a sequence with
403 ;; precedence grammars, so we can't distinguish the condition
404 ;; if the `if' from the subsequent body, for example.
405 ;; This has to be done later in the indentation rules.
406 (exp (exp "\n" exp)
407 ;; We need to mention at least one of the operators in this part
408 ;; of the grammar: if the BNF and the operator table have
409 ;; no overlap, SMIE can't know how they relate.
410 (exp ";" exp)
411 ("try" exp "catch" exp "end_try_catch")
412 ("try" exp "catch" exp "end")
413 ("unwind_protect" exp
414 "unwind_protect_cleanup" exp "end_unwind_protect")
415 ("unwind_protect" exp "unwind_protect_cleanup" exp "end")
416 ("for" exp "endfor")
417 ("for" exp "end")
418 ("do" exp "until" atom)
419 ("while" exp "endwhile")
420 ("while" exp "end")
421 ("if" exp "endif")
422 ("if" exp "else" exp "endif")
423 ("if" exp "elseif" exp "else" exp "endif")
424 ("if" exp "elseif" exp "elseif" exp "else" exp "endif")
425 ("if" exp "elseif" exp "elseif" exp "else" exp "end")
426 ("switch" exp "case" exp "endswitch")
427 ("switch" exp "case" exp "otherwise" exp "endswitch")
428 ("switch" exp "case" exp "case" exp "otherwise" exp "endswitch")
429 ("switch" exp "case" exp "case" exp "otherwise" exp "end")
430 ("function" exp "endfunction")
431 ("function" exp "end"))
432 ;; (fundesc (atom "=" atom))
435 (defconst octave-smie-grammar
436 (smie-prec2->grammar
437 (smie-merge-prec2s
438 (smie-bnf->prec2 octave-smie-bnf-table
439 '((assoc "\n" ";")))
441 (smie-precs->prec2 octave-operator-table))))
443 ;; Tokenizing needs to be refined so that ";;" is treated as two
444 ;; tokens and also so as to recognize the \n separator (and
445 ;; corresponding continuation lines).
447 (defconst octave-operator-regexp
448 (regexp-opt (apply 'append (mapcar 'cdr octave-operator-table))))
450 (defun octave-smie-backward-token ()
451 (let ((pos (point)))
452 (forward-comment (- (point)))
453 (cond
454 ((and (not (eq (char-before) ?\;)) ;Coalesce ";" and "\n".
455 (> pos (line-end-position))
456 (if (looking-back octave-continuation-marker-regexp (- (point) 3))
457 (progn
458 (goto-char (match-beginning 0))
459 (forward-comment (- (point)))
460 nil)
462 ;; Ignore it if it's within parentheses.
463 (let ((ppss (syntax-ppss)))
464 (not (and (nth 1 ppss)
465 (eq ?\( (char-after (nth 1 ppss)))))))
466 (skip-chars-forward " \t")
467 ;; Why bother distinguishing \n and ;?
468 ";") ;;"\n"
469 ((and (looking-back octave-operator-regexp (- (point) 3) 'greedy)
470 ;; Don't mistake a string quote for a transpose.
471 (not (looking-back "\\s\"" (1- (point)))))
472 (goto-char (match-beginning 0))
473 (match-string-no-properties 0))
475 (smie-default-backward-token)))))
477 (defun octave-smie-forward-token ()
478 (skip-chars-forward " \t")
479 (when (looking-at (eval-when-compile
480 (concat "\\(" octave-continuation-marker-regexp
481 "\\)[ \t]*\\($\\|[%#]\\)")))
482 (goto-char (match-end 1))
483 (forward-comment 1))
484 (cond
485 ((and (looking-at "$\\|[%#]")
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))
504 (smie-default-forward-token))))
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))))
525 (defvar electric-layout-rules)
527 ;;;###autoload
528 (define-derived-mode octave-mode prog-mode "Octave"
529 "Major mode for editing Octave code.
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).
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!).
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.
546 Type \\[list-abbrevs] to display the built-in abbrevs for Octave keywords.
548 Keybindings
549 ===========
551 \\{octave-mode-map}
553 Variables you can use to customize Octave mode
554 ==============================================
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.
560 `octave-block-offset'
561 Extra indentation applied to statements in block structures.
562 Default is 2.
564 `octave-continuation-offset'
565 Extra indentation applied to Octave continuation lines.
566 Default is 4.
568 `octave-continuation-string'
569 String used for Octave continuation lines.
570 Default is a backslash.
572 `octave-send-echo-input'
573 Non-nil means always display `inferior-octave-buffer' after sending a
574 command to the inferior Octave process.
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.
580 `octave-send-echo-input'
581 Non-nil means echo input sent to the inferior Octave process.
583 Turning on Octave mode runs the hook `octave-mode-hook'.
585 To begin using this mode for all `.m' files that you edit, add the
586 following lines to your `.emacs' file:
588 (add-to-list 'auto-mode-alist '(\"\\\\.m\\\\'\" . octave-mode))
590 To automatically turn on the abbrev and auto-fill features,
591 add the following lines to your `.emacs' file as well:
593 (add-hook 'octave-mode-hook
594 (lambda ()
595 (abbrev-mode 1)
596 (auto-fill-mode 1)))
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)
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)
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))
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)))
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)
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)
641 (set (make-local-variable 'font-lock-defaults)
642 '(octave-font-lock-keywords))
644 (set (make-local-variable 'syntax-propertize-function)
645 #'octave-syntax-propertize-function)
647 (set (make-local-variable 'imenu-generic-expression)
648 octave-mode-imenu-generic-expression)
649 (set (make-local-variable 'imenu-case-fold-search) nil)
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)
656 (easy-menu-add octave-mode-menu)
657 (octave-initialize-completions))
659 (defvar info-lookup-mode)
661 (defun octave-help ()
662 "Get help on Octave symbols from the Octave info files.
663 Look up symbol in the function, operator and variable indices of the info files."
664 (let ((info-lookup-mode 'octave-mode))
665 (call-interactively 'info-lookup-symbol)))
667 ;;; Miscellaneous useful functions
669 (defsubst octave-in-comment-p ()
670 "Return t if point is inside an Octave comment."
671 (nth 4 (syntax-ppss)))
673 (defsubst octave-in-string-p ()
674 "Return t if point is inside an Octave string."
675 (nth 3 (syntax-ppss)))
677 (defsubst octave-not-in-string-or-comment-p ()
678 "Return t if point is not inside an Octave string or comment."
679 (let ((pps (syntax-ppss)))
680 (not (or (nth 3 pps) (nth 4 pps)))))
683 (defun octave-looking-at-kw (regexp)
684 "Like `looking-at', but sets `case-fold-search' nil."
685 (let ((case-fold-search nil))
686 (looking-at regexp)))
688 (defun octave-maybe-insert-continuation-string ()
689 (if (or (octave-in-comment-p)
690 (save-excursion
691 (beginning-of-line)
692 (looking-at octave-continuation-regexp)))
694 (delete-horizontal-space)
695 (insert (concat " " octave-continuation-string))))
697 ;;; Indentation
699 (defun octave-indent-new-comment-line ()
700 "Break Octave line at point, continuing comment if within one.
701 If within code, insert `octave-continuation-string' before breaking the
702 line. If within a string, signal an error.
703 The new line is properly indented."
704 (interactive)
705 (delete-horizontal-space)
706 (cond
707 ((octave-in-comment-p)
708 (indent-new-comment-line))
709 ((octave-in-string-p)
710 (error "Cannot split a code line inside a string"))
712 (insert (concat " " octave-continuation-string))
713 (reindent-then-newline-and-indent))))
715 (defun octave-indent-defun ()
716 "Properly indent the Octave function which contains point."
717 (interactive)
718 (save-excursion
719 (mark-defun)
720 (message "Indenting function...")
721 (indent-region (point) (mark) nil))
722 (message "Indenting function...done."))
725 ;;; Motion
726 (defun octave-next-code-line (&optional arg)
727 "Move ARG lines of Octave code forward (backward if ARG is negative).
728 Skips past all empty and comment lines. Default for ARG is 1.
730 On success, return 0. Otherwise, go as far as possible and return -1."
731 (interactive "p")
732 (or arg (setq arg 1))
733 (beginning-of-line)
734 (let ((n 0)
735 (inc (if (> arg 0) 1 -1)))
736 (while (and (/= arg 0) (= n 0))
737 (setq n (forward-line inc))
738 (while (and (= n 0)
739 (looking-at "\\s-*\\($\\|\\s<\\)"))
740 (setq n (forward-line inc)))
741 (setq arg (- arg inc)))
744 (defun octave-previous-code-line (&optional arg)
745 "Move ARG lines of Octave code backward (forward if ARG is negative).
746 Skips past all empty and comment lines. Default for ARG is 1.
748 On success, return 0. Otherwise, go as far as possible and return -1."
749 (interactive "p")
750 (or arg (setq arg 1))
751 (octave-next-code-line (- arg)))
753 (defun octave-beginning-of-line ()
754 "Move point to beginning of current Octave line.
755 If on an empty or comment line, go to the beginning of that line.
756 Otherwise, move backward to the beginning of the first Octave code line
757 which is not inside a continuation statement, i.e., which does not
758 follow a code line ending in `...' or `\\', or is inside an open
759 parenthesis list."
760 (interactive)
761 (beginning-of-line)
762 (if (not (looking-at "\\s-*\\($\\|\\s<\\)"))
763 (while (or (condition-case nil
764 (progn
765 (up-list -1)
766 (beginning-of-line)
768 (error nil))
769 (and (or (looking-at "\\s-*\\($\\|\\s<\\)")
770 (save-excursion
771 (if (zerop (octave-previous-code-line))
772 (looking-at octave-continuation-regexp))))
773 (zerop (forward-line -1)))))))
775 (defun octave-end-of-line ()
776 "Move point to end of current Octave line.
777 If on an empty or comment line, go to the end of that line.
778 Otherwise, move forward to the end of the first Octave code line which
779 does not end in `...' or `\\' or is inside an open parenthesis list."
780 (interactive)
781 (end-of-line)
782 (if (save-excursion
783 (beginning-of-line)
784 (looking-at "\\s-*\\($\\|\\s<\\)"))
786 (while (or (condition-case nil
787 (progn
788 (up-list 1)
789 (end-of-line)
791 (error nil))
792 (and (save-excursion
793 (beginning-of-line)
794 (or (looking-at "\\s-*\\($\\|\\s<\\)")
795 (looking-at octave-continuation-regexp)))
796 (zerop (forward-line 1)))))
797 (end-of-line)))
799 (defun octave-mark-block ()
800 "Put point at the beginning of this Octave block, mark at the end.
801 The block marked is the one that contains point or follows point."
802 (interactive)
803 (unless (or (looking-at "\\s(")
804 (save-excursion
805 (let* ((token (funcall smie-forward-token-function))
806 (level (assoc token smie-grammar)))
807 (and level (null (cadr level))))))
808 (backward-up-list 1))
809 (mark-sexp))
811 (defun octave-beginning-of-defun (&optional arg)
812 "Move backward to the beginning of an Octave function.
813 With positive ARG, do it that many times. Negative argument -N means
814 move forward to Nth following beginning of a function.
815 Returns t unless search stops at the beginning or end of the buffer."
816 (let* ((arg (or arg 1))
817 (inc (if (> arg 0) 1 -1))
818 (found nil)
819 (case-fold-search nil))
820 (and (not (eobp))
821 (not (and (> arg 0) (looking-at "\\<function\\>")))
822 (skip-syntax-forward "w"))
823 (while (and (/= arg 0)
824 (setq found
825 (re-search-backward "\\<function\\>" inc)))
826 (if (octave-not-in-string-or-comment-p)
827 (setq arg (- arg inc))))
828 (if found
829 (progn
830 (and (< inc 0) (goto-char (match-beginning 0)))
831 t))))
834 ;;; Filling
835 (defun octave-auto-fill ()
836 "Perform auto-fill in Octave mode.
837 Returns nil if no feasible place to break the line could be found, and t
838 otherwise."
839 (let (fc give-up)
840 (if (or (null (setq fc (current-fill-column)))
841 (save-excursion
842 (beginning-of-line)
843 (and auto-fill-inhibit-regexp
844 (octave-looking-at-kw auto-fill-inhibit-regexp))))
845 nil ; Can't do anything
846 (if (and (not (octave-in-comment-p))
847 (> (current-column) fc))
848 (setq fc (- fc (+ (length octave-continuation-string) 1))))
849 (while (and (not give-up) (> (current-column) fc))
850 (let* ((opoint (point))
851 (fpoint
852 (save-excursion
853 (move-to-column (+ fc 1))
854 (skip-chars-backward "^ \t\n")
855 ;; If we're at the beginning of the line, break after
856 ;; the first word
857 (if (bolp)
858 (re-search-forward "[ \t]" opoint t))
859 ;; If we're in a comment line, don't break after the
860 ;; comment chars
861 (if (save-excursion
862 (skip-syntax-backward " <")
863 (bolp))
864 (re-search-forward "[ \t]" (line-end-position)
865 'move))
866 ;; If we're not in a comment line and just ahead the
867 ;; continuation string, don't break here.
868 (if (and (not (octave-in-comment-p))
869 (looking-at
870 (concat "\\s-*"
871 (regexp-quote
872 octave-continuation-string)
873 "\\s-*$")))
874 (end-of-line))
875 (skip-chars-backward " \t")
876 (point))))
877 (if (save-excursion
878 (goto-char fpoint)
879 (not (or (bolp) (eolp))))
880 (let ((prev-column (current-column)))
881 (if (save-excursion
882 (skip-chars-backward " \t")
883 (= (point) fpoint))
884 (progn
885 (octave-maybe-insert-continuation-string)
886 (indent-new-comment-line t))
887 (save-excursion
888 (goto-char fpoint)
889 (octave-maybe-insert-continuation-string)
890 (indent-new-comment-line t)))
891 (if (>= (current-column) prev-column)
892 (setq give-up t)))
893 (setq give-up t))))
894 (not give-up))))
896 (defun octave-fill-paragraph (&optional arg)
897 "Fill paragraph of Octave code, handling Octave comments."
898 ;; FIXME: difference with generic fill-paragraph:
899 ;; - code lines are only split, never joined.
900 ;; - \n that end comments are never removed.
901 ;; - insert continuation marker when splitting code lines.
902 (interactive "P")
903 (save-excursion
904 (let ((end (progn (forward-paragraph) (copy-marker (point) t)))
905 (beg (progn
906 (forward-paragraph -1)
907 (skip-chars-forward " \t\n")
908 (beginning-of-line)
909 (point)))
910 (cfc (current-fill-column))
911 comment-prefix)
912 (goto-char beg)
913 (while (< (point) end)
914 (condition-case nil
915 (indent-according-to-mode)
916 (error nil))
917 (move-to-column cfc)
918 ;; First check whether we need to combine non-empty comment lines
919 (if (and (< (current-column) cfc)
920 (octave-in-comment-p)
921 (not (save-excursion
922 (beginning-of-line)
923 (looking-at "^\\s-*\\s<+\\s-*$"))))
924 ;; This is a nonempty comment line which does not extend
925 ;; past the fill column. If it is followed by a nonempty
926 ;; comment line with the same comment prefix, try to
927 ;; combine them, and repeat this until either we reach the
928 ;; fill-column or there is nothing more to combine.
929 (progn
930 ;; Get the comment prefix
931 (save-excursion
932 (beginning-of-line)
933 (while (and (re-search-forward "\\s<+")
934 (not (octave-in-comment-p))))
935 (setq comment-prefix (match-string 0)))
936 ;; And keep combining ...
937 (while (and (< (current-column) cfc)
938 (save-excursion
939 (forward-line 1)
940 (and (looking-at
941 (concat "^\\s-*"
942 comment-prefix
943 "\\S<"))
944 (not (looking-at
945 (concat "^\\s-*"
946 comment-prefix
947 "\\s-*$"))))))
948 (delete-char 1)
949 (re-search-forward comment-prefix)
950 (delete-region (match-beginning 0) (match-end 0))
951 (fixup-whitespace)
952 (move-to-column cfc))))
953 ;; We might also try to combine continued code lines> Perhaps
954 ;; some other time ...
955 (skip-chars-forward "^ \t\n")
956 (delete-horizontal-space)
957 (if (or (< (current-column) cfc)
958 (and (= (current-column) cfc) (eolp)))
959 (forward-line 1)
960 (if (not (eolp)) (insert " "))
961 (or (octave-auto-fill)
962 (forward-line 1))))
963 t)))
966 ;;; Completions
967 (defun octave-initialize-completions ()
968 "Create an alist for Octave completions."
969 (if octave-completion-alist
971 (setq octave-completion-alist
972 (append octave-reserved-words
973 octave-text-functions
974 octave-variables))))
976 (defun octave-completion-at-point-function ()
977 "Find the text to complete and the corresponding table."
978 (let* ((beg (save-excursion (backward-sexp 1) (point)))
979 (end (point)))
980 (if (< beg (point))
981 ;; Extend region past point, if applicable.
982 (save-excursion (goto-char beg) (forward-sexp 1)
983 (setq end (max end (point)))))
984 (list beg end octave-completion-alist)))
986 (defun octave-complete-symbol ()
987 "Perform completion on Octave symbol preceding point.
988 Compare that symbol against Octave's reserved words and builtin
989 variables."
990 (interactive)
991 (apply 'completion-in-region (octave-completion-at-point-function)))
993 ;;; Electric characters && friends
995 (defun octave-abbrev-start ()
996 "Start entering an Octave abbreviation.
997 If Abbrev mode is turned on, typing ` (grave accent) followed by ? or
998 \\[help-command] lists all Octave abbrevs. Any other key combination is
999 executed normally.
1000 Note that all Octave mode abbrevs start with a grave accent."
1001 (interactive)
1002 (if (not abbrev-mode)
1003 (self-insert-command 1)
1004 (let (c)
1005 (insert last-command-event)
1006 (if (if (featurep 'xemacs)
1007 (or (eq (event-to-character (setq c (next-event))) ??)
1008 (eq (event-to-character c) help-char))
1009 (or (eq (setq c (read-event)) ??)
1010 (eq c help-char)))
1011 (let ((abbrev-table-name-list '(octave-abbrev-table)))
1012 (list-abbrevs))
1013 (setq unread-command-events (list c))))))
1015 (define-skeleton octave-insert-defun
1016 "Insert an Octave function skeleton.
1017 Prompt for the function's name, arguments and return values (to be
1018 entered without parens)."
1019 (let* ((defname (substring (buffer-name) 0 -2))
1020 (name (read-string (format "Function name (default %s): " defname)
1021 nil nil defname))
1022 (args (read-string "Arguments: "))
1023 (vals (read-string "Return values: ")))
1024 (format "%s%s (%s)"
1025 (cond
1026 ((string-equal vals "") vals)
1027 ((string-match "[ ,]" vals) (concat "[" vals "] = "))
1028 (t (concat vals " = ")))
1029 name
1030 args))
1031 \n "function " > str \n \n
1032 octave-block-comment-start "usage: " str \n
1033 octave-block-comment-start \n octave-block-comment-start
1034 \n _ \n
1035 "endfunction" > \n)
1037 ;;; Communication with the inferior Octave process
1038 (defun octave-kill-process ()
1039 "Kill inferior Octave process and its buffer."
1040 (interactive)
1041 (if inferior-octave-process
1042 (progn
1043 (process-send-string inferior-octave-process "quit;\n")
1044 (accept-process-output inferior-octave-process)))
1045 (if inferior-octave-buffer
1046 (kill-buffer inferior-octave-buffer)))
1048 (defun octave-show-process-buffer ()
1049 "Make sure that `inferior-octave-buffer' is displayed."
1050 (interactive)
1051 (if (get-buffer inferior-octave-buffer)
1052 (display-buffer inferior-octave-buffer)
1053 (message "No buffer named %s" inferior-octave-buffer)))
1055 (defun octave-hide-process-buffer ()
1056 "Delete all windows that display `inferior-octave-buffer'."
1057 (interactive)
1058 (if (get-buffer inferior-octave-buffer)
1059 (delete-windows-on inferior-octave-buffer)
1060 (message "No buffer named %s" inferior-octave-buffer)))
1062 (defun octave-send-region (beg end)
1063 "Send current region to the inferior Octave process."
1064 (interactive "r")
1065 (inferior-octave t)
1066 (let ((proc inferior-octave-process)
1067 (string (buffer-substring-no-properties beg end))
1068 line)
1069 (with-current-buffer inferior-octave-buffer
1070 (setq inferior-octave-output-list nil)
1071 (while (not (string-equal string ""))
1072 (if (string-match "\n" string)
1073 (setq line (substring string 0 (match-beginning 0))
1074 string (substring string (match-end 0)))
1075 (setq line string string ""))
1076 (setq inferior-octave-receive-in-progress t)
1077 (inferior-octave-send-list-and-digest (list (concat line "\n")))
1078 (while inferior-octave-receive-in-progress
1079 (accept-process-output proc))
1080 (insert-before-markers
1081 (mapconcat 'identity
1082 (append
1083 (if octave-send-echo-input (list line) (list ""))
1084 (mapcar 'inferior-octave-strip-ctrl-g
1085 inferior-octave-output-list)
1086 (list inferior-octave-output-string))
1087 "\n")))))
1088 (if octave-send-show-buffer
1089 (display-buffer inferior-octave-buffer)))
1091 (defun octave-send-block ()
1092 "Send current Octave block to the inferior Octave process."
1093 (interactive)
1094 (save-excursion
1095 (octave-mark-block)
1096 (octave-send-region (point) (mark))))
1098 (defun octave-send-defun ()
1099 "Send current Octave function to the inferior Octave process."
1100 (interactive)
1101 (save-excursion
1102 (mark-defun)
1103 (octave-send-region (point) (mark))))
1105 (defun octave-send-line (&optional arg)
1106 "Send current Octave code line to the inferior Octave process.
1107 With positive prefix ARG, send that many lines.
1108 If `octave-send-line-auto-forward' is non-nil, go to the next unsent
1109 code line."
1110 (interactive "P")
1111 (or arg (setq arg 1))
1112 (if (> arg 0)
1113 (let (beg end)
1114 (beginning-of-line)
1115 (setq beg (point))
1116 (octave-next-code-line (- arg 1))
1117 (end-of-line)
1118 (setq end (point))
1119 (if octave-send-line-auto-forward
1120 (octave-next-code-line 1))
1121 (octave-send-region beg end))))
1123 (defun octave-eval-print-last-sexp ()
1124 "Evaluate Octave sexp before point and print value into current buffer."
1125 (interactive)
1126 (inferior-octave t)
1127 (let ((standard-output (current-buffer))
1128 (print-escape-newlines nil)
1129 (opoint (point)))
1130 (terpri)
1131 (prin1
1132 (save-excursion
1133 (forward-sexp -1)
1134 (inferior-octave-send-list-and-digest
1135 (list (concat (buffer-substring-no-properties (point) opoint)
1136 "\n")))
1137 (mapconcat 'identity inferior-octave-output-list "\n")))
1138 (terpri)))
1140 ;;; Bug reporting
1141 (defun octave-submit-bug-report ()
1142 "Submit a bug report on the Emacs Octave package via mail."
1143 (interactive)
1144 (require 'reporter)
1145 (and
1146 (y-or-n-p "Do you want to submit a bug report? ")
1147 (reporter-submit-bug-report
1148 octave-maintainer-address
1149 (concat "Emacs version " emacs-version)
1150 (list
1151 'octave-blink-matching-block
1152 'octave-block-offset
1153 'octave-comment-char
1154 'octave-continuation-offset
1155 'octave-continuation-string
1156 'octave-send-echo-input
1157 'octave-send-line-auto-forward
1158 'octave-send-show-buffer))))
1160 ;; provide ourself
1162 (provide 'octave-mod)
1164 ;;; octave-mod.el ends here