Improve key bindings in edit-abbrevs-mode
[emacs.git] / lisp / progmodes / octave-mod.el
blob7ec4cf3d94771aa74a50c13a50550d47b0df3dfb
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 (save-excursion
672 ;; FIXME: use syntax-ppss?
673 (nth 4 (parse-partial-sexp (line-beginning-position) (point)))))
675 (defsubst octave-in-string-p ()
676 "Return t if point is inside an Octave string."
677 (save-excursion
678 ;; FIXME: use syntax-ppss?
679 (nth 3 (parse-partial-sexp (line-beginning-position) (point)))))
681 (defsubst octave-not-in-string-or-comment-p ()
682 "Return t if point is not inside an Octave string or comment."
683 ;; FIXME: Use syntax-ppss?
684 (let ((pps (parse-partial-sexp (line-beginning-position) (point))))
685 (not (or (nth 3 pps) (nth 4 pps)))))
688 (defun octave-looking-at-kw (regexp)
689 "Like `looking-at', but sets `case-fold-search' nil."
690 (let ((case-fold-search nil))
691 (looking-at regexp)))
693 (defun octave-maybe-insert-continuation-string ()
694 (if (or (octave-in-comment-p)
695 (save-excursion
696 (beginning-of-line)
697 (looking-at octave-continuation-regexp)))
699 (delete-horizontal-space)
700 (insert (concat " " octave-continuation-string))))
703 ;;; Indentation
705 (defun octave-indent-new-comment-line ()
706 "Break Octave line at point, continuing comment if within one.
707 If within code, insert `octave-continuation-string' before breaking the
708 line. If within a string, signal an error.
709 The new line is properly indented."
710 (interactive)
711 (delete-horizontal-space)
712 (cond
713 ((octave-in-comment-p)
714 (indent-new-comment-line))
715 ((octave-in-string-p)
716 (error "Cannot split a code line inside a string"))
718 (insert (concat " " octave-continuation-string))
719 (reindent-then-newline-and-indent))))
721 (defun octave-indent-defun ()
722 "Properly indent the Octave function which contains point."
723 (interactive)
724 (save-excursion
725 (mark-defun)
726 (message "Indenting function...")
727 (indent-region (point) (mark) nil))
728 (message "Indenting function...done."))
731 ;;; Motion
732 (defun octave-next-code-line (&optional arg)
733 "Move ARG lines of Octave code forward (backward if ARG is negative).
734 Skips past all empty and comment lines. Default for ARG is 1.
736 On success, return 0. Otherwise, go as far as possible and return -1."
737 (interactive "p")
738 (or arg (setq arg 1))
739 (beginning-of-line)
740 (let ((n 0)
741 (inc (if (> arg 0) 1 -1)))
742 (while (and (/= arg 0) (= n 0))
743 (setq n (forward-line inc))
744 (while (and (= n 0)
745 (looking-at "\\s-*\\($\\|\\s<\\)"))
746 (setq n (forward-line inc)))
747 (setq arg (- arg inc)))
750 (defun octave-previous-code-line (&optional arg)
751 "Move ARG lines of Octave code backward (forward if ARG is negative).
752 Skips past all empty and comment lines. Default for ARG is 1.
754 On success, return 0. Otherwise, go as far as possible and return -1."
755 (interactive "p")
756 (or arg (setq arg 1))
757 (octave-next-code-line (- arg)))
759 (defun octave-beginning-of-line ()
760 "Move point to beginning of current Octave line.
761 If on an empty or comment line, go to the beginning of that line.
762 Otherwise, move backward to the beginning of the first Octave code line
763 which is not inside a continuation statement, i.e., which does not
764 follow a code line ending in `...' or `\\', or is inside an open
765 parenthesis list."
766 (interactive)
767 (beginning-of-line)
768 (if (not (looking-at "\\s-*\\($\\|\\s<\\)"))
769 (while (or (condition-case nil
770 (progn
771 (up-list -1)
772 (beginning-of-line)
774 (error nil))
775 (and (or (looking-at "\\s-*\\($\\|\\s<\\)")
776 (save-excursion
777 (if (zerop (octave-previous-code-line))
778 (looking-at octave-continuation-regexp))))
779 (zerop (forward-line -1)))))))
781 (defun octave-end-of-line ()
782 "Move point to end of current Octave line.
783 If on an empty or comment line, go to the end of that line.
784 Otherwise, move forward to the end of the first Octave code line which
785 does not end in `...' or `\\' or is inside an open parenthesis list."
786 (interactive)
787 (end-of-line)
788 (if (save-excursion
789 (beginning-of-line)
790 (looking-at "\\s-*\\($\\|\\s<\\)"))
792 (while (or (condition-case nil
793 (progn
794 (up-list 1)
795 (end-of-line)
797 (error nil))
798 (and (save-excursion
799 (beginning-of-line)
800 (or (looking-at "\\s-*\\($\\|\\s<\\)")
801 (looking-at octave-continuation-regexp)))
802 (zerop (forward-line 1)))))
803 (end-of-line)))
805 (defun octave-mark-block ()
806 "Put point at the beginning of this Octave block, mark at the end.
807 The block marked is the one that contains point or follows point."
808 (interactive)
809 (unless (or (looking-at "\\s(")
810 (save-excursion
811 (let* ((token (funcall smie-forward-token-function))
812 (level (assoc token smie-grammar)))
813 (and level (null (cadr level))))))
814 (backward-up-list 1))
815 (mark-sexp))
817 (defun octave-beginning-of-defun (&optional arg)
818 "Move backward to the beginning of an Octave function.
819 With positive ARG, do it that many times. Negative argument -N means
820 move forward to Nth following beginning of a function.
821 Returns t unless search stops at the beginning or end of the buffer."
822 (let* ((arg (or arg 1))
823 (inc (if (> arg 0) 1 -1))
824 (found nil)
825 (case-fold-search nil))
826 (and (not (eobp))
827 (not (and (> arg 0) (looking-at "\\<function\\>")))
828 (skip-syntax-forward "w"))
829 (while (and (/= arg 0)
830 (setq found
831 (re-search-backward "\\<function\\>" inc)))
832 (if (octave-not-in-string-or-comment-p)
833 (setq arg (- arg inc))))
834 (if found
835 (progn
836 (and (< inc 0) (goto-char (match-beginning 0)))
837 t))))
840 ;;; Filling
841 (defun octave-auto-fill ()
842 "Perform auto-fill in Octave mode.
843 Returns nil if no feasible place to break the line could be found, and t
844 otherwise."
845 (let (fc give-up)
846 (if (or (null (setq fc (current-fill-column)))
847 (save-excursion
848 (beginning-of-line)
849 (and auto-fill-inhibit-regexp
850 (octave-looking-at-kw auto-fill-inhibit-regexp))))
851 nil ; Can't do anything
852 (if (and (not (octave-in-comment-p))
853 (> (current-column) fc))
854 (setq fc (- fc (+ (length octave-continuation-string) 1))))
855 (while (and (not give-up) (> (current-column) fc))
856 (let* ((opoint (point))
857 (fpoint
858 (save-excursion
859 (move-to-column (+ fc 1))
860 (skip-chars-backward "^ \t\n")
861 ;; If we're at the beginning of the line, break after
862 ;; the first word
863 (if (bolp)
864 (re-search-forward "[ \t]" opoint t))
865 ;; If we're in a comment line, don't break after the
866 ;; comment chars
867 (if (save-excursion
868 (skip-syntax-backward " <")
869 (bolp))
870 (re-search-forward "[ \t]" (line-end-position)
871 'move))
872 ;; If we're not in a comment line and just ahead the
873 ;; continuation string, don't break here.
874 (if (and (not (octave-in-comment-p))
875 (looking-at
876 (concat "\\s-*"
877 (regexp-quote
878 octave-continuation-string)
879 "\\s-*$")))
880 (end-of-line))
881 (skip-chars-backward " \t")
882 (point))))
883 (if (save-excursion
884 (goto-char fpoint)
885 (not (or (bolp) (eolp))))
886 (let ((prev-column (current-column)))
887 (if (save-excursion
888 (skip-chars-backward " \t")
889 (= (point) fpoint))
890 (progn
891 (octave-maybe-insert-continuation-string)
892 (indent-new-comment-line t))
893 (save-excursion
894 (goto-char fpoint)
895 (octave-maybe-insert-continuation-string)
896 (indent-new-comment-line t)))
897 (if (>= (current-column) prev-column)
898 (setq give-up t)))
899 (setq give-up t))))
900 (not give-up))))
902 (defun octave-fill-paragraph (&optional arg)
903 "Fill paragraph of Octave code, handling Octave comments."
904 ;; FIXME: difference with generic fill-paragraph:
905 ;; - code lines are only split, never joined.
906 ;; - \n that end comments are never removed.
907 ;; - insert continuation marker when splitting code lines.
908 (interactive "P")
909 (save-excursion
910 (let ((end (progn (forward-paragraph) (copy-marker (point) t)))
911 (beg (progn
912 (forward-paragraph -1)
913 (skip-chars-forward " \t\n")
914 (beginning-of-line)
915 (point)))
916 (cfc (current-fill-column))
917 comment-prefix)
918 (goto-char beg)
919 (while (< (point) end)
920 (condition-case nil
921 (indent-according-to-mode)
922 (error nil))
923 (move-to-column cfc)
924 ;; First check whether we need to combine non-empty comment lines
925 (if (and (< (current-column) cfc)
926 (octave-in-comment-p)
927 (not (save-excursion
928 (beginning-of-line)
929 (looking-at "^\\s-*\\s<+\\s-*$"))))
930 ;; This is a nonempty comment line which does not extend
931 ;; past the fill column. If it is followed by a nonempty
932 ;; comment line with the same comment prefix, try to
933 ;; combine them, and repeat this until either we reach the
934 ;; fill-column or there is nothing more to combine.
935 (progn
936 ;; Get the comment prefix
937 (save-excursion
938 (beginning-of-line)
939 (while (and (re-search-forward "\\s<+")
940 (not (octave-in-comment-p))))
941 (setq comment-prefix (match-string 0)))
942 ;; And keep combining ...
943 (while (and (< (current-column) cfc)
944 (save-excursion
945 (forward-line 1)
946 (and (looking-at
947 (concat "^\\s-*"
948 comment-prefix
949 "\\S<"))
950 (not (looking-at
951 (concat "^\\s-*"
952 comment-prefix
953 "\\s-*$"))))))
954 (delete-char 1)
955 (re-search-forward comment-prefix)
956 (delete-region (match-beginning 0) (match-end 0))
957 (fixup-whitespace)
958 (move-to-column cfc))))
959 ;; We might also try to combine continued code lines> Perhaps
960 ;; some other time ...
961 (skip-chars-forward "^ \t\n")
962 (delete-horizontal-space)
963 (if (or (< (current-column) cfc)
964 (and (= (current-column) cfc) (eolp)))
965 (forward-line 1)
966 (if (not (eolp)) (insert " "))
967 (or (octave-auto-fill)
968 (forward-line 1))))
969 t)))
972 ;;; Completions
973 (defun octave-initialize-completions ()
974 "Create an alist for Octave completions."
975 (if octave-completion-alist
977 (setq octave-completion-alist
978 (append octave-reserved-words
979 octave-text-functions
980 octave-variables))))
982 (defun octave-completion-at-point-function ()
983 "Find the text to complete and the corresponding table."
984 (let* ((beg (save-excursion (backward-sexp 1) (point)))
985 (end (point)))
986 (if (< beg (point))
987 ;; Extend region past point, if applicable.
988 (save-excursion (goto-char beg) (forward-sexp 1)
989 (setq end (max end (point)))))
990 (list beg end octave-completion-alist)))
992 (defun octave-complete-symbol ()
993 "Perform completion on Octave symbol preceding point.
994 Compare that symbol against Octave's reserved words and builtin
995 variables."
996 (interactive)
997 (apply 'completion-in-region (octave-completion-at-point-function)))
999 ;;; Electric characters && friends
1001 (defun octave-abbrev-start ()
1002 "Start entering an Octave abbreviation.
1003 If Abbrev mode is turned on, typing ` (grave accent) followed by ? or
1004 \\[help-command] lists all Octave abbrevs. Any other key combination is
1005 executed normally.
1006 Note that all Octave mode abbrevs start with a grave accent."
1007 (interactive)
1008 (if (not abbrev-mode)
1009 (self-insert-command 1)
1010 (let (c)
1011 (insert last-command-event)
1012 (if (if (featurep 'xemacs)
1013 (or (eq (event-to-character (setq c (next-event))) ??)
1014 (eq (event-to-character c) help-char))
1015 (or (eq (setq c (read-event)) ??)
1016 (eq c help-char)))
1017 (let ((abbrev-table-name-list '(octave-abbrev-table)))
1018 (list-abbrevs))
1019 (setq unread-command-events (list c))))))
1021 (define-skeleton octave-insert-defun
1022 "Insert an Octave function skeleton.
1023 Prompt for the function's name, arguments and return values (to be
1024 entered without parens)."
1025 (let* ((defname (substring (buffer-name) 0 -2))
1026 (name (read-string (format "Function name (default %s): " defname)
1027 nil nil defname))
1028 (args (read-string "Arguments: "))
1029 (vals (read-string "Return values: ")))
1030 (format "%s%s (%s)"
1031 (cond
1032 ((string-equal vals "") vals)
1033 ((string-match "[ ,]" vals) (concat "[" vals "] = "))
1034 (t (concat vals " = ")))
1035 name
1036 args))
1037 \n "function " > str \n \n
1038 octave-block-comment-start "usage: " str \n
1039 octave-block-comment-start \n octave-block-comment-start
1040 \n _ \n
1041 "endfunction" > \n)
1043 ;;; Communication with the inferior Octave process
1044 (defun octave-kill-process ()
1045 "Kill inferior Octave process and its buffer."
1046 (interactive)
1047 (if inferior-octave-process
1048 (progn
1049 (process-send-string inferior-octave-process "quit;\n")
1050 (accept-process-output inferior-octave-process)))
1051 (if inferior-octave-buffer
1052 (kill-buffer inferior-octave-buffer)))
1054 (defun octave-show-process-buffer ()
1055 "Make sure that `inferior-octave-buffer' is displayed."
1056 (interactive)
1057 (if (get-buffer inferior-octave-buffer)
1058 (display-buffer inferior-octave-buffer)
1059 (message "No buffer named %s" inferior-octave-buffer)))
1061 (defun octave-hide-process-buffer ()
1062 "Delete all windows that display `inferior-octave-buffer'."
1063 (interactive)
1064 (if (get-buffer inferior-octave-buffer)
1065 (delete-windows-on inferior-octave-buffer)
1066 (message "No buffer named %s" inferior-octave-buffer)))
1068 (defun octave-send-region (beg end)
1069 "Send current region to the inferior Octave process."
1070 (interactive "r")
1071 (inferior-octave t)
1072 (let ((proc inferior-octave-process)
1073 (string (buffer-substring-no-properties beg end))
1074 line)
1075 (with-current-buffer inferior-octave-buffer
1076 (setq inferior-octave-output-list nil)
1077 (while (not (string-equal string ""))
1078 (if (string-match "\n" string)
1079 (setq line (substring string 0 (match-beginning 0))
1080 string (substring string (match-end 0)))
1081 (setq line string string ""))
1082 (setq inferior-octave-receive-in-progress t)
1083 (inferior-octave-send-list-and-digest (list (concat line "\n")))
1084 (while inferior-octave-receive-in-progress
1085 (accept-process-output proc))
1086 (insert-before-markers
1087 (mapconcat 'identity
1088 (append
1089 (if octave-send-echo-input (list line) (list ""))
1090 (mapcar 'inferior-octave-strip-ctrl-g
1091 inferior-octave-output-list)
1092 (list inferior-octave-output-string))
1093 "\n")))))
1094 (if octave-send-show-buffer
1095 (display-buffer inferior-octave-buffer)))
1097 (defun octave-send-block ()
1098 "Send current Octave block to the inferior Octave process."
1099 (interactive)
1100 (save-excursion
1101 (octave-mark-block)
1102 (octave-send-region (point) (mark))))
1104 (defun octave-send-defun ()
1105 "Send current Octave function to the inferior Octave process."
1106 (interactive)
1107 (save-excursion
1108 (mark-defun)
1109 (octave-send-region (point) (mark))))
1111 (defun octave-send-line (&optional arg)
1112 "Send current Octave code line to the inferior Octave process.
1113 With positive prefix ARG, send that many lines.
1114 If `octave-send-line-auto-forward' is non-nil, go to the next unsent
1115 code line."
1116 (interactive "P")
1117 (or arg (setq arg 1))
1118 (if (> arg 0)
1119 (let (beg end)
1120 (beginning-of-line)
1121 (setq beg (point))
1122 (octave-next-code-line (- arg 1))
1123 (end-of-line)
1124 (setq end (point))
1125 (if octave-send-line-auto-forward
1126 (octave-next-code-line 1))
1127 (octave-send-region beg end))))
1129 (defun octave-eval-print-last-sexp ()
1130 "Evaluate Octave sexp before point and print value into current buffer."
1131 (interactive)
1132 (inferior-octave t)
1133 (let ((standard-output (current-buffer))
1134 (print-escape-newlines nil)
1135 (opoint (point)))
1136 (terpri)
1137 (prin1
1138 (save-excursion
1139 (forward-sexp -1)
1140 (inferior-octave-send-list-and-digest
1141 (list (concat (buffer-substring-no-properties (point) opoint)
1142 "\n")))
1143 (mapconcat 'identity inferior-octave-output-list "\n")))
1144 (terpri)))
1146 ;;; Bug reporting
1147 (defun octave-submit-bug-report ()
1148 "Submit a bug report on the Emacs Octave package via mail."
1149 (interactive)
1150 (require 'reporter)
1151 (and
1152 (y-or-n-p "Do you want to submit a bug report? ")
1153 (reporter-submit-bug-report
1154 octave-maintainer-address
1155 (concat "Emacs version " emacs-version)
1156 (list
1157 'octave-blink-matching-block
1158 'octave-block-offset
1159 'octave-comment-char
1160 'octave-continuation-offset
1161 'octave-continuation-string
1162 'octave-send-echo-input
1163 'octave-send-line-auto-forward
1164 'octave-send-show-buffer))))
1166 ;; provide ourself
1168 (provide 'octave-mod)
1170 ;;; octave-mod.el ends here