1 ;;; octave.el --- editing octave source files under emacs -*- lexical-binding: t; -*-
3 ;; Copyright (C) 1997, 2001-2016 Free Software Foundation, Inc.
5 ;; Author: Kurt Hornik <Kurt.Hornik@wu-wien.ac.at>
6 ;; John Eaton <jwe@octave.org>
7 ;; Maintainer: emacs-devel@gnu.org
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/>.
27 ;; This package provides Emacs support for Octave. It defines a major
28 ;; mode for editing Octave code and contains code for interacting with
29 ;; an inferior Octave process using comint.
31 ;; See the documentation of `octave-mode' and `run-octave' for further
32 ;; information on usage and customization.
38 "Editing Octave code."
39 :link '(custom-manual "(octave-mode)Top")
40 :link '(url-link "http://www.gnu.org/s/octave")
41 :link '(custom-group-link :tag "Font Lock Faces group" font-lock-faces)
44 (define-obsolete-function-alias 'octave-submit-bug-report
45 'report-emacs-bug "24.4")
47 (define-abbrev-table 'octave-abbrev-table nil
48 "Abbrev table for Octave's reserved words.
49 Used in `octave-mode' and `inferior-octave-mode' buffers.")
51 (defvar octave-comment-char ?#
52 "Character to start an Octave comment.")
54 (defvar octave-comment-start (char-to-string octave-comment-char)
55 "Octave-specific `comment-start' (which see).")
57 (defvar octave-comment-start-skip "\\(^\\|\\S<\\)\\(?:%!\\|\\s<+\\)\\s-*"
58 "Octave-specific `comment-start-skip' (which see).")
60 (defvar octave-function-header-regexp
61 (concat "^\\s-*\\_<\\(function\\)\\_>"
62 "\\([^=;(\n]*=[ \t]*\\|[ \t]*\\)\\(\\(?:\\w\\|\\s_\\)+\\)\\_>")
63 "Regexp to match an Octave function header.
64 The string `function' and its name are given by the first and third
65 parenthetical grouping.")
68 (defvar octave-mode-map
69 (let ((map (make-sparse-keymap)))
70 (define-key map "\M-." 'octave-find-definition)
71 (define-key map "\M-\C-j" 'octave-indent-new-comment-line)
72 (define-key map "\C-c\C-p" 'octave-previous-code-line)
73 (define-key map "\C-c\C-n" 'octave-next-code-line)
74 (define-key map "\C-c\C-a" 'octave-beginning-of-line)
75 (define-key map "\C-c\C-e" 'octave-end-of-line)
76 (define-key map [remap down-list] 'smie-down-list)
77 (define-key map "\C-c\M-\C-h" 'octave-mark-block)
78 (define-key map "\C-c]" 'smie-close-block)
79 (define-key map "\C-c/" 'smie-close-block)
80 (define-key map "\C-c;" 'octave-update-function-file-comment)
81 (define-key map "\C-hd" 'octave-help)
82 (define-key map "\C-ha" 'octave-lookfor)
83 (define-key map "\C-c\C-l" 'octave-source-file)
84 (define-key map "\C-c\C-f" 'octave-insert-defun)
85 (define-key map "\C-c\C-il" 'octave-send-line)
86 (define-key map "\C-c\C-ib" 'octave-send-block)
87 (define-key map "\C-c\C-if" 'octave-send-defun)
88 (define-key map "\C-c\C-ir" 'octave-send-region)
89 (define-key map "\C-c\C-ia" 'octave-send-buffer)
90 (define-key map "\C-c\C-is" 'octave-show-process-buffer)
91 (define-key map "\C-c\C-iq" 'octave-hide-process-buffer)
92 (define-key map "\C-c\C-ik" 'octave-kill-process)
93 (define-key map "\C-c\C-i\C-l" 'octave-send-line)
94 (define-key map "\C-c\C-i\C-b" 'octave-send-block)
95 (define-key map "\C-c\C-i\C-f" 'octave-send-defun)
96 (define-key map "\C-c\C-i\C-r" 'octave-send-region)
97 (define-key map "\C-c\C-i\C-a" 'octave-send-buffer)
98 (define-key map "\C-c\C-i\C-s" 'octave-show-process-buffer)
99 (define-key map "\C-c\C-i\C-q" 'octave-hide-process-buffer)
100 (define-key map "\C-c\C-i\C-k" 'octave-kill-process)
102 "Keymap used in Octave mode.")
106 (easy-menu-define octave-mode-menu octave-mode-map
107 "Menu for Octave mode."
109 ["Split Line at Point" octave-indent-new-comment-line t]
110 ["Previous Code Line" octave-previous-code-line t]
111 ["Next Code Line" octave-next-code-line t]
112 ["Begin of Line" octave-beginning-of-line t]
113 ["End of Line" octave-end-of-line t]
114 ["Mark Block" octave-mark-block t]
115 ["Close Block" smie-close-block t]
117 ["Start Octave Process" run-octave t]
118 ["Documentation Lookup" info-lookup-symbol t]
119 ["Help on Function" octave-help t]
120 ["Search help" octave-lookfor t]
121 ["Find Function Definition" octave-find-definition t]
122 ["Insert Function" octave-insert-defun t]
123 ["Update Function File Comment" octave-update-function-file-comment t]
125 ["Function Syntax Hints" (eldoc-mode 'toggle)
126 :style toggle :selected (bound-and-true-p eldoc-mode)
127 :help "Display function signatures after typing `SPC' or `('"]
128 ["Delimiter Matching" show-paren-mode
129 :style toggle :selected show-paren-mode
130 :help "Highlight matched pairs such as `if ... end'"
131 :visible (fboundp 'smie--matching-block-data)]
132 ["Auto Fill" auto-fill-mode
133 :style toggle :selected auto-fill-function
134 :help "Automatic line breaking"]
135 ["Electric Layout" electric-layout-mode
136 :style toggle :selected electric-layout-mode
137 :help "Automatically insert newlines around some chars"]
140 ["Send Current Line" octave-send-line t]
141 ["Send Current Block" octave-send-block t]
142 ["Send Current Function" octave-send-defun t]
143 ["Send Region" octave-send-region t]
144 ["Send Buffer" octave-send-buffer t]
145 ["Source Current File" octave-source-file t]
146 ["Show Process Buffer" octave-show-process-buffer t]
147 ["Hide Process Buffer" octave-hide-process-buffer t]
148 ["Kill Process" octave-kill-process t])
150 ["Octave Mode Manual" (info "(octave-mode)Top") t]
151 ["Customize Octave" (customize-group 'octave) t]
152 ["Submit Bug Report" report-emacs-bug t]))
154 (defvar octave-mode-syntax-table
155 (let ((table (make-syntax-table)))
156 (modify-syntax-entry ?\r " " table)
157 (modify-syntax-entry ?+ "." table)
158 (modify-syntax-entry ?- "." table)
159 (modify-syntax-entry ?= "." table)
160 (modify-syntax-entry ?* "." table)
161 (modify-syntax-entry ?/ "." table)
162 (modify-syntax-entry ?> "." table)
163 (modify-syntax-entry ?< "." table)
164 (modify-syntax-entry ?& "." table)
165 (modify-syntax-entry ?| "." table)
166 (modify-syntax-entry ?! "." table)
167 (modify-syntax-entry ?\\ "." table)
168 (modify-syntax-entry ?\' "." table)
169 (modify-syntax-entry ?\` "." table)
170 (modify-syntax-entry ?. "." table)
171 (modify-syntax-entry ?\" "\"" table)
172 (modify-syntax-entry ?_ "_" table)
173 ;; The "b" flag only applies to the second letter of the comstart
174 ;; and the first letter of the comend, i.e. the "4b" below is ineffective.
175 ;; If we try to put `b' on the single-line comments, we get a similar
176 ;; problem where the % and # chars appear as first chars of the 2-char
177 ;; comend, so the multi-line ender is also turned into style-b.
178 ;; So we need the new "c" comment style.
179 (modify-syntax-entry ?\% "< 13" table)
180 (modify-syntax-entry ?\# "< 13" table)
181 (modify-syntax-entry ?\{ "(} 2c" table)
182 (modify-syntax-entry ?\} "){ 4c" table)
183 (modify-syntax-entry ?\n ">" table)
185 "Syntax table in use in `octave-mode' buffers.")
187 (defcustom octave-font-lock-texinfo-comment t
188 "Control whether to highlight the texinfo comment block."
192 (defcustom octave-blink-matching-block t
193 "Control the blinking of matching Octave block keywords.
194 Non-nil means show matching begin of block when inserting a space,
195 newline or semicolon after an else or end keyword."
198 (defcustom octave-block-offset 2
199 "Extra indentation applied to statements in Octave block structures."
202 (defvar octave-block-comment-start
203 (concat (make-string 2 octave-comment-char) " ")
204 "String to insert to start a new Octave comment on an empty line.")
206 (defcustom octave-continuation-offset 4
207 "Extra indentation applied to Octave continuation lines."
211 (defconst octave-continuation-marker-regexp "\\\\\\|\\.\\.\\."))
213 (defvar octave-continuation-regexp
214 (concat "[^#%\n]*\\(" octave-continuation-marker-regexp
215 "\\)\\s-*\\(\\s<.*\\)?$"))
217 ;; Char \ is considered a bad decision for continuing a line.
218 (defconst octave-continuation-string "..."
219 "Character string used for Octave continuation lines.")
221 (defvar octave-mode-imenu-generic-expression
224 (list nil octave-function-header-regexp 3))
225 "Imenu expression for Octave mode. See `imenu-generic-expression'.")
227 (defcustom octave-mode-hook nil
228 "Hook to be run when Octave mode is started."
231 (defcustom octave-send-show-buffer t
232 "Non-nil means display `inferior-octave-buffer' after sending to it."
235 (defcustom octave-send-line-auto-forward t
236 "Control auto-forward after sending to the inferior Octave process.
237 Non-nil means always go to the next Octave code line after sending."
240 (defcustom octave-send-echo-input t
241 "Non-nil means echo input sent to the inferior Octave process."
251 ;; Use '__operators__' in Octave REPL to get a full list?
252 '((assoc ";" "\n") (assoc ",") ;The doc says they have equal precedence!?
253 (right "=" "+=" "-=" "*=" "/=")
254 (assoc "&&") (assoc "||") ; The doc claims they have equal precedence!?
255 (assoc "&") (assoc "|") ; The doc claims they have equal precedence!?
256 (nonassoc "<" "<=" "==" ">=" ">" "!=" "~=")
257 (nonassoc ":") ;No idea what this is.
259 (assoc "*" "/" "\\" ".\\" ".*" "./")
261 (nonassoc "++" "--" "!" "~") ;And unary "+" and "-".
262 (right "^" "**" ".^" ".**")
263 ;; It's not really an operator, but for indentation purposes it
264 ;; could be convenient to treat it as one.
268 ;; We can't distinguish the first element in a sequence with
269 ;; precedence grammars, so we can't distinguish the condition
270 ;; of the `if' from the subsequent body, for example.
271 ;; This has to be done later in the indentation rules.
272 '(("try" exp "catch" exp "end_try_catch")
273 ("unwind_protect" exp
274 "unwind_protect_cleanup" exp "end_unwind_protect")
276 ("parfor" exp "endparfor")
277 ("while" exp "endwhile")
279 ("if" exp "else" exp "endif")
280 ("if" exp "elseif" exp "else" exp "endif")
281 ("if" exp "elseif" exp "elseif" exp "else" exp "endif")
282 ("switch" exp "case" exp "endswitch")
283 ("switch" exp "case" exp "otherwise" exp "endswitch")
284 ("switch" exp "case" exp "case" exp "otherwise" exp "endswitch")
285 ("function" exp "endfunction")
286 ("enumeration" exp "endenumeration")
287 ("events" exp "endevents")
288 ("methods" exp "endmethods")
289 ("properties" exp "endproperties")
290 ("classdef" exp "endclassdef")
295 ;; FIXME: We don't parse these declarations correctly since
296 ;; SMIE *really* likes to parse "a b = 2 c" as "(a b) = (2 c)".
297 ;; IOW to do it right, we'd need to change octave-smie-*ward-token
298 ;; so that the spaces between vars in var-decls are lexed as
299 ;; something like ",".
300 ;; Doesn't seem worth the trouble/slowdown for now.
301 ;; We could hack smie-rules so as to work around the bad parse,
302 ;; but even that doesn't seem worth the trouble.
303 (var-decls (atom "=" atom)) ;; (var-decls "," var-decls)
304 (single-exp (atom "=" atom))
306 ;; We need to mention at least one of the operators in this part
307 ;; of the grammar: if the BNF and the operator table have
308 ;; no overlap, SMIE can't know how they relate.
310 ("do" exp "until" single-exp)
312 ;; For every rule that ends in "endfoo", add a corresponding
313 ;; rule which uses "end" instead.
314 ,@(mapcar (lambda (rule) (nconc (butlast rule) '("end")))
316 ("global" var-decls) ("persistent" var-decls)
317 ;; These aren't super-important, but having them here
318 ;; makes it easier to extract all keywords.
319 ("break") ("continue") ("return")
320 ;; The following rules do not correspond to valid code AFAIK,
321 ;; but they lead to a grammar that degrades more gracefully
322 ;; on incomplete/incorrect code. It also helps us in
323 ;; computing octave--block-offset-keywords.
324 ("try" exp "end") ("unwind_protect" exp "end")
326 ;; (fundesc (atom "=" atom))
329 (defconst octave-smie-grammar
333 (smie-bnf->prec2 bnf-table '((assoc "\n" ";")))
334 (smie-precs->prec2 operator-table)))))
336 (defconst octave-operator-regexp
338 (regexp-opt (remove "\n" (apply #'append
339 (mapcar #'cdr operator-table)))))))
341 ;; Tokenizing needs to be refined so that ";;" is treated as two
342 ;; tokens and also so as to recognize the \n separator (and
343 ;; corresponding continuation lines).
345 (defun octave-smie--funcall-p ()
346 "Return non-nil if we're in an expression context. Moves point."
347 (looking-at "[ \t]*("))
349 (defun octave-smie--end-index-p ()
350 (let ((ppss (syntax-ppss)))
352 (memq (char-after (nth 1 ppss)) '(?\( ?\[ ?\{)))))
354 (defun octave-smie--in-parens-p ()
355 (let ((ppss (syntax-ppss)))
357 (eq ?\( (char-after (nth 1 ppss))))))
359 (defun octave-smie-backward-token ()
361 (forward-comment (- (point)))
363 ((and (not (eq (char-before) ?\;)) ;Coalesce ";" and "\n".
364 (> pos (line-end-position))
365 (if (looking-back octave-continuation-marker-regexp (- (point) 3))
367 (goto-char (match-beginning 0))
368 (forward-comment (- (point)))
371 (not (octave-smie--in-parens-p)))
372 (skip-chars-forward " \t")
373 ;; Why bother distinguishing \n and ;?
375 ((and (looking-back octave-operator-regexp (- (point) 3) 'greedy)
376 ;; Don't mistake a string quote for a transpose.
377 (not (looking-back "\\s\"" (1- (point)))))
378 (goto-char (match-beginning 0))
379 (match-string-no-properties 0))
381 (let ((tok (smie-default-backward-token)))
383 ((equal tok "enumeration")
384 (if (save-excursion (smie-default-forward-token)
385 (octave-smie--funcall-p))
386 "enumeration (function)"
388 ((equal tok "end") (if (octave-smie--end-index-p) "end (index)" tok))
391 (defun octave-smie-forward-token ()
392 (skip-chars-forward " \t")
393 (when (looking-at (eval-when-compile
394 (concat "\\(" octave-continuation-marker-regexp
395 "\\)[ \t]*\\($\\|[%#]\\)")))
396 (goto-char (match-end 1))
399 ((and (looking-at "[%#\n]")
400 (not (or (save-excursion (skip-chars-backward " \t")
401 ;; Only add implicit ; when needed.
402 (or (bolp) (eq (char-before) ?\;)))
403 (octave-smie--in-parens-p))))
404 (if (eolp) (forward-char 1) (forward-comment 1))
405 ;; Why bother distinguishing \n and ;?
407 ((progn (forward-comment (point-max)) nil))
408 ((looking-at ";[ \t]*\\($\\|[%#]\\)")
409 ;; Combine the ; with the subsequent \n.
410 (goto-char (match-beginning 1))
413 ((and (looking-at octave-operator-regexp)
414 ;; Don't mistake a string quote for a transpose.
415 (not (looking-at "\\s\"")))
416 (goto-char (match-end 0))
417 (match-string-no-properties 0))
419 (let ((tok (smie-default-forward-token)))
421 ((equal tok "enumeration")
422 (if (octave-smie--funcall-p)
423 "enumeration (function)"
425 ((equal tok "end") (if (octave-smie--end-index-p) "end (index)" tok))
428 (defconst octave--block-offset-keywords
429 (let* ((end-prec (nth 1 (assoc "end" octave-smie-grammar)))
432 (mapcar (lambda (x) (if (eq end-prec (nth 2 x)) (car x)))
433 octave-smie-grammar))))
434 ;; Not sure if it would harm to keep "switch", but the previous code
435 ;; excluded it, presumably because there shouldn't be any code on
436 ;; the lines between "switch" and "case".
437 (delete "switch" end-matchers)))
439 (defun octave-smie-rules (kind token)
440 (pcase (cons kind token)
441 ;; We could set smie-indent-basic instead, but that would have two
443 ;; - changes to octave-block-offset wouldn't take effect immediately.
444 ;; - edebug wouldn't show the use of this variable.
445 (`(:elem . basic) octave-block-offset)
446 (`(:list-intro . ,(or "global" "persistent")) t)
447 ;; Since "case" is in the same BNF rules as switch..end, SMIE by default
448 ;; aligns it with "switch".
449 (`(:before . "case") (if (not (smie-rule-sibling-p)) octave-block-offset))
451 (if (apply #'smie-rule-parent-p octave--block-offset-keywords)
452 (smie-rule-parent octave-block-offset)
453 ;; For (invalid) code between switch and case.
454 ;; (if (smie-rule-parent-p "switch") 4)
457 (defun octave-indent-comment ()
458 "A function for `smie-indent-functions' (which see)."
460 (back-to-indentation)
462 ((octave-in-string-or-comment-p) nil)
463 ((looking-at-p "\\(\\s<\\)\\1\\{2,\\}")
465 ;; Exclude %{, %} and %!.
466 ((and (looking-at-p "\\s<\\(?:[^{}!]\\|$\\)")
467 (not (looking-at-p "\\(\\s<\\)\\1")))
468 (comment-choose-indent)))))
471 (defvar octave-reserved-words
475 (and (stringp x) (string-match "\\`[[:alpha:]]" x) x))
476 octave-smie-grammar))
477 "Reserved words in Octave.")
479 (defvar octave-font-lock-keywords
481 ;; Fontify all builtin keywords.
482 (cons (concat "\\_<" (regexp-opt octave-reserved-words) "\\_>")
483 'font-lock-keyword-face)
484 ;; Note: 'end' also serves as the last index in an indexing expression,
485 ;; and 'enumerate' is also a function.
486 ;; Ref: http://www.mathworks.com/help/matlab/ref/end.html
487 ;; Ref: http://www.mathworks.com/help/matlab/ref/enumeration.html
488 (list (lambda (limit)
489 (while (re-search-forward "\\_<en\\(?:d\\|umeratio\\(n\\)\\)\\_>"
491 (let ((beg (match-beginning 0))
493 (unless (octave-in-string-or-comment-p)
494 (when (if (match-end 1)
495 (octave-smie--funcall-p)
496 (octave-smie--end-index-p))
497 (put-text-property beg end 'face nil)))))
499 ;; Fontify all operators.
500 (cons octave-operator-regexp 'font-lock-builtin-face)
501 ;; Fontify all function declarations.
502 (list octave-function-header-regexp
503 '(1 font-lock-keyword-face)
504 '(3 font-lock-function-name-face nil t)))
505 "Additional Octave expressions to highlight.")
507 (defun octave-syntax-propertize-function (start end)
509 (octave-syntax-propertize-sqs end)
510 (funcall (syntax-propertize-rules
511 ("\\\\" (0 (when (eq (nth 3 (save-excursion
512 (syntax-ppss (match-beginning 0))))
514 (string-to-syntax "\\"))))
515 ;; Try to distinguish the string-quotes from the transpose-quotes.
516 ("\\(?:^\\|[[({,; ]\\)\\('\\)"
517 (1 (prog1 "\"'" (octave-syntax-propertize-sqs end)))))
520 (defun octave-syntax-propertize-sqs (end)
521 "Propertize the content/end of single-quote strings."
522 (when (eq (nth 3 (syntax-ppss)) ?\')
524 (when (re-search-forward
525 "\\(?:\\=\\|[^']\\)\\(?:''\\)*\\('\\)\\($\\|[^']\\)" end 'move)
526 (goto-char (match-beginning 2))
527 (when (eq (char-before (match-beginning 1)) ?\\)
528 ;; Backslash cannot escape a single quote.
529 (put-text-property (1- (match-beginning 1)) (match-beginning 1)
530 'syntax-table (string-to-syntax ".")))
531 (put-text-property (match-beginning 1) (match-end 1)
532 'syntax-table (string-to-syntax "\"'")))))
534 (defvar electric-layout-rules)
537 (define-derived-mode octave-mode prog-mode "Octave"
538 "Major mode for editing Octave code.
540 Octave is a high-level language, primarily intended for numerical
541 computations. It provides a convenient command line interface
542 for solving linear and nonlinear problems numerically. Function
543 definitions can also be stored in files and used in batch mode.
545 See Info node `(octave-mode) Using Octave Mode' for more details.
549 :abbrev-table octave-abbrev-table
552 (smie-setup octave-smie-grammar #'octave-smie-rules
553 :forward-token #'octave-smie-forward-token
554 :backward-token #'octave-smie-backward-token)
555 (setq-local smie-indent-basic 'octave-block-offset)
556 (add-hook 'smie-indent-functions #'octave-indent-comment nil t)
558 (setq-local smie-blink-matching-triggers
559 (cons ?\; smie-blink-matching-triggers))
560 (unless octave-blink-matching-block
561 (remove-hook 'post-self-insert-hook #'smie-blink-matching-open 'local))
563 (setq-local electric-indent-chars
564 (cons ?\; electric-indent-chars))
565 ;; IIUC matlab-mode takes the opposite approach: it makes RET insert
566 ;; a ";" at those places where it's correct (i.e. outside of parens).
567 (setq-local electric-layout-rules '((?\; . after)))
569 (setq-local comment-use-syntax t)
570 (setq-local comment-start octave-comment-start)
571 (setq-local comment-end "")
572 (setq-local comment-start-skip octave-comment-start-skip)
573 (setq-local comment-add 1)
575 (setq-local parse-sexp-ignore-comments t)
576 (setq-local paragraph-start (concat "\\s-*$\\|" page-delimiter))
577 (setq-local paragraph-separate paragraph-start)
578 (setq-local paragraph-ignore-fill-prefix t)
579 (setq-local fill-paragraph-function 'octave-fill-paragraph)
581 (setq-local fill-nobreak-predicate
582 (lambda () (eq (octave-in-string-p) ?')))
583 (add-function :around (local 'comment-line-break-function)
584 #'octave--indent-new-comment-line)
586 (setq font-lock-defaults '(octave-font-lock-keywords))
588 (setq-local syntax-propertize-function #'octave-syntax-propertize-function)
590 (setq-local imenu-generic-expression octave-mode-imenu-generic-expression)
591 (setq-local imenu-case-fold-search nil)
593 (setq-local add-log-current-defun-function #'octave-add-log-current-defun)
595 (add-hook 'completion-at-point-functions 'octave-completion-at-point nil t)
596 (add-hook 'before-save-hook 'octave-sync-function-file-names nil t)
597 (setq-local beginning-of-defun-function 'octave-beginning-of-defun)
598 (and octave-font-lock-texinfo-comment (octave-font-lock-texinfo-comment))
599 (add-hook 'eldoc-documentation-functions 'octave-eldoc-function nil t)
601 (easy-menu-add octave-mode-menu))
604 (defcustom inferior-octave-program "octave"
605 "Program invoked by `inferior-octave'."
608 (defcustom inferior-octave-buffer "*Inferior Octave*"
609 "Name of buffer for running an inferior Octave process."
612 (defcustom inferior-octave-prompt
613 ;; For Octave >= 3.8, default is always 'octave', see
614 ;; http://hg.savannah.gnu.org/hgweb/octave/rev/708173343c50
615 "\\(?:^octave\\(?:.bin\\|.exe\\)?\\(?:-[.0-9]+\\)?\\(?::[0-9]+\\)?\\|^debug\\|^\\)>+ "
616 "Regexp to match prompts for the inferior Octave process."
619 (defcustom inferior-octave-prompt-read-only comint-prompt-read-only
620 "If non-nil, the Octave prompt is read only.
621 See `comint-prompt-read-only' for details."
625 (defcustom inferior-octave-startup-file
626 (let ((n (file-name-nondirectory inferior-octave-program)))
627 (locate-user-emacs-file (format "init_%s.m" n) (format ".emacs-%s" n)))
628 "Name of the inferior Octave startup file.
629 The contents of this file are sent to the inferior Octave process on
631 :type '(choice (const :tag "None" nil) file)
634 (defcustom inferior-octave-startup-args '("-i" "--no-line-editing")
635 "List of command line arguments for the inferior Octave process.
636 For example, for suppressing the startup message and using `traditional'
637 mode, include \"-q\" and \"--traditional\"."
638 :type '(repeat string)
641 (defcustom inferior-octave-mode-hook nil
642 "Hook to be run when Inferior Octave mode is started."
645 (defcustom inferior-octave-error-regexp-alist
646 '(("error:\\s-*\\(.*?\\) at line \\([0-9]+\\), column \\([0-9]+\\)"
648 ("warning:\\s-*\\([^:\n]+\\):.*at line \\([0-9]+\\), column \\([0-9]+\\)"
650 "Value for `compilation-error-regexp-alist' in inferior octave."
652 :type '(repeat (choice (symbol :tag "Predefined symbol")
653 (sexp :tag "Error specification"))))
655 (defvar inferior-octave-compilation-font-lock-keywords
656 '(("\\_<PASS\\_>" . compilation-info-face)
657 ("\\_<FAIL\\_>" . compilation-error-face)
658 ("\\_<\\(warning\\):" 1 compilation-warning-face)
659 ("\\_<\\(error\\):" 1 compilation-error-face)
660 ("^\\s-*!!!!!.*\\|^.*failed$" . compilation-error-face))
661 "Value for `compilation-mode-font-lock-keywords' in inferior octave.")
663 (defvar inferior-octave-process nil)
665 (defvar inferior-octave-mode-map
666 (let ((map (make-sparse-keymap)))
667 (set-keymap-parent map comint-mode-map)
668 (define-key map "\M-." 'octave-find-definition)
669 (define-key map "\t" 'completion-at-point)
670 (define-key map "\C-hd" 'octave-help)
671 (define-key map "\C-ha" 'octave-lookfor)
672 ;; Same as in `shell-mode'.
673 (define-key map "\M-?" 'comint-dynamic-list-filename-completions)
674 (define-key map "\C-c\C-l" 'inferior-octave-dynamic-list-input-ring)
675 (define-key map [menu-bar inout list-history]
676 '("List Input History" . inferior-octave-dynamic-list-input-ring))
678 "Keymap used in Inferior Octave mode.")
680 (defvar inferior-octave-mode-syntax-table
681 (let ((table (make-syntax-table octave-mode-syntax-table)))
683 "Syntax table in use in `inferior-octave-mode' buffers.")
685 (defvar inferior-octave-font-lock-keywords
687 (cons inferior-octave-prompt 'font-lock-type-face))
688 ;; Could certainly do more font locking in inferior Octave ...
689 "Additional expressions to highlight in Inferior Octave mode.")
691 (defvar inferior-octave-output-list nil)
692 (defvar inferior-octave-output-string nil)
693 (defvar inferior-octave-receive-in-progress nil)
695 (define-obsolete-variable-alias 'inferior-octave-startup-hook
696 'inferior-octave-mode-hook "24.4")
698 (defvar inferior-octave-dynamic-complete-functions
699 '(inferior-octave-completion-at-point comint-filename-completion)
700 "List of functions called to perform completion for inferior Octave.
701 This variable is used to initialize `comint-dynamic-complete-functions'
702 in the Inferior Octave buffer.")
704 (defvar info-lookup-mode)
705 (defvar compilation-error-regexp-alist)
706 (defvar compilation-mode-font-lock-keywords)
708 (declare-function compilation-forget-errors "compile" ())
710 (defun inferior-octave-process-live-p ()
711 (process-live-p inferior-octave-process))
713 (define-derived-mode inferior-octave-mode comint-mode "Inferior Octave"
714 "Major mode for interacting with an inferior Octave process.
716 See Info node `(octave-mode) Running Octave from Within Emacs' for more
720 \\{inferior-octave-mode-map}"
721 :abbrev-table octave-abbrev-table
724 (setq comint-prompt-regexp inferior-octave-prompt)
726 (setq-local comment-use-syntax t)
727 (setq-local comment-start octave-comment-start)
728 (setq-local comment-end "")
729 (setq comment-column 32)
730 (setq-local comment-start-skip octave-comment-start-skip)
732 (setq font-lock-defaults '(inferior-octave-font-lock-keywords nil nil))
734 (setq-local info-lookup-mode 'octave-mode)
735 (add-hook 'eldoc-documentation-functions 'octave-eldoc-function nil t)
737 (setq-local comint-input-ring-file-name
738 (or (getenv "OCTAVE_HISTFILE") "~/.octave_hist"))
739 (setq-local comint-input-ring-size
740 (string-to-number (or (getenv "OCTAVE_HISTSIZE") "1024")))
741 (comint-read-input-ring t)
742 (setq-local comint-dynamic-complete-functions
743 inferior-octave-dynamic-complete-functions)
744 (setq-local comint-prompt-read-only inferior-octave-prompt-read-only)
745 (add-hook 'comint-input-filter-functions
746 'inferior-octave-directory-tracker nil t)
747 ;; http://thread.gmane.org/gmane.comp.gnu.octave.general/48572
748 (add-hook 'window-configuration-change-hook
749 'inferior-octave-track-window-width-change nil t)
750 (setq-local compilation-error-regexp-alist inferior-octave-error-regexp-alist)
751 (setq-local compilation-mode-font-lock-keywords
752 inferior-octave-compilation-font-lock-keywords)
753 (compilation-shell-minor-mode 1)
754 (compilation-forget-errors))
757 (defun inferior-octave (&optional arg)
758 "Run an inferior Octave process, I/O via `inferior-octave-buffer'.
759 This buffer is put in Inferior Octave mode. See `inferior-octave-mode'.
761 Unless ARG is non-nil, switches to this buffer.
763 The elements of the list `inferior-octave-startup-args' are sent as
764 command line arguments to the inferior Octave process on startup.
766 Additional commands to be executed on startup can be provided either in
767 the file specified by `inferior-octave-startup-file' or by the default
768 startup file, `~/.emacs-octave'."
770 (let ((buffer (get-buffer-create inferior-octave-buffer)))
772 (pop-to-buffer buffer))
773 (unless (comint-check-proc buffer)
774 (with-current-buffer buffer
775 (inferior-octave-startup)
776 (inferior-octave-mode)))
780 (defalias 'run-octave 'inferior-octave)
782 (defun inferior-octave-startup ()
783 "Start an inferior Octave process."
784 (let ((proc (comint-exec-1
785 (substring inferior-octave-buffer 1 -1)
786 inferior-octave-buffer
787 inferior-octave-program
789 inferior-octave-startup-args
790 ;; --no-gui is introduced in Octave > 3.7
791 (and (not (member "--no-gui" inferior-octave-startup-args))
792 (zerop (process-file inferior-octave-program
793 nil nil nil "--no-gui" "--help"))
795 (set-process-filter proc 'inferior-octave-output-digest)
796 (setq inferior-octave-process proc
797 inferior-octave-output-list nil
798 inferior-octave-output-string nil
799 inferior-octave-receive-in-progress t)
801 ;; This may look complicated ... However, we need to make sure that
802 ;; we additional startup code only AFTER Octave is ready (otherwise,
803 ;; output may be mixed up). Hence, we need to digest the Octave
804 ;; output to see when it issues a prompt.
805 (while inferior-octave-receive-in-progress
806 (unless (inferior-octave-process-live-p)
807 ;; Spit out the error messages.
808 (when inferior-octave-output-list
809 (princ (concat (mapconcat 'identity inferior-octave-output-list "\n")
811 (process-mark inferior-octave-process)))
812 (error "Process `%s' died" inferior-octave-process))
813 (accept-process-output inferior-octave-process))
814 (goto-char (point-max))
815 (set-marker (process-mark proc) (point))
816 (insert-before-markers
818 (if (not (bobp)) "
\f\n")
819 (if inferior-octave-output-list
821 'identity inferior-octave-output-list "\n")
824 ;; An empty secondary prompt, as e.g. obtained by '--braindead',
826 (inferior-octave-send-list-and-digest (list "PS2\n"))
827 (when (string-match "\\(PS2\\|ans\\) = *$"
828 (car inferior-octave-output-list))
829 (inferior-octave-send-list-and-digest (list "PS2 ('> ');\n")))
831 (inferior-octave-send-list-and-digest
832 (list "disp (getenv ('OCTAVE_SRCDIR'))\n"))
833 (process-put proc 'octave-srcdir
834 (unless (equal (car inferior-octave-output-list) "")
835 (car inferior-octave-output-list)))
837 ;; O.K., now we are ready for the Inferior Octave startup commands.
838 (inferior-octave-send-list-and-digest
840 (unless (equal inferior-octave-output-string ">> ")
841 ;; See http://hg.savannah.gnu.org/hgweb/octave/rev/708173343c50
842 "PS1 ('octave> ');\n")
843 (when (and inferior-octave-startup-file
844 (file-exists-p inferior-octave-startup-file))
845 (format "source ('%s');\n" inferior-octave-startup-file))))
846 (when inferior-octave-output-list
847 (insert-before-markers
848 (mapconcat 'identity inferior-octave-output-list "\n")))
850 ;; And finally, everything is back to normal.
851 (set-process-filter proc 'comint-output-filter)
852 ;; Just in case, to be sure a cd in the startup file won't have
853 ;; detrimental effects.
854 (with-demoted-errors (inferior-octave-resync-dirs))
855 ;; Generate a proper prompt, which is critical to
856 ;; `comint-history-isearch-backward-regexp'. Bug#14433.
857 (comint-send-string proc "\n")))
859 (defun inferior-octave-completion-table ()
860 (completion-table-with-cache
862 (inferior-octave-send-list-and-digest
863 (list (format "completion_matches ('%s');\n" command)))
864 (delete-consecutive-dups
865 (sort inferior-octave-output-list 'string-lessp)))))
867 (defun inferior-octave-completion-at-point ()
868 "Return the data to complete the Octave symbol at point."
869 ;; http://debbugs.gnu.org/14300
870 (unless (string-match-p "/" (or (comint--match-partial-filename) ""))
871 (let ((beg (save-excursion
872 (skip-syntax-backward "w_" (comint-line-beginning-position))
875 (when (and beg (> end beg))
876 (list beg end (completion-table-in-turn
877 (inferior-octave-completion-table)
878 'comint-completion-file-name-table))))))
880 (defun inferior-octave-dynamic-list-input-ring ()
881 "List the buffer's input history in a help buffer."
882 ;; We cannot use `comint-dynamic-list-input-ring', because it replaces
883 ;; "completion" by "history reference" ...
885 (if (or (not (ring-p comint-input-ring))
886 (ring-empty-p comint-input-ring))
887 (message "No history")
889 (history-buffer " *Input History*")
890 (index (1- (ring-length comint-input-ring)))
891 (conf (current-window-configuration)))
892 ;; We have to build up a list ourselves from the ring vector.
894 (setq history (cons (ring-ref comint-input-ring index) history)
896 ;; Change "completion" to "history reference"
897 ;; to make the display accurate.
898 (with-output-to-temp-buffer history-buffer
899 (display-completion-list history)
900 (set-buffer history-buffer))
901 (message "Hit space to flush")
902 (let ((ch (read-event)))
904 (set-window-configuration conf)
905 (push ch unread-command-events))))))
907 (defun inferior-octave-output-digest (_proc string)
908 "Special output filter for the inferior Octave process.
909 Save all output between newlines into `inferior-octave-output-list', and
910 the rest to `inferior-octave-output-string'."
911 (setq string (concat inferior-octave-output-string string))
912 (while (string-match "\n" string)
913 (setq inferior-octave-output-list
914 (append inferior-octave-output-list
915 (list (substring string 0 (match-beginning 0))))
916 string (substring string (match-end 0))))
917 (if (string-match inferior-octave-prompt string)
918 (setq inferior-octave-receive-in-progress nil))
919 (setq inferior-octave-output-string string))
921 (defun inferior-octave-check-process ()
922 (or (inferior-octave-process-live-p)
923 (error (substitute-command-keys
924 "No inferior octave process running. Type \\[run-octave]"))))
926 (defun inferior-octave-send-list-and-digest (list)
927 "Send LIST to the inferior Octave process and digest the output.
928 The elements of LIST have to be strings and are sent one by one. All
929 output is passed to the filter `inferior-octave-output-digest'."
930 (inferior-octave-check-process)
931 (let* ((proc inferior-octave-process)
932 (filter (process-filter proc))
934 (set-process-filter proc 'inferior-octave-output-digest)
935 (setq inferior-octave-output-list nil)
937 (while (setq string (car list))
938 (setq inferior-octave-output-string nil
939 inferior-octave-receive-in-progress t)
940 (comint-send-string proc string)
941 (while inferior-octave-receive-in-progress
942 (accept-process-output proc))
943 (setq list (cdr list)))
944 (set-process-filter proc filter))))
946 (defvar inferior-octave-directory-tracker-resync nil)
947 (make-variable-buffer-local 'inferior-octave-directory-tracker-resync)
949 (defun inferior-octave-directory-tracker (string)
950 "Tracks `cd' commands issued to the inferior Octave process.
951 Use \\[inferior-octave-resync-dirs] to resync if Emacs gets confused."
952 (when inferior-octave-directory-tracker-resync
953 (or (inferior-octave-resync-dirs 'noerror)
954 (setq inferior-octave-directory-tracker-resync nil)))
956 ((string-match "^[ \t]*cd[ \t;]*$" string)
958 ((string-match "^[ \t]*cd[ \t]+\\([^ \t\n;]*\\)[ \t\n;]*" string)
960 (cd (match-string 1 string))
961 (error (setq inferior-octave-directory-tracker-resync t)
963 (error-message-string err)
964 (match-string 1 string)))))))
966 (defun inferior-octave-resync-dirs (&optional noerror)
967 "Resync the buffer's idea of the current directory.
968 This command queries the inferior Octave process about its current
969 directory and makes this the current buffer's default directory."
971 (inferior-octave-send-list-and-digest '("disp (pwd ())\n"))
974 (cd (car inferior-octave-output-list))
976 (error (unless noerror (signal (car err) (cdr err))))))
978 (defcustom inferior-octave-minimal-columns 80
979 "The minimal column width for the inferior Octave process."
983 (defvar inferior-octave-last-column-width nil)
985 (defun inferior-octave-track-window-width-change ()
986 ;; http://thread.gmane.org/gmane.comp.gnu.octave.general/48572
987 (let ((width (max inferior-octave-minimal-columns (window-width))))
988 (unless (eq inferior-octave-last-column-width width)
989 (setq-local inferior-octave-last-column-width width)
990 (when (inferior-octave-process-live-p)
991 (inferior-octave-send-list-and-digest
992 (list (format "putenv ('COLUMNS', '%s');\n" width)))))))
995 ;;; Miscellaneous useful functions
997 (defun octave-in-comment-p ()
998 "Return non-nil if point is inside an Octave comment."
999 (nth 4 (syntax-ppss)))
1001 (defun octave-in-string-p ()
1002 "Return non-nil if point is inside an Octave string."
1003 (nth 3 (syntax-ppss)))
1005 (defun octave-in-string-or-comment-p ()
1006 "Return non-nil if point is inside an Octave string or comment."
1007 (nth 8 (syntax-ppss)))
1009 (defun octave-looking-at-kw (regexp)
1010 "Like `looking-at', but sets `case-fold-search' nil."
1011 (let ((case-fold-search nil))
1012 (looking-at regexp)))
1014 (defun octave-maybe-insert-continuation-string ()
1015 (if (or (octave-in-comment-p)
1018 (looking-at octave-continuation-regexp)))
1020 (delete-horizontal-space)
1021 (insert (concat " " octave-continuation-string))))
1023 (defun octave-completing-read ()
1024 (let ((def (or (thing-at-point 'symbol)
1026 (skip-syntax-backward "-(")
1027 (thing-at-point 'symbol)))))
1029 (format (if def "Function (default %s): " "Function: ") def)
1030 (inferior-octave-completion-table)
1031 nil nil nil nil def)))
1033 (defun octave-goto-function-definition (fn)
1034 "Go to the function definition of FN in current buffer."
1037 (let ((orig (point)) found)
1038 (goto-char (point-min))
1039 (while (and (not found) (re-search-forward re nil t))
1040 (when (and (equal (match-string sub) fn)
1041 (not (nth 8 (syntax-ppss))))
1043 (unless found (goto-char orig))
1045 (pcase (and buffer-file-name (file-name-extension buffer-file-name))
1046 (`"cc" (funcall search
1047 "\\_<DEFUN\\(?:_DLD\\)?\\s-*(\\s-*\\(\\(?:\\sw\\|\\s_\\)+\\)" 1))
1048 (_ (funcall search octave-function-header-regexp 3)))))
1050 (defun octave-function-file-p ()
1051 "Return non-nil if the first token is \"function\".
1052 The value is (START END NAME-START NAME-END) of the function."
1054 (goto-char (point-min))
1055 (when (equal (funcall smie-forward-token-function) "function")
1056 (forward-word-strictly -1)
1057 (let* ((start (point))
1058 (end (progn (forward-sexp 1) (point)))
1061 (re-search-forward octave-function-header-regexp
1063 (list (match-beginning 3) (match-end 3)))))
1064 (cons start (cons end name))))))
1066 ;; Like forward-comment but stop at non-comment blank
1067 (defun octave-skip-comment-forward (limit)
1068 (let ((ppss (syntax-ppss)))
1070 (goto-char (nth 8 ppss))
1071 (goto-char (or (comment-search-forward limit t) (point)))))
1072 (while (and (< (point) limit) (looking-at-p "\\s<"))
1073 (forward-comment 1)))
1075 ;;; First non-copyright comment block
1076 (defun octave-function-file-comment ()
1077 "Beginning and end positions of the function file comment."
1079 (goto-char (point-min))
1080 ;; Copyright block: octave/libinterp/parse-tree/lex.ll around line 1634
1081 (while (save-excursion
1082 (when (comment-search-forward (point-max) t)
1083 (when (eq (char-after) ?\{) ; case of block comment
1085 (skip-syntax-forward "-")
1086 (let ((case-fold-search t))
1087 (looking-at-p "\\(?:copyright\\|author\\)\\_>"))))
1088 (octave-skip-comment-forward (point-max)))
1089 (let ((beg (comment-search-forward (point-max) t)))
1092 (octave-skip-comment-forward (point-max))
1093 (list beg (point))))))
1095 (defun octave-sync-function-file-names ()
1096 "Ensure function name agree with function file name.
1097 See Info node `(octave)Function Files'."
1099 (when buffer-file-name
1100 (pcase-let ((`(,start ,_end ,name-start ,name-end)
1101 (octave-function-file-p)))
1102 (when (and start name-start)
1103 (let* ((func (buffer-substring name-start name-end))
1104 (file (file-name-sans-extension
1105 (file-name-nondirectory buffer-file-name)))
1106 (help-form (format-message "\
1107 a: Use function name `%s'
1108 b: Use file name `%s'
1109 q: Don't fix\n" func file))
1110 (c (unless (equal file func)
1111 (save-window-excursion
1114 "Which name to use? (a/b/q) " '(?a ?b ?q))))))
1116 (`?a (let ((newname (expand-file-name
1117 (concat func (file-name-extension
1118 buffer-file-name t)))))
1119 (when (or (not (file-exists-p newname))
1121 (format "Target file %s exists; proceed? " newname)))
1122 (when (file-exists-p buffer-file-name)
1123 (rename-file buffer-file-name newname t))
1124 (set-visited-file-name newname))))
1125 (`?b (save-excursion
1126 (goto-char name-start)
1127 (delete-region name-start name-end)
1128 (insert file)))))))))
1130 (defun octave-update-function-file-comment (beg end)
1131 "Query replace function names in function file comment."
1134 (barf-if-buffer-read-only)
1136 (list (region-beginning) (region-end))
1137 (or (octave-function-file-comment)
1138 (error "No function file comment found")))))
1140 (let* ((bounds (or (octave-function-file-p)
1141 (error "Not in a function file buffer")))
1142 (func (if (cddr bounds)
1143 (apply #'buffer-substring (cddr bounds))
1144 (error "Function name not found")))
1147 (when (re-search-forward
1148 "[=}]\\s-*\\(\\(?:\\sw\\|\\s_\\)+\\)\\_>"
1149 (min (line-end-position 4) end)
1152 (old-func (read-string (format (if old-func
1153 "Name to replace (default %s): "
1154 "Name to replace: ")
1157 (if (and func old-func (not (equal func old-func)))
1158 (perform-replace old-func func 'query
1159 nil 'delimited nil nil beg end)
1160 (message "Function names match")))))
1162 (defface octave-function-comment-block
1163 '((t (:inherit font-lock-doc-face)))
1164 "Face used to highlight function comment block.")
1166 (eval-when-compile (require 'texinfo))
1168 (defun octave-font-lock-texinfo-comment ()
1173 (if (numberp (nth 1 kw))
1174 `(,(nth 0 kw) ,(nth 1 kw) ,(nth 2 kw) prepend)
1175 (message "Ignoring Texinfo highlight: %S" kw)))
1176 texinfo-font-lock-keywords)))))
1177 (font-lock-add-keywords
1180 (while (and (< (point) limit)
1181 (search-forward "-*- texinfo -*-" limit t)
1182 (octave-in-comment-p))
1183 (let ((beg (nth 8 (syntax-ppss)))
1185 (octave-skip-comment-forward (point-max))
1187 (put-text-property beg end 'font-lock-multiline t)
1188 (font-lock-prepend-text-property
1189 beg end 'face 'octave-function-comment-block)
1192 (while (re-search-forward (car kw) end 'move)
1193 (font-lock-apply-highlight (cdr kw))))))
1200 (defun octave-indent-new-comment-line (&optional soft)
1201 "Break Octave line at point, continuing comment if within one.
1202 Insert `octave-continuation-string' before breaking the line
1203 unless inside a list. Signal an error if within a single-quoted
1206 (funcall comment-line-break-function soft))
1208 (defun octave--indent-new-comment-line (orig &rest args)
1210 ((octave-in-comment-p) nil)
1211 ((eq (octave-in-string-p) ?')
1212 (error "Cannot split a single-quoted string"))
1213 ((eq (octave-in-string-p) ?\")
1214 (insert octave-continuation-string))
1216 (delete-horizontal-space)
1217 (unless (and (cadr (syntax-ppss))
1218 (eq (char-after (cadr (syntax-ppss))) ?\())
1219 (insert " " octave-continuation-string))))
1221 (indent-according-to-mode))
1223 (define-obsolete-function-alias
1224 'octave-indent-defun 'prog-indent-sexp "24.4")
1228 (defun octave-next-code-line (&optional arg)
1229 "Move ARG lines of Octave code forward (backward if ARG is negative).
1230 Skips past all empty and comment lines. Default for ARG is 1.
1232 On success, return 0. Otherwise, go as far as possible and return -1."
1234 (or arg (setq arg 1))
1237 (inc (if (> arg 0) 1 -1)))
1238 (while (and (/= arg 0) (= n 0))
1239 (setq n (forward-line inc))
1241 (looking-at "\\s-*\\($\\|\\s<\\)"))
1242 (setq n (forward-line inc)))
1243 (setq arg (- arg inc)))
1246 (defun octave-previous-code-line (&optional arg)
1247 "Move ARG lines of Octave code backward (forward if ARG is negative).
1248 Skips past all empty and comment lines. Default for ARG is 1.
1250 On success, return 0. Otherwise, go as far as possible and return -1."
1252 (or arg (setq arg 1))
1253 (octave-next-code-line (- arg)))
1255 (defun octave-beginning-of-line ()
1256 "Move point to beginning of current Octave line.
1257 If on an empty or comment line, go to the beginning of that line.
1258 Otherwise, move backward to the beginning of the first Octave code line
1259 which is not inside a continuation statement, i.e., which does not
1260 follow a code line ending with `...' or is inside an open
1264 (unless (looking-at "\\s-*\\($\\|\\s<\\)")
1265 (while (or (when (cadr (syntax-ppss))
1266 (goto-char (cadr (syntax-ppss)))
1269 (and (or (looking-at "\\s-*\\($\\|\\s<\\)")
1271 (if (zerop (octave-previous-code-line))
1272 (looking-at octave-continuation-regexp))))
1273 (zerop (forward-line -1)))))))
1275 (defun octave-end-of-line ()
1276 "Move point to end of current Octave line.
1277 If on an empty or comment line, go to the end of that line.
1278 Otherwise, move forward to the end of the first Octave code line which
1279 does not end with `...' or is inside an open parenthesis list."
1282 (unless (save-excursion
1284 (looking-at "\\s-*\\($\\|\\s<\\)"))
1285 (while (or (when (cadr (syntax-ppss))
1292 (and (save-excursion
1294 (or (looking-at "\\s-*\\($\\|\\s<\\)")
1295 (looking-at octave-continuation-regexp)))
1296 (zerop (forward-line 1)))))
1299 (defun octave-mark-block ()
1300 "Put point at the beginning of this Octave block, mark at the end.
1301 The block marked is the one that contains point or follows point."
1303 (if (and (looking-at "\\sw\\|\\s_")
1304 (looking-back "\\sw\\|\\s_" (1- (point))))
1305 (skip-syntax-forward "w_"))
1306 (unless (or (looking-at "\\s(")
1308 (let* ((token (funcall smie-forward-token-function))
1309 (level (assoc token smie-grammar)))
1310 (and level (not (numberp (cadr level)))))))
1311 (backward-up-list 1))
1314 (defun octave-beginning-of-defun (&optional arg)
1315 "Octave-specific `beginning-of-defun-function' (which see)."
1316 (or arg (setq arg 1))
1317 ;; Move out of strings or comments.
1318 (when (octave-in-string-or-comment-p)
1319 (goto-char (octave-in-string-or-comment-p)))
1320 (letrec ((orig (point))
1321 (toplevel (lambda (pos)
1324 (backward-up-list 1)
1325 (funcall toplevel (point)))
1326 (scan-error pos)))))
1327 (goto-char (funcall toplevel (point)))
1328 (when (and (> arg 0) (/= orig (point)))
1329 (setq arg (1- arg)))
1330 (forward-sexp (- arg))
1331 (and (< arg 0) (forward-sexp -1))
1334 (defun octave-fill-paragraph (&optional _arg)
1335 "Fill paragraph of Octave code, handling Octave comments."
1336 ;; FIXME: difference with generic fill-paragraph:
1337 ;; - code lines are only split, never joined.
1338 ;; - \n that end comments are never removed.
1339 ;; - insert continuation marker when splitting code lines.
1342 (let ((end (progn (forward-paragraph) (copy-marker (point) t)))
1344 (forward-paragraph -1)
1345 (skip-chars-forward " \t\n")
1348 (cfc (current-fill-column))
1351 (while (< (point) end)
1353 (indent-according-to-mode)
1355 (move-to-column cfc)
1356 ;; First check whether we need to combine non-empty comment lines
1357 (if (and (< (current-column) cfc)
1358 (octave-in-comment-p)
1359 (not (save-excursion
1361 (looking-at "^\\s-*\\s<+\\s-*$"))))
1362 ;; This is a nonempty comment line which does not extend
1363 ;; past the fill column. If it is followed by a nonempty
1364 ;; comment line with the same comment prefix, try to
1365 ;; combine them, and repeat this until either we reach the
1366 ;; fill-column or there is nothing more to combine.
1368 ;; Get the comment prefix
1371 (while (and (re-search-forward "\\s<+")
1372 (not (octave-in-comment-p))))
1373 (setq comment-prefix (match-string 0)))
1374 ;; And keep combining ...
1375 (while (and (< (current-column) cfc)
1387 (re-search-forward comment-prefix)
1388 (delete-region (match-beginning 0) (match-end 0))
1390 (move-to-column cfc))))
1391 ;; We might also try to combine continued code lines> Perhaps
1392 ;; some other time ...
1393 (skip-chars-forward "^ \t\n")
1394 (delete-horizontal-space)
1395 (if (or (< (current-column) cfc)
1396 (and (= (current-column) cfc) (eolp)))
1398 (if (not (eolp)) (insert " "))
1399 (or (funcall normal-auto-fill-function)
1403 (defun octave-completion-at-point ()
1404 "Find the text to complete and the corresponding table."
1405 (let* ((beg (save-excursion (skip-syntax-backward "w_") (point)))
1408 ;; Extend region past point, if applicable.
1409 (save-excursion (skip-syntax-forward "w_")
1410 (setq end (point))))
1412 (list beg end (or (and (inferior-octave-process-live-p)
1413 (inferior-octave-completion-table))
1414 octave-reserved-words)))))
1416 (defun octave-add-log-current-defun ()
1417 "A function for `add-log-current-defun-function' (which see)."
1420 (and (beginning-of-defun)
1421 (re-search-forward octave-function-header-regexp
1422 (line-end-position) t)
1426 ;;; Electric characters && friends
1427 (define-skeleton octave-insert-defun
1428 "Insert an Octave function skeleton.
1429 Prompt for the function's name, arguments and return values (to be
1430 entered without parens)."
1431 (let* ((defname (file-name-sans-extension (buffer-name)))
1432 (name (read-string (format "Function name (default %s): " defname)
1434 (args (read-string "Arguments: "))
1435 (vals (read-string "Return values: ")))
1438 ((string-equal vals "") vals)
1439 ((string-match "[ ,]" vals) (concat "[" vals "] = "))
1440 (t (concat vals " = ")))
1443 \n octave-block-comment-start "usage: " str \n
1444 octave-block-comment-start '(delete-horizontal-space) \n
1445 octave-block-comment-start '(delete-horizontal-space) \n
1446 "function " > str \n
1450 ;;; Communication with the inferior Octave process
1451 (defun octave-kill-process ()
1452 "Kill inferior Octave process and its buffer."
1454 (when (and (buffer-live-p (get-buffer inferior-octave-buffer))
1455 (or (yes-or-no-p (format "Kill %S and its buffer? "
1456 inferior-octave-process))
1457 (user-error "Aborted")))
1458 (when (inferior-octave-process-live-p)
1459 (set-process-query-on-exit-flag inferior-octave-process nil)
1460 (process-send-string inferior-octave-process "quit;\n")
1461 (accept-process-output inferior-octave-process))
1462 (kill-buffer inferior-octave-buffer)))
1464 (defun octave-show-process-buffer ()
1465 "Make sure that `inferior-octave-buffer' is displayed."
1467 (if (get-buffer inferior-octave-buffer)
1468 (display-buffer inferior-octave-buffer)
1469 (message "No buffer named %s" inferior-octave-buffer)))
1471 (defun octave-hide-process-buffer ()
1472 "Delete all windows that display `inferior-octave-buffer'."
1474 (if (get-buffer inferior-octave-buffer)
1475 (delete-windows-on inferior-octave-buffer)
1476 (message "No buffer named %s" inferior-octave-buffer)))
1478 (defun octave-source-file (file)
1479 "Execute FILE in the inferior Octave process.
1480 This is done using Octave's source function. FILE defaults to
1481 current buffer file unless called with a prefix arg \\[universal-argument]."
1482 (interactive (list (or (and (not current-prefix-arg) buffer-file-name)
1483 (read-file-name "File: " nil nil t))))
1485 (signal 'wrong-type-argument (list 'stringp file)))
1487 (with-current-buffer inferior-octave-buffer
1488 (comint-send-string inferior-octave-process
1489 (format "source '%s'\n" file))))
1491 (defun octave-send-region (beg end)
1492 "Send current region to the inferior Octave process."
1495 (let ((proc inferior-octave-process)
1496 (string (buffer-substring-no-properties beg end))
1498 (with-current-buffer inferior-octave-buffer
1499 ;; http://lists.gnu.org/archive/html/emacs-devel/2013-10/msg00095.html
1500 (compilation-forget-errors)
1501 (setq inferior-octave-output-list nil)
1502 (while (not (string-equal string ""))
1503 (if (string-match "\n" string)
1504 (setq line (substring string 0 (match-beginning 0))
1505 string (substring string (match-end 0)))
1506 (setq line string string ""))
1507 (setq inferior-octave-receive-in-progress t)
1508 (inferior-octave-send-list-and-digest (list (concat line "\n")))
1509 (while inferior-octave-receive-in-progress
1510 (accept-process-output proc))
1511 (insert-before-markers
1512 (mapconcat 'identity
1514 (if octave-send-echo-input (list line) (list ""))
1515 inferior-octave-output-list
1516 (list inferior-octave-output-string))
1518 (if octave-send-show-buffer
1519 (display-buffer inferior-octave-buffer)))
1521 (defun octave-send-buffer ()
1522 "Send current buffer to the inferior Octave process."
1524 (octave-send-region (point-min) (point-max)))
1526 (defun octave-send-block ()
1527 "Send current Octave block to the inferior Octave process."
1531 (octave-send-region (point) (mark))))
1533 (defun octave-send-defun ()
1534 "Send current Octave function to the inferior Octave process."
1538 (octave-send-region (point) (mark))))
1540 (defun octave-send-line (&optional arg)
1541 "Send current Octave code line to the inferior Octave process.
1542 With positive prefix ARG, send that many lines.
1543 If `octave-send-line-auto-forward' is non-nil, go to the next unsent
1546 (or arg (setq arg 1))
1551 (octave-next-code-line (- arg 1))
1554 (if octave-send-line-auto-forward
1555 (octave-next-code-line 1))
1556 (octave-send-region beg end))))
1558 (defun octave-eval-print-last-sexp ()
1559 "Evaluate Octave sexp before point and print value into current buffer."
1562 (let ((standard-output (current-buffer))
1563 (print-escape-newlines nil)
1569 (inferior-octave-send-list-and-digest
1570 (list (concat (buffer-substring-no-properties (point) opoint)
1572 (mapconcat 'identity inferior-octave-output-list "\n")))
1577 (defcustom octave-eldoc-message-style 'auto
1578 "Octave eldoc message style: auto, oneline, multiline."
1579 :type '(choice (const :tag "Automatic" auto)
1580 (const :tag "One Line" oneline)
1581 (const :tag "Multi Line" multiline))
1584 ;; (FN SIGNATURE1 SIGNATURE2 ...)
1585 (defvar octave-eldoc-cache nil)
1587 (defun octave-eldoc-function-signatures (fn)
1588 (unless (equal fn (car octave-eldoc-cache))
1589 (inferior-octave-send-list-and-digest
1590 (list (format "print_usage ('%s');\n" fn)))
1592 (dolist (line inferior-octave-output-list)
1594 "\\s-*\\(?:--[^:]+\\|usage\\):\\s-*\\(.*\\)$"
1596 (push (match-string 1 line) result)))
1597 (setq octave-eldoc-cache
1598 (cons (substring-no-properties fn)
1599 (nreverse result)))))
1600 (cdr octave-eldoc-cache))
1602 (defun octave-eldoc-function ()
1603 "A function for `eldoc-documentation-function' (which see)."
1604 (when (inferior-octave-process-live-p)
1605 (let* ((ppss (syntax-ppss))
1606 (paren-pos (cadr ppss))
1609 ;; PAREN-POS must be after the prompt
1611 (if (eq (get-buffer-process (current-buffer))
1612 inferior-octave-process)
1613 (process-mark inferior-octave-process)
1615 (or (not (eq (get-buffer-process (current-buffer))
1616 inferior-octave-process))
1617 (< (process-mark inferior-octave-process)
1619 (eq (char-after paren-pos) ?\())
1620 (goto-char paren-pos)
1621 (setq paren-pos nil))
1622 (when (or (< (skip-syntax-backward "-") 0) paren-pos)
1623 (thing-at-point 'symbol))))
1624 (sigs (and fn (octave-eldoc-function-signatures fn)))
1625 (oneline (mapconcat 'identity sigs
1626 (propertize " | " 'face 'warning)))
1627 (multiline (mapconcat (lambda (s) (concat "-- " s)) sigs "\n")))
1629 ;; Return the value according to style.
1630 (pcase octave-eldoc-message-style
1631 (`auto (if (< (length oneline) (window-width (minibuffer-window)))
1635 (`multiline multiline)))))
1637 (defcustom octave-help-buffer "*Octave Help*"
1638 "Buffer name for `octave-help'."
1642 ;; Used in a mode derived from help-mode.
1643 (declare-function help-button-action "help-mode" (button))
1645 (define-button-type 'octave-help-file
1647 'action #'help-button-action
1648 'help-function 'octave-find-definition)
1650 (define-button-type 'octave-help-function
1654 (buffer-substring (button-start b) (button-end b)))))
1656 (defvar octave-help-mode-map
1657 (let ((map (make-sparse-keymap)))
1658 (define-key map "\M-." 'octave-find-definition)
1659 (define-key map "\C-hd" 'octave-help)
1660 (define-key map "\C-ha" 'octave-lookfor)
1663 (define-derived-mode octave-help-mode help-mode "OctHelp"
1664 "Major mode for displaying Octave documentation."
1666 :syntax-table octave-mode-syntax-table
1667 (eval-and-compile (require 'help-mode))
1668 ;; Don't highlight `EXAMPLE' as elisp symbols by using a regexp that
1670 (setq-local help-xref-symbol-regexp "x\\`"))
1672 (defun octave-help (fn)
1673 "Display the documentation of FN."
1674 (interactive (list (octave-completing-read)))
1675 (inferior-octave-send-list-and-digest
1676 (list (format "help ('%s');\n" fn)))
1677 (let ((lines inferior-octave-output-list)
1678 (inhibit-read-only t))
1679 (when (string-match "error: \\(.*\\)$" (car lines))
1680 (error "%s" (match-string 1 (car lines))))
1681 (with-help-window octave-help-buffer
1682 (princ (mapconcat 'identity lines "\n"))
1683 (with-current-buffer octave-help-buffer
1684 ;; Bound to t so that `help-buffer' returns current buffer for
1685 ;; `help-setup-xref'.
1686 (let ((help-xref-following t))
1687 (help-setup-xref (list 'octave-help fn)
1688 (called-interactively-p 'interactive)))
1689 ;; Note: can be turned off by suppress_verbose_help_message.
1691 ;; Remove boring trailing text: Additional help for built-in functions
1692 ;; and operators ...
1693 (goto-char (point-max))
1694 (when (search-backward "\n\n\n" nil t)
1695 (goto-char (match-beginning 0))
1696 (delete-region (point) (point-max)))
1697 ;; File name highlight
1698 (goto-char (point-min))
1699 (when (re-search-forward "from the file \\(.*\\)$"
1702 (let* ((file (match-string 1))
1703 (dir (file-name-directory
1704 (directory-file-name (file-name-directory file)))))
1705 (replace-match "" nil nil nil 1)
1706 (insert (substitute-command-keys "`"))
1707 ;; Include the parent directory which may be regarded as
1708 ;; the category for the FN.
1709 (help-insert-xref-button (file-relative-name file dir)
1710 'octave-help-file fn)
1711 (insert (substitute-command-keys "'"))))
1712 ;; Make 'See also' clickable.
1713 (with-syntax-table octave-mode-syntax-table
1714 (when (re-search-forward "^\\s-*See also:" nil t)
1715 (let ((end (save-excursion (re-search-forward "^\\s-*$" nil t))))
1716 (while (re-search-forward
1717 "\\s-*\\([^,\n]+?\\)\\s-*\\(?:[,]\\|[.]?$\\)" end t)
1718 (make-text-button (match-beginning 1) (match-end 1)
1719 :type 'octave-help-function)))))
1720 (octave-help-mode)))))
1722 (defun octave-lookfor (str &optional all)
1723 "Search for the string STR in all function help strings.
1724 If ALL is non-nil search the entire help string else only search the first
1726 (interactive "sSearch for: \nP")
1727 (inferior-octave-send-list-and-digest
1728 (list (format "lookfor (%s'%s');\n"
1729 (if all "'-all', " "")
1731 (let ((lines inferior-octave-output-list))
1732 (when (and (stringp (car lines))
1733 (string-match "error: \\(.*\\)$" (car lines)))
1734 (error "%s" (match-string 1 (car lines))))
1735 (with-help-window octave-help-buffer
1736 (with-current-buffer octave-help-buffer
1738 (insert (mapconcat 'identity lines "\n"))
1739 (insert (format "Nothing found for \"%s\".\n" str)))
1740 ;; Bound to t so that `help-buffer' returns current buffer for
1741 ;; `help-setup-xref'.
1742 (let ((help-xref-following t))
1743 (help-setup-xref (list 'octave-lookfor str all)
1744 (called-interactively-p 'interactive)))
1745 (goto-char (point-min))
1747 (while (re-search-forward "^\\([^[:blank:]]+\\) " nil 'noerror)
1748 (make-text-button (match-beginning 1) (match-end 1)
1749 :type 'octave-help-function)))
1751 (goto-char (point-max))
1752 (insert "\nRetry with ")
1753 (insert-text-button "'-all'"
1755 'action #'(lambda (_b)
1756 (octave-lookfor str '-all)))
1758 (octave-help-mode)))))
1760 (defcustom octave-source-directories nil
1761 "A list of directories for Octave sources.
1762 If the environment variable OCTAVE_SRCDIR is set, it is searched first."
1763 :type '(repeat directory)
1766 (defun octave-source-directories ()
1767 (let ((srcdir (or (and inferior-octave-process
1768 (process-get inferior-octave-process 'octave-srcdir))
1769 (getenv "OCTAVE_SRCDIR"))))
1771 (cons srcdir octave-source-directories)
1772 octave-source-directories)))
1774 (defvar octave-find-definition-filename-function
1775 #'octave-find-definition-default-filename)
1777 (defun octave-find-definition-default-filename (name)
1778 "Default value for `octave-find-definition-filename-function'."
1779 (pcase (file-name-extension name)
1781 (octave-find-definition-default-filename
1782 (concat "libinterp/dldfcn/"
1783 (file-name-sans-extension (file-name-nondirectory name))
1786 (let ((file (or (locate-file name (octave-source-directories))
1787 (locate-file (file-name-nondirectory name)
1788 (octave-source-directories)))))
1789 (or (and file (file-exists-p file))
1790 (error "File `%s' not found" name))
1793 (if (yes-or-no-p (format-message "File `%s' may be binary; open? "
1794 (file-name-nondirectory name)))
1796 (user-error "Aborted")))
1799 (defvar find-tag-marker-ring)
1801 (defun octave-find-definition (fn)
1802 "Find the definition of FN.
1803 Functions implemented in C++ can be found if
1804 variable `octave-source-directories' is set correctly."
1805 (interactive (list (octave-completing-read)))
1807 (let ((orig (point)))
1808 (if (and (derived-mode-p 'octave-mode)
1809 (octave-goto-function-definition fn))
1810 (ring-insert find-tag-marker-ring (copy-marker orig))
1811 (inferior-octave-send-list-and-digest
1812 ;; help NAME is more verbose
1814 if iskeyword('%s') disp('`%s'' is a keyword') else which('%s') endif\n"
1817 ;; Skip garbage lines such as
1818 ;; warning: fmincg.m: possible Matlab-style ....
1819 (while (and (not file) (consp inferior-octave-output-list))
1820 (setq line (pop inferior-octave-output-list))
1821 (when (string-match "from the file \\(.*\\)$" line)
1822 (setq file (match-string 1 line))))
1824 (user-error "%s" (or line (format-message "`%s' not found" fn)))
1825 (ring-insert find-tag-marker-ring (point-marker))
1826 (setq file (funcall octave-find-definition-filename-function file))
1829 (octave-goto-function-definition fn)))))))
1832 ;;; octave.el ends here