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