1 ;;; octave.el --- editing octave source files under emacs -*- lexical-binding: t; -*-
3 ;; Copyright (C) 1997, 2001-2013 Free Software Foundation, Inc.
5 ;; Author: Kurt Hornik <Kurt.Hornik@wu-wien.ac.at>
6 ;; John Eaton <jwe@octave.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.
40 (unless (fboundp 'user-error)
41 (defalias 'user-error 'error))
42 (unless (fboundp 'delete-consecutive-dups)
43 (defalias 'delete-consecutive-dups 'delete-dups)))
45 (unless (fboundp 'setq-local)
46 (defmacro setq-local (var val)
47 "Set variable VAR to value VAL in current buffer."
48 (list 'set (list 'make-local-variable (list 'quote var)) val))))
51 "Editing Octave code."
52 :link '(custom-group-link :tag "Font Lock Faces group" font-lock-faces)
55 (define-obsolete-function-alias 'octave-submit-bug-report
56 'report-emacs-bug "24.4")
58 (define-abbrev-table 'octave-abbrev-table nil
59 "Abbrev table for Octave's reserved words.
60 Used in `octave-mode' and `inferior-octave-mode' buffers.")
62 (defvar octave-comment-char ?#
63 "Character to start an Octave comment.")
65 (defvar octave-comment-start (char-to-string octave-comment-char)
66 "Octave-specific `comment-start' (which see).")
68 (defvar octave-comment-start-skip "\\(^\\|\\S<\\)\\(?:%!\\|\\s<+\\)\\s-*"
69 "Octave-specific `comment-start-skip' (which see).")
71 (defvar octave-begin-keywords
72 '("classdef" "do" "enumeration" "events" "for" "function" "if" "methods"
73 "parfor" "properties" "switch" "try" "unwind_protect" "while"))
75 (defvar octave-else-keywords
76 '("case" "catch" "else" "elseif" "otherwise" "unwind_protect_cleanup"))
78 (defvar octave-end-keywords
79 '("endclassdef" "endenumeration" "endevents" "endfor" "endfunction" "endif"
80 "endmethods" "endparfor" "endproperties" "endswitch" "end_try_catch"
81 "end_unwind_protect" "endwhile" "until" "end"))
83 (defvar octave-reserved-words
84 (append octave-begin-keywords
87 '("break" "continue" "global" "persistent" "return"))
88 "Reserved words in Octave.")
90 (defvar octave-function-header-regexp
91 (concat "^\\s-*\\_<\\(function\\)\\_>"
92 "\\([^=;(\n]*=[ \t]*\\|[ \t]*\\)\\(\\(?:\\w\\|\\s_\\)+\\)\\_>")
93 "Regexp to match an Octave function header.
94 The string `function' and its name are given by the first and third
95 parenthetical grouping.")
98 (defvar octave-mode-map
99 (let ((map (make-sparse-keymap)))
100 (define-key map "\M-." 'octave-find-definition)
101 (define-key map "\M-\C-j" 'octave-indent-new-comment-line)
102 (define-key map "\C-c\C-p" 'octave-previous-code-line)
103 (define-key map "\C-c\C-n" 'octave-next-code-line)
104 (define-key map "\C-c\C-a" 'octave-beginning-of-line)
105 (define-key map "\C-c\C-e" 'octave-end-of-line)
106 (define-key map [remap down-list] 'smie-down-list)
107 (define-key map "\C-c\M-\C-h" 'octave-mark-block)
108 (define-key map "\C-c]" 'smie-close-block)
109 (define-key map "\C-c/" 'smie-close-block)
110 (define-key map "\C-c;" 'octave-update-function-file-comment)
111 (define-key map "\C-hd" 'octave-help)
112 (define-key map "\C-ha" 'octave-lookfor)
113 (define-key map "\C-c\C-l" 'octave-source-file)
114 (define-key map "\C-c\C-f" 'octave-insert-defun)
115 (define-key map "\C-c\C-il" 'octave-send-line)
116 (define-key map "\C-c\C-ib" 'octave-send-block)
117 (define-key map "\C-c\C-if" 'octave-send-defun)
118 (define-key map "\C-c\C-ir" 'octave-send-region)
119 (define-key map "\C-c\C-ia" 'octave-send-buffer)
120 (define-key map "\C-c\C-is" 'octave-show-process-buffer)
121 (define-key map "\C-c\C-iq" 'octave-hide-process-buffer)
122 (define-key map "\C-c\C-ik" 'octave-kill-process)
123 (define-key map "\C-c\C-i\C-l" 'octave-send-line)
124 (define-key map "\C-c\C-i\C-b" 'octave-send-block)
125 (define-key map "\C-c\C-i\C-f" 'octave-send-defun)
126 (define-key map "\C-c\C-i\C-r" 'octave-send-region)
127 (define-key map "\C-c\C-i\C-a" 'octave-send-buffer)
128 (define-key map "\C-c\C-i\C-s" 'octave-show-process-buffer)
129 (define-key map "\C-c\C-i\C-q" 'octave-hide-process-buffer)
130 (define-key map "\C-c\C-i\C-k" 'octave-kill-process)
132 "Keymap used in Octave mode.")
136 (easy-menu-define octave-mode-menu octave-mode-map
137 "Menu for Octave mode."
139 ["Split Line at Point" octave-indent-new-comment-line t]
140 ["Previous Code Line" octave-previous-code-line t]
141 ["Next Code Line" octave-next-code-line t]
142 ["Begin of Line" octave-beginning-of-line t]
143 ["End of Line" octave-end-of-line t]
144 ["Mark Block" octave-mark-block t]
145 ["Close Block" smie-close-block t]
147 ["Start Octave Process" run-octave t]
148 ["Documentation Lookup" info-lookup-symbol t]
149 ["Help on Function" octave-help t]
150 ["Search help" octave-lookfor t]
151 ["Find Function Definition" octave-find-definition t]
152 ["Insert Function" octave-insert-defun t]
153 ["Update Function File Comment" octave-update-function-file-comment t]
155 ["Function Syntax Hints" (call-interactively
156 (if (fboundp 'eldoc-post-insert-mode)
157 'eldoc-post-insert-mode
159 :style toggle :selected (or eldoc-post-insert-mode eldoc-mode)
160 :help "Display function signatures after typing `SPC' or `('"]
161 ["Delimiter Matching" show-paren-mode
162 :style toggle :selected show-paren-mode
163 :help "Highlight matched pairs such as `if ... end'"
164 :visible (fboundp 'smie--matching-block-data)]
165 ["Auto Fill" auto-fill-mode
166 :style toggle :selected auto-fill-function
167 :help "Automatic line breaking"]
168 ["Electric Layout" electric-layout-mode
169 :style toggle :selected electric-layout-mode
170 :help "Automatically insert newlines around some chars"]
173 ["Send Current Line" octave-send-line t]
174 ["Send Current Block" octave-send-block t]
175 ["Send Current Function" octave-send-defun t]
176 ["Send Region" octave-send-region t]
177 ["Send Buffer" octave-send-buffer t]
178 ["Source Current File" octave-source-file t]
179 ["Show Process Buffer" octave-show-process-buffer t]
180 ["Hide Process Buffer" octave-hide-process-buffer t]
181 ["Kill Process" octave-kill-process t])
183 ["Customize Octave" (customize-group 'octave) t]
184 ["Submit Bug Report" report-emacs-bug t]))
186 (defvar octave-mode-syntax-table
187 (let ((table (make-syntax-table)))
188 (modify-syntax-entry ?\r " " table)
189 (modify-syntax-entry ?+ "." table)
190 (modify-syntax-entry ?- "." table)
191 (modify-syntax-entry ?= "." table)
192 (modify-syntax-entry ?* "." table)
193 (modify-syntax-entry ?/ "." table)
194 (modify-syntax-entry ?> "." table)
195 (modify-syntax-entry ?< "." table)
196 (modify-syntax-entry ?& "." table)
197 (modify-syntax-entry ?| "." table)
198 (modify-syntax-entry ?! "." table)
199 (modify-syntax-entry ?\\ "." table)
200 (modify-syntax-entry ?\' "." table)
201 (modify-syntax-entry ?\` "." table)
202 (modify-syntax-entry ?. "." table)
203 (modify-syntax-entry ?\" "\"" table)
204 (modify-syntax-entry ?_ "_" table)
205 ;; The "b" flag only applies to the second letter of the comstart
206 ;; and the first letter of the comend, i.e. the "4b" below is ineffective.
207 ;; If we try to put `b' on the single-line comments, we get a similar
208 ;; problem where the % and # chars appear as first chars of the 2-char
209 ;; comend, so the multi-line ender is also turned into style-b.
210 ;; So we need the new "c" comment style.
211 (modify-syntax-entry ?\% "< 13" table)
212 (modify-syntax-entry ?\# "< 13" table)
213 (modify-syntax-entry ?\{ "(} 2c" table)
214 (modify-syntax-entry ?\} "){ 4c" table)
215 (modify-syntax-entry ?\n ">" table)
217 "Syntax table in use in `octave-mode' buffers.")
219 (defcustom octave-font-lock-texinfo-comment t
220 "Control whether to highlight the texinfo comment block."
225 (defcustom octave-blink-matching-block t
226 "Control the blinking of matching Octave block keywords.
227 Non-nil means show matching begin of block when inserting a space,
228 newline or semicolon after an else or end keyword."
232 (defcustom octave-block-offset 2
233 "Extra indentation applied to statements in Octave block structures."
237 (defvar octave-block-comment-start
238 (concat (make-string 2 octave-comment-char) " ")
239 "String to insert to start a new Octave comment on an empty line.")
241 (defcustom octave-continuation-offset 4
242 "Extra indentation applied to Octave continuation lines."
247 (defconst octave-continuation-marker-regexp "\\\\\\|\\.\\.\\."))
249 (defvar octave-continuation-regexp
250 (concat "[^#%\n]*\\(" octave-continuation-marker-regexp
251 "\\)\\s-*\\(\\s<.*\\)?$"))
253 ;; Char \ is considered a bad decision for continuing a line.
254 (defconst octave-continuation-string "..."
255 "Character string used for Octave continuation lines.")
257 (defvar octave-mode-imenu-generic-expression
260 (list nil octave-function-header-regexp 3))
261 "Imenu expression for Octave mode. See `imenu-generic-expression'.")
263 (defcustom octave-mode-hook nil
264 "Hook to be run when Octave mode is started."
268 (defcustom octave-send-show-buffer t
269 "Non-nil means display `inferior-octave-buffer' after sending to it."
273 (defcustom octave-send-line-auto-forward t
274 "Control auto-forward after sending to the inferior Octave process.
275 Non-nil means always go to the next Octave code line after sending."
279 (defcustom octave-send-echo-input t
280 "Non-nil means echo input sent to the inferior Octave process."
289 ;; Use '__operators__' in Octave REPL to get a full list.
290 (defconst octave-operator-table
291 '((assoc ";" "\n") (assoc ",") ; The doc claims they have equal precedence!?
292 (right "=" "+=" "-=" "*=" "/=")
293 (assoc "&&") (assoc "||") ; The doc claims they have equal precedence!?
294 (assoc "&") (assoc "|") ; The doc claims they have equal precedence!?
295 (nonassoc "<" "<=" "==" ">=" ">" "!=" "~=")
296 (nonassoc ":") ;No idea what this is.
298 (assoc "*" "/" "\\" ".\\" ".*" "./")
300 (nonassoc "++" "--" "!" "~") ;And unary "+" and "-".
301 (right "^" "**" ".^" ".**")
302 ;; It's not really an operator, but for indentation purposes it
303 ;; could be convenient to treat it as one.
306 (defconst octave-smie-bnf-table
308 ;; We can't distinguish the first element in a sequence with
309 ;; precedence grammars, so we can't distinguish the condition
310 ;; if the `if' from the subsequent body, for example.
311 ;; This has to be done later in the indentation rules.
313 ;; We need to mention at least one of the operators in this part
314 ;; of the grammar: if the BNF and the operator table have
315 ;; no overlap, SMIE can't know how they relate.
317 ("try" exp "catch" exp "end_try_catch")
318 ("try" exp "catch" exp "end")
319 ("unwind_protect" exp
320 "unwind_protect_cleanup" exp "end_unwind_protect")
321 ("unwind_protect" exp "unwind_protect_cleanup" exp "end")
324 ("parfor" exp "endparfor")
326 ("do" exp "until" atom)
327 ("while" exp "endwhile")
330 ("if" exp "else" exp "endif")
331 ("if" exp "elseif" exp "else" exp "endif")
332 ("if" exp "elseif" exp "elseif" exp "else" exp "endif")
333 ("if" exp "elseif" exp "elseif" exp "else" exp "end")
334 ("switch" exp "case" exp "endswitch")
335 ("switch" exp "case" exp "otherwise" exp "endswitch")
336 ("switch" exp "case" exp "case" exp "otherwise" exp "endswitch")
337 ("switch" exp "case" exp "case" exp "otherwise" exp "end")
338 ("function" exp "endfunction")
339 ("function" exp "end")
340 ("enumeration" exp "endenumeration")
341 ("enumeration" exp "end")
342 ("events" exp "endevents")
344 ("methods" exp "endmethods")
345 ("methods" exp "end")
346 ("properties" exp "endproperties")
347 ("properties" exp "end")
348 ("classdef" exp "endclassdef")
349 ("classdef" exp "end"))
350 ;; (fundesc (atom "=" atom))
353 (defconst octave-smie-grammar
356 (smie-bnf->prec2 octave-smie-bnf-table
359 (smie-precs->prec2 octave-operator-table))))
361 ;; Tokenizing needs to be refined so that ";;" is treated as two
362 ;; tokens and also so as to recognize the \n separator (and
363 ;; corresponding continuation lines).
365 (defconst octave-operator-regexp
366 (regexp-opt (remove "\n" (apply 'append
367 (mapcar 'cdr octave-operator-table)))))
369 (defun octave-smie-backward-token ()
371 (forward-comment (- (point)))
373 ((and (not (eq (char-before) ?\;)) ;Coalesce ";" and "\n".
374 (> pos (line-end-position))
375 (if (looking-back octave-continuation-marker-regexp (- (point) 3))
377 (goto-char (match-beginning 0))
378 (forward-comment (- (point)))
381 ;; Ignore it if it's within parentheses.
382 (let ((ppss (syntax-ppss)))
383 (not (and (nth 1 ppss)
384 (eq ?\( (char-after (nth 1 ppss)))))))
385 (skip-chars-forward " \t")
386 ;; Why bother distinguishing \n and ;?
388 ((and (looking-back octave-operator-regexp (- (point) 3) 'greedy)
389 ;; Don't mistake a string quote for a transpose.
390 (not (looking-back "\\s\"" (1- (point)))))
391 (goto-char (match-beginning 0))
392 (match-string-no-properties 0))
394 (smie-default-backward-token)))))
396 (defun octave-smie-forward-token ()
397 (skip-chars-forward " \t")
398 (when (looking-at (eval-when-compile
399 (concat "\\(" octave-continuation-marker-regexp
400 "\\)[ \t]*\\($\\|[%#]\\)")))
401 (goto-char (match-end 1))
404 ((and (looking-at "[%#\n]")
405 (not (or (save-excursion (skip-chars-backward " \t")
406 ;; Only add implicit ; when needed.
407 (or (bolp) (eq (char-before) ?\;)))
408 ;; Ignore it if it's within parentheses.
409 (let ((ppss (syntax-ppss)))
411 (eq ?\( (char-after (nth 1 ppss))))))))
412 (if (eolp) (forward-char 1) (forward-comment 1))
413 ;; Why bother distinguishing \n and ;?
415 ((progn (forward-comment (point-max)) nil))
416 ((looking-at ";[ \t]*\\($\\|[%#]\\)")
417 ;; Combine the ; with the subsequent \n.
418 (goto-char (match-beginning 1))
421 ((and (looking-at octave-operator-regexp)
422 ;; Don't mistake a string quote for a transpose.
423 (not (looking-at "\\s\"")))
424 (goto-char (match-end 0))
425 (match-string-no-properties 0))
427 (smie-default-forward-token))))
429 (defun octave-smie-rules (kind token)
430 (pcase (cons kind token)
431 ;; We could set smie-indent-basic instead, but that would have two
433 ;; - changes to octave-block-offset wouldn't take effect immediately.
434 ;; - edebug wouldn't show the use of this variable.
435 (`(:elem . basic) octave-block-offset)
436 ;; Since "case" is in the same BNF rules as switch..end, SMIE by default
437 ;; aligns it with "switch".
438 (`(:before . "case") (if (not (smie-rule-sibling-p)) octave-block-offset))
440 (if (smie-rule-parent-p "classdef" "events" "enumeration" "function" "if"
441 "while" "else" "elseif" "for" "parfor"
442 "properties" "methods" "otherwise" "case"
443 "try" "catch" "unwind_protect"
444 "unwind_protect_cleanup")
445 (smie-rule-parent octave-block-offset)
446 ;; For (invalid) code between switch and case.
447 ;; (if (smie-rule-parent-p "switch") 4)
450 (defun octave-indent-comment ()
451 "A function for `smie-indent-functions' (which see)."
453 (back-to-indentation)
455 ((octave-in-string-or-comment-p) nil)
456 ((looking-at-p "\\(\\s<\\)\\1\\{2,\\}")
458 ;; Exclude %{, %} and %!.
459 ((and (looking-at-p "\\s<\\(?:[^{}!]\\|$\\)")
460 (not (looking-at-p "\\(\\s<\\)\\1")))
461 (comment-choose-indent)))))
464 (defvar octave-font-lock-keywords
466 ;; Fontify all builtin keywords.
467 (cons (concat "\\_<\\("
468 (regexp-opt octave-reserved-words)
470 'font-lock-keyword-face)
471 ;; Note: 'end' also serves as the last index in an indexing expression.
472 ;; Ref: http://www.mathworks.com/help/matlab/ref/end.html
473 (list (lambda (limit)
474 (while (re-search-forward "\\_<end\\_>" limit 'move)
475 (let ((beg (match-beginning 0))
477 (unless (octave-in-string-or-comment-p)
482 (when (memq (char-after) '(?\( ?\[ ?\{))
483 (put-text-property beg end 'face nil))
485 (error (goto-char end))))))
487 ;; Fontify all operators.
488 (cons octave-operator-regexp 'font-lock-builtin-face)
489 ;; Fontify all function declarations.
490 (list octave-function-header-regexp
491 '(1 font-lock-keyword-face)
492 '(3 font-lock-function-name-face nil t)))
493 "Additional Octave expressions to highlight.")
495 (defun octave-syntax-propertize-function (start end)
497 (octave-syntax-propertize-sqs end)
498 (funcall (syntax-propertize-rules
499 ("\\\\" (0 (when (eq (nth 3 (save-excursion
500 (syntax-ppss (match-beginning 0))))
502 (string-to-syntax "\\"))))
503 ;; Try to distinguish the string-quotes from the transpose-quotes.
504 ("\\(?:^\\|[[({,; ]\\)\\('\\)"
505 (1 (prog1 "\"'" (octave-syntax-propertize-sqs end)))))
508 (defun octave-syntax-propertize-sqs (end)
509 "Propertize the content/end of single-quote strings."
510 (when (eq (nth 3 (syntax-ppss)) ?\')
512 (when (re-search-forward
513 "\\(?:\\=\\|[^']\\)\\(?:''\\)*\\('\\)\\($\\|[^']\\)" end 'move)
514 (goto-char (match-beginning 2))
515 (when (eq (char-before (match-beginning 1)) ?\\)
516 ;; Backslash cannot escape a single quote.
517 (put-text-property (1- (match-beginning 1)) (match-beginning 1)
518 'syntax-table (string-to-syntax ".")))
519 (put-text-property (match-beginning 1) (match-end 1)
520 'syntax-table (string-to-syntax "\"'")))))
522 (defvar electric-layout-rules)
525 (define-derived-mode octave-mode prog-mode "Octave"
526 "Major mode for editing Octave code.
528 Octave is a high-level language, primarily intended for numerical
529 computations. It provides a convenient command line interface
530 for solving linear and nonlinear problems numerically. Function
531 definitions can also be stored in files and used in batch mode.
533 See Info node `(octave-mode) Using Octave Mode' for more details.
537 :abbrev-table octave-abbrev-table
540 (smie-setup octave-smie-grammar #'octave-smie-rules
541 :forward-token #'octave-smie-forward-token
542 :backward-token #'octave-smie-backward-token)
543 (setq-local smie-indent-basic 'octave-block-offset)
544 (add-hook 'smie-indent-functions #'octave-indent-comment nil t)
546 (setq-local smie-blink-matching-triggers
547 (cons ?\; smie-blink-matching-triggers))
548 (unless octave-blink-matching-block
549 (remove-hook 'post-self-insert-hook #'smie-blink-matching-open 'local))
551 (setq-local electric-indent-chars
552 (cons ?\; electric-indent-chars))
553 ;; IIUC matlab-mode takes the opposite approach: it makes RET insert
554 ;; a ";" at those places where it's correct (i.e. outside of parens).
555 (setq-local electric-layout-rules '((?\; . after)))
557 (setq-local comment-use-syntax t)
558 (setq-local comment-start octave-comment-start)
559 (setq-local comment-end "")
560 (setq-local comment-start-skip octave-comment-start-skip)
561 (setq-local comment-add 1)
563 (setq-local parse-sexp-ignore-comments t)
564 (setq-local paragraph-start (concat "\\s-*$\\|" page-delimiter))
565 (setq-local paragraph-separate paragraph-start)
566 (setq-local paragraph-ignore-fill-prefix t)
567 (setq-local fill-paragraph-function 'octave-fill-paragraph)
569 (setq-local fill-nobreak-predicate
570 (lambda () (eq (octave-in-string-p) ?')))
572 (if (fboundp 'add-function) ; new in 24.4
573 (add-function :around (local 'comment-line-break-function)
574 #'octave--indent-new-comment-line)
575 (setq-local comment-line-break-function
576 (apply-partially #'octave--indent-new-comment-line
577 #'comment-indent-new-line))))
579 (setq font-lock-defaults '(octave-font-lock-keywords))
581 (setq-local syntax-propertize-function #'octave-syntax-propertize-function)
583 (setq-local imenu-generic-expression octave-mode-imenu-generic-expression)
584 (setq-local imenu-case-fold-search nil)
586 (setq-local add-log-current-defun-function #'octave-add-log-current-defun)
588 (add-hook 'completion-at-point-functions 'octave-completion-at-point nil t)
589 (add-hook 'before-save-hook 'octave-sync-function-file-names nil t)
590 (setq-local beginning-of-defun-function 'octave-beginning-of-defun)
591 (and octave-font-lock-texinfo-comment (octave-font-lock-texinfo-comment))
592 (setq-local eldoc-documentation-function 'octave-eldoc-function)
594 (easy-menu-add octave-mode-menu))
597 (defcustom inferior-octave-program "octave"
598 "Program invoked by `inferior-octave'."
602 (defcustom inferior-octave-buffer "*Inferior Octave*"
603 "Name of buffer for running an inferior Octave process."
607 (defcustom inferior-octave-prompt
608 ;; For Octave >= 3.8, default is always 'octave', see
609 ;; http://hg.savannah.gnu.org/hgweb/octave/rev/708173343c50
610 "\\(?:^octave\\(?:.bin\\|.exe\\)?\\(?:-[.0-9]+\\)?\\(?::[0-9]+\\)?\\|^debug\\|^\\)>+ "
611 "Regexp to match prompts for the inferior Octave process."
615 (defcustom inferior-octave-prompt-read-only comint-prompt-read-only
616 "If non-nil, the Octave prompt is read only.
617 See `comint-prompt-read-only' for details."
622 (defcustom inferior-octave-startup-file
623 (let ((n (file-name-nondirectory inferior-octave-program)))
624 (locate-user-emacs-file (format "init_%s.m" n) (format ".emacs-%s" n)))
625 "Name of the inferior Octave startup file.
626 The contents of this file are sent to the inferior Octave process on
628 :type '(choice (const :tag "None" nil) file)
632 (defcustom inferior-octave-startup-args '("-i" "--no-line-editing")
633 "List of command line arguments for the inferior Octave process.
634 For example, for suppressing the startup message and using `traditional'
635 mode, include \"-q\" and \"--traditional\"."
636 :type '(repeat string)
640 (defcustom inferior-octave-mode-hook nil
641 "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."
651 :type '(repeat (choice (symbol :tag "Predefined symbol")
652 (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 (setq-local eldoc-documentation-function 'octave-eldoc-function)
737 (setq comint-input-ring-file-name
738 (or (getenv "OCTAVE_HISTFILE") "~/.octave_hist")
739 comint-input-ring-size (or (getenv "OCTAVE_HISTSIZE") 1024))
740 (comint-read-input-ring t)
741 (setq-local comint-dynamic-complete-functions
742 inferior-octave-dynamic-complete-functions)
743 (setq-local comint-prompt-read-only inferior-octave-prompt-read-only)
744 (add-hook 'comint-input-filter-functions
745 'inferior-octave-directory-tracker nil t)
746 ;; http://thread.gmane.org/gmane.comp.gnu.octave.general/48572
747 (add-hook 'window-configuration-change-hook
748 'inferior-octave-track-window-width-change nil t)
749 (setq-local compilation-error-regexp-alist inferior-octave-error-regexp-alist)
750 (setq-local compilation-mode-font-lock-keywords
751 inferior-octave-compilation-font-lock-keywords)
752 (compilation-shell-minor-mode 1)
753 (compilation-forget-errors))
756 (defun inferior-octave (&optional arg)
757 "Run an inferior Octave process, I/O via `inferior-octave-buffer'.
758 This buffer is put in Inferior Octave mode. See `inferior-octave-mode'.
760 Unless ARG is non-nil, switches to this buffer.
762 The elements of the list `inferior-octave-startup-args' are sent as
763 command line arguments to the inferior Octave process on startup.
765 Additional commands to be executed on startup can be provided either in
766 the file specified by `inferior-octave-startup-file' or by the default
767 startup file, `~/.emacs-octave'."
769 (let ((buffer (get-buffer-create inferior-octave-buffer)))
771 (pop-to-buffer buffer))
772 (unless (comint-check-proc buffer)
773 (with-current-buffer buffer
774 (inferior-octave-startup)
775 (inferior-octave-mode)))
779 (defalias 'run-octave 'inferior-octave)
781 (defun inferior-octave-startup ()
782 "Start an inferior Octave process."
783 (let ((proc (comint-exec-1
784 (substring inferior-octave-buffer 1 -1)
785 inferior-octave-buffer
786 inferior-octave-program
788 inferior-octave-startup-args
789 ;; --no-gui is introduced in Octave > 3.7
790 (and (not (member "--no-gui" inferior-octave-startup-args))
791 (zerop (process-file inferior-octave-program
792 nil nil nil "--no-gui" "--help"))
794 (set-process-filter proc 'inferior-octave-output-digest)
795 (setq inferior-octave-process proc
796 inferior-octave-output-list nil
797 inferior-octave-output-string nil
798 inferior-octave-receive-in-progress t)
800 ;; This may look complicated ... However, we need to make sure that
801 ;; we additional startup code only AFTER Octave is ready (otherwise,
802 ;; output may be mixed up). Hence, we need to digest the Octave
803 ;; output to see when it issues a prompt.
804 (while inferior-octave-receive-in-progress
805 (unless (inferior-octave-process-live-p)
806 ;; Spit out the error messages.
807 (when inferior-octave-output-list
808 (princ (concat (mapconcat 'identity inferior-octave-output-list "\n")
810 (process-mark inferior-octave-process)))
811 (error "Process `%s' died" inferior-octave-process))
812 (accept-process-output inferior-octave-process))
813 (goto-char (point-max))
814 (set-marker (process-mark proc) (point))
815 (insert-before-markers
817 (if (not (bobp)) "
\f\n")
818 (if inferior-octave-output-list
820 'identity inferior-octave-output-list "\n")
823 ;; An empty secondary prompt, as e.g. obtained by '--braindead',
825 (inferior-octave-send-list-and-digest (list "PS2\n"))
826 (when (string-match "\\(PS2\\|ans\\) = *$"
827 (car inferior-octave-output-list))
828 (inferior-octave-send-list-and-digest (list "PS2 ('> ');\n")))
830 (inferior-octave-send-list-and-digest
831 (list "disp (getenv ('OCTAVE_SRCDIR'))\n"))
832 (process-put proc 'octave-srcdir
833 (unless (equal (car inferior-octave-output-list) "")
834 (car inferior-octave-output-list)))
836 ;; O.K., now we are ready for the Inferior Octave startup commands.
837 (inferior-octave-send-list-and-digest
839 (unless (equal inferior-octave-output-string ">> ")
840 ;; See http://hg.savannah.gnu.org/hgweb/octave/rev/708173343c50
841 "PS1 ('octave> ');\n")
842 (when (and inferior-octave-startup-file
843 (file-exists-p inferior-octave-startup-file))
844 (format "source ('%s');\n" inferior-octave-startup-file))))
845 (when inferior-octave-output-list
846 (insert-before-markers
847 (mapconcat 'identity inferior-octave-output-list "\n")))
849 ;; And finally, everything is back to normal.
850 (set-process-filter proc 'comint-output-filter)
851 ;; Just in case, to be sure a cd in the startup file won't have
852 ;; detrimental effects.
853 (with-demoted-errors (inferior-octave-resync-dirs))
854 ;; Generate a proper prompt, which is critical to
855 ;; `comint-history-isearch-backward-regexp'. Bug#14433.
856 (comint-send-string proc "\n")))
858 (defun inferior-octave-completion-table ()
859 (completion-table-with-cache
861 (inferior-octave-send-list-and-digest
862 (list (format "completion_matches ('%s');\n" command)))
863 (delete-consecutive-dups
864 (sort inferior-octave-output-list 'string-lessp)))))
866 (defun inferior-octave-completion-at-point ()
867 "Return the data to complete the Octave symbol at point."
868 ;; http://debbugs.gnu.org/14300
869 (unless (string-match-p "/" (or (comint--match-partial-filename) ""))
870 (let ((beg (save-excursion
871 (skip-syntax-backward "w_" (comint-line-beginning-position))
874 (when (and beg (> end beg))
875 (list beg end (completion-table-in-turn
876 (inferior-octave-completion-table)
877 'comint-completion-file-name-table))))))
879 (define-obsolete-function-alias 'inferior-octave-complete
880 'completion-at-point "24.1")
882 (defun inferior-octave-dynamic-list-input-ring ()
883 "List the buffer's input history in a help buffer."
884 ;; We cannot use `comint-dynamic-list-input-ring', because it replaces
885 ;; "completion" by "history reference" ...
887 (if (or (not (ring-p comint-input-ring))
888 (ring-empty-p comint-input-ring))
889 (message "No history")
891 (history-buffer " *Input History*")
892 (index (1- (ring-length comint-input-ring)))
893 (conf (current-window-configuration)))
894 ;; We have to build up a list ourselves from the ring vector.
896 (setq history (cons (ring-ref comint-input-ring index) history)
898 ;; Change "completion" to "history reference"
899 ;; to make the display accurate.
900 (with-output-to-temp-buffer history-buffer
901 (display-completion-list history)
902 (set-buffer history-buffer))
903 (message "Hit space to flush")
904 (let ((ch (read-event)))
906 (set-window-configuration conf)
907 (setq unread-command-events (list ch)))))))
909 (defun inferior-octave-output-digest (_proc string)
910 "Special output filter for the inferior Octave process.
911 Save all output between newlines into `inferior-octave-output-list', and
912 the rest to `inferior-octave-output-string'."
913 (setq string (concat inferior-octave-output-string string))
914 (while (string-match "\n" string)
915 (setq inferior-octave-output-list
916 (append inferior-octave-output-list
917 (list (substring string 0 (match-beginning 0))))
918 string (substring string (match-end 0))))
919 (if (string-match inferior-octave-prompt string)
920 (setq inferior-octave-receive-in-progress nil))
921 (setq inferior-octave-output-string string))
923 (defun inferior-octave-check-process ()
924 (or (inferior-octave-process-live-p)
925 (error (substitute-command-keys
926 "No inferior octave process running. Type \\[run-octave]"))))
928 (defun inferior-octave-send-list-and-digest (list)
929 "Send LIST to the inferior Octave process and digest the output.
930 The elements of LIST have to be strings and are sent one by one. All
931 output is passed to the filter `inferior-octave-output-digest'."
932 (inferior-octave-check-process)
933 (let* ((proc inferior-octave-process)
934 (filter (process-filter proc))
936 (set-process-filter proc 'inferior-octave-output-digest)
937 (setq inferior-octave-output-list nil)
939 (while (setq string (car list))
940 (setq inferior-octave-output-string nil
941 inferior-octave-receive-in-progress t)
942 (comint-send-string proc string)
943 (while inferior-octave-receive-in-progress
944 (accept-process-output proc))
945 (setq list (cdr list)))
946 (set-process-filter proc filter))))
948 (defvar inferior-octave-directory-tracker-resync nil)
949 (make-variable-buffer-local 'inferior-octave-directory-tracker-resync)
951 (defun inferior-octave-directory-tracker (string)
952 "Tracks `cd' commands issued to the inferior Octave process.
953 Use \\[inferior-octave-resync-dirs] to resync if Emacs gets confused."
954 (when inferior-octave-directory-tracker-resync
955 (or (inferior-octave-resync-dirs 'noerror)
956 (setq inferior-octave-directory-tracker-resync nil)))
958 ((string-match "^[ \t]*cd[ \t;]*$" string)
960 ((string-match "^[ \t]*cd[ \t]+\\([^ \t\n;]*\\)[ \t\n;]*" string)
962 (cd (match-string 1 string))
963 (error (setq inferior-octave-directory-tracker-resync t)
965 (error-message-string err)
966 (match-string 1 string)))))))
968 (defun inferior-octave-resync-dirs (&optional noerror)
969 "Resync the buffer's idea of the current directory.
970 This command queries the inferior Octave process about its current
971 directory and makes this the current buffer's default directory."
973 (inferior-octave-send-list-and-digest '("disp (pwd ())\n"))
976 (cd (car inferior-octave-output-list))
978 (error (unless noerror (signal (car err) (cdr err))))))
980 (defcustom inferior-octave-minimal-columns 80
981 "The minimal column width for the inferior Octave process."
986 (defvar inferior-octave-last-column-width nil)
988 (defun inferior-octave-track-window-width-change ()
989 ;; http://thread.gmane.org/gmane.comp.gnu.octave.general/48572
990 (let ((width (max inferior-octave-minimal-columns (window-width))))
991 (unless (eq inferior-octave-last-column-width width)
992 (setq-local inferior-octave-last-column-width width)
993 (when (inferior-octave-process-live-p)
994 (inferior-octave-send-list-and-digest
995 (list (format "putenv ('COLUMNS', '%s');\n" width)))))))
998 ;;; Miscellaneous useful functions
1000 (defun octave-in-comment-p ()
1001 "Return non-nil if point is inside an Octave comment."
1002 (nth 4 (syntax-ppss)))
1004 (defun octave-in-string-p ()
1005 "Return non-nil if point is inside an Octave string."
1006 (nth 3 (syntax-ppss)))
1008 (defun octave-in-string-or-comment-p ()
1009 "Return non-nil if point is inside an Octave string or comment."
1010 (nth 8 (syntax-ppss)))
1012 (defun octave-looking-at-kw (regexp)
1013 "Like `looking-at', but sets `case-fold-search' nil."
1014 (let ((case-fold-search nil))
1015 (looking-at regexp)))
1017 (defun octave-maybe-insert-continuation-string ()
1018 (if (or (octave-in-comment-p)
1021 (looking-at octave-continuation-regexp)))
1023 (delete-horizontal-space)
1024 (insert (concat " " octave-continuation-string))))
1026 (defun octave-completing-read ()
1027 (let ((def (or (thing-at-point 'symbol)
1029 (skip-syntax-backward "-(")
1030 (thing-at-point 'symbol)))))
1032 (format (if def "Function (default %s): "
1034 (inferior-octave-completion-table)
1035 nil nil nil nil def)))
1037 (defun octave-goto-function-definition (fn)
1038 "Go to the function definition of FN in current buffer."
1041 (let ((orig (point)) found)
1042 (goto-char (point-min))
1043 (while (and (not found) (re-search-forward re nil t))
1044 (when (and (equal (match-string sub) fn)
1045 (not (nth 8 (syntax-ppss))))
1047 (unless found (goto-char orig))
1049 (pcase (and buffer-file-name (file-name-extension buffer-file-name))
1050 ("cc" (funcall search
1051 "\\_<DEFUN\\(?:_DLD\\)?\\s-*(\\s-*\\(\\(?:\\sw\\|\\s_\\)+\\)" 1))
1052 (t (funcall search octave-function-header-regexp 3)))))
1054 (defun octave-function-file-p ()
1055 "Return non-nil if the first token is \"function\".
1056 The value is (START END NAME-START NAME-END) of the function."
1058 (goto-char (point-min))
1059 (when (equal (funcall smie-forward-token-function) "function")
1061 (let* ((start (point))
1062 (end (progn (forward-sexp 1) (point)))
1065 (re-search-forward octave-function-header-regexp
1067 (list (match-beginning 3) (match-end 3)))))
1068 (cons start (cons end name))))))
1070 ;; Like forward-comment but stop at non-comment blank
1071 (defun octave-skip-comment-forward (limit)
1072 (let ((ppss (syntax-ppss)))
1074 (goto-char (nth 8 ppss))
1075 (goto-char (or (comment-search-forward limit t) (point)))))
1076 (while (and (< (point) limit) (looking-at-p "\\s<"))
1077 (forward-comment 1)))
1079 ;;; First non-copyright comment block
1080 (defun octave-function-file-comment ()
1081 "Beginning and end positions of the function file comment."
1083 (goto-char (point-min))
1084 ;; Copyright block: octave/libinterp/parse-tree/lex.ll around line 1634
1085 (while (save-excursion
1086 (when (comment-search-forward (point-max) t)
1087 (when (eq (char-after) ?\{) ; case of block comment
1089 (skip-syntax-forward "-")
1090 (let ((case-fold-search t))
1091 (looking-at-p "\\(?:copyright\\|author\\)\\_>"))))
1092 (octave-skip-comment-forward (point-max)))
1093 (let ((beg (comment-search-forward (point-max) t)))
1096 (octave-skip-comment-forward (point-max))
1097 (list beg (point))))))
1099 (defun octave-sync-function-file-names ()
1100 "Ensure function name agree with function file name.
1101 See Info node `(octave)Function Files'."
1103 (when buffer-file-name
1104 (pcase-let ((`(,start ,_end ,name-start ,name-end)
1105 (octave-function-file-p)))
1106 (when (and start name-start)
1107 (let* ((func (buffer-substring name-start name-end))
1108 (file (file-name-sans-extension
1109 (file-name-nondirectory buffer-file-name)))
1110 (help-form (format "\
1111 a: Use function name `%s'
1112 b: Use file name `%s'
1113 q: Don't fix\n" func file))
1114 (c (unless (equal file func)
1115 (save-window-excursion
1118 "Which name to use? (a/b/q) " '(?a ?b ?q))))))
1120 (?a (let ((newname (expand-file-name
1121 (concat func (file-name-extension
1122 buffer-file-name t)))))
1123 (when (or (not (file-exists-p newname))
1125 (format "Target file %s exists; proceed? " newname)))
1126 (when (file-exists-p buffer-file-name)
1127 (rename-file buffer-file-name newname t))
1128 (set-visited-file-name newname))))
1130 (goto-char name-start)
1131 (delete-region name-start name-end)
1132 (insert file)))))))))
1134 (defun octave-update-function-file-comment (beg end)
1135 "Query replace function names in function file comment."
1138 (barf-if-buffer-read-only)
1140 (list (region-beginning) (region-end))
1141 (or (octave-function-file-comment)
1142 (error "No function file comment found")))))
1144 (let* ((bounds (or (octave-function-file-p)
1145 (error "Not in a function file buffer")))
1146 (func (if (cddr bounds)
1147 (apply #'buffer-substring (cddr bounds))
1148 (error "Function name not found")))
1151 (when (re-search-forward
1152 "[=}]\\s-*\\(\\(?:\\sw\\|\\s_\\)+\\)\\_>"
1153 (min (line-end-position 4) end)
1156 (old-func (read-string (format (if old-func
1157 "Name to replace (default %s): "
1158 "Name to replace: ")
1161 (if (and func old-func (not (equal func old-func)))
1162 (perform-replace old-func func 'query
1163 nil 'delimited nil nil beg end)
1164 (message "Function names match")))))
1166 (defface octave-function-comment-block
1167 '((t (:inherit font-lock-doc-face)))
1168 "Face used to highlight function comment block."
1171 (eval-when-compile (require 'texinfo))
1173 (defun octave-font-lock-texinfo-comment ()
1178 (if (numberp (nth 1 kw))
1179 `(,(nth 0 kw) ,(nth 1 kw) ,(nth 2 kw) prepend)
1180 (message "Ignoring Texinfo highlight: %S" kw)))
1181 texinfo-font-lock-keywords)))))
1182 (font-lock-add-keywords
1185 (while (and (< (point) limit)
1186 (search-forward "-*- texinfo -*-" limit t)
1187 (octave-in-comment-p))
1188 (let ((beg (nth 8 (syntax-ppss)))
1190 (octave-skip-comment-forward (point-max))
1192 (put-text-property beg end 'font-lock-multiline t)
1193 (font-lock-prepend-text-property
1194 beg end 'face 'octave-function-comment-block)
1197 (while (re-search-forward (car kw) end 'move)
1198 (font-lock-apply-highlight (cdr kw))))))
1205 (defun octave-indent-new-comment-line (&optional soft)
1206 "Break Octave line at point, continuing comment if within one.
1207 Insert `octave-continuation-string' before breaking the line
1208 unless inside a list. Signal an error if within a single-quoted
1211 (funcall comment-line-break-function soft))
1213 (defun octave--indent-new-comment-line (orig &rest args)
1215 ((octave-in-comment-p) nil)
1216 ((eq (octave-in-string-p) ?')
1217 (error "Cannot split a single-quoted string"))
1218 ((eq (octave-in-string-p) ?\")
1219 (insert octave-continuation-string))
1221 (delete-horizontal-space)
1222 (unless (and (cadr (syntax-ppss))
1223 (eq (char-after (cadr (syntax-ppss))) ?\())
1224 (insert " " octave-continuation-string))))
1226 (indent-according-to-mode))
1228 (define-obsolete-function-alias
1229 'octave-indent-defun 'prog-indent-sexp "24.4")
1233 (defun octave-next-code-line (&optional arg)
1234 "Move ARG lines of Octave code forward (backward if ARG is negative).
1235 Skips past all empty and comment lines. Default for ARG is 1.
1237 On success, return 0. Otherwise, go as far as possible and return -1."
1239 (or arg (setq arg 1))
1242 (inc (if (> arg 0) 1 -1)))
1243 (while (and (/= arg 0) (= n 0))
1244 (setq n (forward-line inc))
1246 (looking-at "\\s-*\\($\\|\\s<\\)"))
1247 (setq n (forward-line inc)))
1248 (setq arg (- arg inc)))
1251 (defun octave-previous-code-line (&optional arg)
1252 "Move ARG lines of Octave code backward (forward if ARG is negative).
1253 Skips past all empty and comment lines. Default for ARG is 1.
1255 On success, return 0. Otherwise, go as far as possible and return -1."
1257 (or arg (setq arg 1))
1258 (octave-next-code-line (- arg)))
1260 (defun octave-beginning-of-line ()
1261 "Move point to beginning of current Octave line.
1262 If on an empty or comment line, go to the beginning of that line.
1263 Otherwise, move backward to the beginning of the first Octave code line
1264 which is not inside a continuation statement, i.e., which does not
1265 follow a code line ending with `...' or is inside an open
1269 (unless (looking-at "\\s-*\\($\\|\\s<\\)")
1270 (while (or (when (cadr (syntax-ppss))
1271 (goto-char (cadr (syntax-ppss)))
1274 (and (or (looking-at "\\s-*\\($\\|\\s<\\)")
1276 (if (zerop (octave-previous-code-line))
1277 (looking-at octave-continuation-regexp))))
1278 (zerop (forward-line -1)))))))
1280 (defun octave-end-of-line ()
1281 "Move point to end of current Octave line.
1282 If on an empty or comment line, go to the end of that line.
1283 Otherwise, move forward to the end of the first Octave code line which
1284 does not end with `...' or is inside an open parenthesis list."
1287 (unless (save-excursion
1289 (looking-at "\\s-*\\($\\|\\s<\\)"))
1290 (while (or (when (cadr (syntax-ppss))
1297 (and (save-excursion
1299 (or (looking-at "\\s-*\\($\\|\\s<\\)")
1300 (looking-at octave-continuation-regexp)))
1301 (zerop (forward-line 1)))))
1304 (defun octave-mark-block ()
1305 "Put point at the beginning of this Octave block, mark at the end.
1306 The block marked is the one that contains point or follows point."
1308 (if (and (looking-at "\\sw\\|\\s_")
1309 (looking-back "\\sw\\|\\s_" (1- (point))))
1310 (skip-syntax-forward "w_"))
1311 (unless (or (looking-at "\\s(")
1313 (let* ((token (funcall smie-forward-token-function))
1314 (level (assoc token smie-grammar)))
1315 (and level (not (numberp (cadr level)))))))
1316 (backward-up-list 1))
1319 (defun octave-beginning-of-defun (&optional arg)
1320 "Octave-specific `beginning-of-defun-function' (which see)."
1321 (or arg (setq arg 1))
1322 ;; Move out of strings or comments.
1323 (when (octave-in-string-or-comment-p)
1324 (goto-char (octave-in-string-or-comment-p)))
1325 (letrec ((orig (point))
1326 (toplevel (lambda (pos)
1329 (backward-up-list 1)
1330 (funcall toplevel (point)))
1331 (scan-error pos)))))
1332 (goto-char (funcall toplevel (point)))
1333 (when (and (> arg 0) (/= orig (point)))
1334 (setq arg (1- arg)))
1335 (forward-sexp (- arg))
1336 (and (< arg 0) (forward-sexp -1))
1339 (defun octave-fill-paragraph (&optional _arg)
1340 "Fill paragraph of Octave code, handling Octave comments."
1341 ;; FIXME: difference with generic fill-paragraph:
1342 ;; - code lines are only split, never joined.
1343 ;; - \n that end comments are never removed.
1344 ;; - insert continuation marker when splitting code lines.
1347 (let ((end (progn (forward-paragraph) (copy-marker (point) t)))
1349 (forward-paragraph -1)
1350 (skip-chars-forward " \t\n")
1353 (cfc (current-fill-column))
1356 (while (< (point) end)
1358 (indent-according-to-mode)
1360 (move-to-column cfc)
1361 ;; First check whether we need to combine non-empty comment lines
1362 (if (and (< (current-column) cfc)
1363 (octave-in-comment-p)
1364 (not (save-excursion
1366 (looking-at "^\\s-*\\s<+\\s-*$"))))
1367 ;; This is a nonempty comment line which does not extend
1368 ;; past the fill column. If it is followed by a nonempty
1369 ;; comment line with the same comment prefix, try to
1370 ;; combine them, and repeat this until either we reach the
1371 ;; fill-column or there is nothing more to combine.
1373 ;; Get the comment prefix
1376 (while (and (re-search-forward "\\s<+")
1377 (not (octave-in-comment-p))))
1378 (setq comment-prefix (match-string 0)))
1379 ;; And keep combining ...
1380 (while (and (< (current-column) cfc)
1392 (re-search-forward comment-prefix)
1393 (delete-region (match-beginning 0) (match-end 0))
1395 (move-to-column cfc))))
1396 ;; We might also try to combine continued code lines> Perhaps
1397 ;; some other time ...
1398 (skip-chars-forward "^ \t\n")
1399 (delete-horizontal-space)
1400 (if (or (< (current-column) cfc)
1401 (and (= (current-column) cfc) (eolp)))
1403 (if (not (eolp)) (insert " "))
1404 (or (funcall normal-auto-fill-function)
1408 (defun octave-completion-at-point ()
1409 "Find the text to complete and the corresponding table."
1410 (let* ((beg (save-excursion (skip-syntax-backward "w_") (point)))
1413 ;; Extend region past point, if applicable.
1414 (save-excursion (skip-syntax-forward "w_")
1415 (setq end (point))))
1417 (list beg end (or (and (inferior-octave-process-live-p)
1418 (inferior-octave-completion-table))
1419 octave-reserved-words)))))
1421 (define-obsolete-function-alias 'octave-complete-symbol
1422 'completion-at-point "24.1")
1424 (defun octave-add-log-current-defun ()
1425 "A function for `add-log-current-defun-function' (which see)."
1428 (and (beginning-of-defun)
1429 (re-search-forward octave-function-header-regexp
1430 (line-end-position) t)
1434 ;;; Electric characters && friends
1435 (define-skeleton octave-insert-defun
1436 "Insert an Octave function skeleton.
1437 Prompt for the function's name, arguments and return values (to be
1438 entered without parens)."
1439 (let* ((defname (file-name-sans-extension (buffer-name)))
1440 (name (read-string (format "Function name (default %s): " defname)
1442 (args (read-string "Arguments: "))
1443 (vals (read-string "Return values: ")))
1446 ((string-equal vals "") vals)
1447 ((string-match "[ ,]" vals) (concat "[" vals "] = "))
1448 (t (concat vals " = ")))
1451 \n octave-block-comment-start "usage: " str \n
1452 octave-block-comment-start '(delete-horizontal-space) \n
1453 octave-block-comment-start '(delete-horizontal-space) \n
1454 "function " > str \n
1458 ;;; Communication with the inferior Octave process
1459 (defun octave-kill-process ()
1460 "Kill inferior Octave process and its buffer."
1462 (when (and (buffer-live-p (get-buffer inferior-octave-buffer))
1463 (or (yes-or-no-p (format "Kill %S and its buffer? "
1464 inferior-octave-process))
1465 (user-error "Aborted")))
1466 (when (inferior-octave-process-live-p)
1467 (set-process-query-on-exit-flag inferior-octave-process nil)
1468 (process-send-string inferior-octave-process "quit;\n")
1469 (accept-process-output inferior-octave-process))
1470 (kill-buffer inferior-octave-buffer)))
1472 (defun octave-show-process-buffer ()
1473 "Make sure that `inferior-octave-buffer' is displayed."
1475 (if (get-buffer inferior-octave-buffer)
1476 (display-buffer inferior-octave-buffer)
1477 (message "No buffer named %s" inferior-octave-buffer)))
1479 (defun octave-hide-process-buffer ()
1480 "Delete all windows that display `inferior-octave-buffer'."
1482 (if (get-buffer inferior-octave-buffer)
1483 (delete-windows-on inferior-octave-buffer)
1484 (message "No buffer named %s" inferior-octave-buffer)))
1486 (defun octave-source-file (file)
1487 "Execute FILE in the inferior Octave process.
1488 This is done using Octave's source function. FILE defaults to
1489 current buffer file unless called with a prefix arg \\[universal-argument]."
1490 (interactive (list (or (and (not current-prefix-arg) buffer-file-name)
1491 (read-file-name "File: " nil nil t))))
1493 (signal 'wrong-type-argument (list 'stringp file)))
1495 (with-current-buffer inferior-octave-buffer
1496 (comint-send-string inferior-octave-process
1497 (format "source '%s'\n" file))))
1499 (defun octave-send-region (beg end)
1500 "Send current region to the inferior Octave process."
1503 (let ((proc inferior-octave-process)
1504 (string (buffer-substring-no-properties beg end))
1506 (with-current-buffer inferior-octave-buffer
1507 ;; http://lists.gnu.org/archive/html/emacs-devel/2013-10/msg00095.html
1508 (compilation-forget-errors)
1509 (setq inferior-octave-output-list nil)
1510 (while (not (string-equal string ""))
1511 (if (string-match "\n" string)
1512 (setq line (substring string 0 (match-beginning 0))
1513 string (substring string (match-end 0)))
1514 (setq line string string ""))
1515 (setq inferior-octave-receive-in-progress t)
1516 (inferior-octave-send-list-and-digest (list (concat line "\n")))
1517 (while inferior-octave-receive-in-progress
1518 (accept-process-output proc))
1519 (insert-before-markers
1520 (mapconcat 'identity
1522 (if octave-send-echo-input (list line) (list ""))
1523 inferior-octave-output-list
1524 (list inferior-octave-output-string))
1526 (if octave-send-show-buffer
1527 (display-buffer inferior-octave-buffer)))
1529 (defun octave-send-buffer ()
1530 "Send current buffer to the inferior Octave process."
1532 (octave-send-region (point-min) (point-max)))
1534 (defun octave-send-block ()
1535 "Send current Octave block to the inferior Octave process."
1539 (octave-send-region (point) (mark))))
1541 (defun octave-send-defun ()
1542 "Send current Octave function to the inferior Octave process."
1546 (octave-send-region (point) (mark))))
1548 (defun octave-send-line (&optional arg)
1549 "Send current Octave code line to the inferior Octave process.
1550 With positive prefix ARG, send that many lines.
1551 If `octave-send-line-auto-forward' is non-nil, go to the next unsent
1554 (or arg (setq arg 1))
1559 (octave-next-code-line (- arg 1))
1562 (if octave-send-line-auto-forward
1563 (octave-next-code-line 1))
1564 (octave-send-region beg end))))
1566 (defun octave-eval-print-last-sexp ()
1567 "Evaluate Octave sexp before point and print value into current buffer."
1570 (let ((standard-output (current-buffer))
1571 (print-escape-newlines nil)
1577 (inferior-octave-send-list-and-digest
1578 (list (concat (buffer-substring-no-properties (point) opoint)
1580 (mapconcat 'identity inferior-octave-output-list "\n")))
1585 (defcustom octave-eldoc-message-style 'auto
1586 "Octave eldoc message style: auto, oneline, multiline."
1587 :type '(choice (const :tag "Automatic" auto)
1588 (const :tag "One Line" oneline)
1589 (const :tag "Multi Line" multiline))
1593 ;; (FN SIGNATURE1 SIGNATURE2 ...)
1594 (defvar octave-eldoc-cache nil)
1596 (defun octave-eldoc-function-signatures (fn)
1597 (unless (equal fn (car octave-eldoc-cache))
1598 (inferior-octave-send-list-and-digest
1599 (list (format "print_usage ('%s');\n" fn)))
1601 (dolist (line inferior-octave-output-list)
1603 "\\s-*\\(?:--[^:]+\\|usage\\):\\s-*\\(.*\\)$"
1605 (push (match-string 1 line) result)))
1606 (setq octave-eldoc-cache
1607 (cons (substring-no-properties fn)
1608 (nreverse result)))))
1609 (cdr octave-eldoc-cache))
1611 (defun octave-eldoc-function ()
1612 "A function for `eldoc-documentation-function' (which see)."
1613 (when (inferior-octave-process-live-p)
1614 (let* ((ppss (syntax-ppss))
1615 (paren-pos (cadr ppss))
1618 ;; PAREN-POS must be after the prompt
1620 (if (eq (get-buffer-process (current-buffer))
1621 inferior-octave-process)
1622 (process-mark inferior-octave-process)
1624 (or (not (eq (get-buffer-process (current-buffer))
1625 inferior-octave-process))
1626 (< (process-mark inferior-octave-process)
1628 (eq (char-after paren-pos) ?\())
1629 (goto-char paren-pos)
1630 (setq paren-pos nil))
1631 (when (or (< (skip-syntax-backward "-") 0) paren-pos)
1632 (thing-at-point 'symbol))))
1633 (sigs (and fn (octave-eldoc-function-signatures fn)))
1634 (oneline (mapconcat 'identity sigs
1635 (propertize " | " 'face 'warning)))
1636 (multiline (mapconcat (lambda (s) (concat "-- " s)) sigs "\n")))
1638 ;; Return the value according to style.
1639 (pcase octave-eldoc-message-style
1640 (`auto (if (< (length oneline) (window-width (minibuffer-window)))
1644 (`multiline multiline)))))
1646 (defcustom octave-help-buffer "*Octave Help*"
1647 "Buffer name for `octave-help'."
1652 ;; Used in a mode derived from help-mode.
1653 (declare-function help-button-action "help-mode" (button))
1655 (define-button-type 'octave-help-file
1657 'action #'help-button-action
1658 'help-function 'octave-find-definition)
1660 (define-button-type 'octave-help-function
1664 (buffer-substring (button-start b) (button-end b)))))
1666 (defvar octave-help-mode-map
1667 (let ((map (make-sparse-keymap)))
1668 (define-key map "\M-." 'octave-find-definition)
1669 (define-key map "\C-hd" 'octave-help)
1670 (define-key map "\C-ha" 'octave-lookfor)
1673 (define-derived-mode octave-help-mode help-mode "OctHelp"
1674 "Major mode for displaying Octave documentation."
1676 :syntax-table octave-mode-syntax-table
1677 (eval-and-compile (require 'help-mode))
1678 ;; Don't highlight `EXAMPLE' as elisp symbols by using a regexp that
1680 (setq-local help-xref-symbol-regexp "x\\`"))
1682 (defun octave-help (fn)
1683 "Display the documentation of FN."
1684 (interactive (list (octave-completing-read)))
1685 (inferior-octave-send-list-and-digest
1686 (list (format "help ('%s');\n" fn)))
1687 (let ((lines inferior-octave-output-list)
1688 (inhibit-read-only t))
1689 (when (string-match "error: \\(.*\\)$" (car lines))
1690 (error "%s" (match-string 1 (car lines))))
1691 (with-help-window octave-help-buffer
1692 (princ (mapconcat 'identity lines "\n"))
1693 (with-current-buffer octave-help-buffer
1694 ;; Bound to t so that `help-buffer' returns current buffer for
1695 ;; `help-setup-xref'.
1696 (let ((help-xref-following t))
1697 (help-setup-xref (list 'octave-help fn)
1698 (called-interactively-p 'interactive)))
1699 ;; Note: can be turned off by suppress_verbose_help_message.
1701 ;; Remove boring trailing text: Additional help for built-in functions
1702 ;; and operators ...
1703 (goto-char (point-max))
1704 (when (search-backward "\n\n\n" nil t)
1705 (goto-char (match-beginning 0))
1706 (delete-region (point) (point-max)))
1707 ;; File name highlight
1708 (goto-char (point-min))
1709 (when (re-search-forward "from the file \\(.*\\)$"
1712 (let* ((file (match-string 1))
1713 (dir (file-name-directory
1714 (directory-file-name (file-name-directory file)))))
1715 (replace-match "" nil nil nil 1)
1717 ;; Include the parent directory which may be regarded as
1718 ;; the category for the FN.
1719 (help-insert-xref-button (file-relative-name file dir)
1720 'octave-help-file fn)
1722 ;; Make 'See also' clickable.
1723 (with-syntax-table octave-mode-syntax-table
1724 (when (re-search-forward "^\\s-*See also:" nil t)
1725 (let ((end (save-excursion (re-search-forward "^\\s-*$" nil t))))
1726 (while (re-search-forward
1727 "\\s-*\\([^,\n]+?\\)\\s-*\\(?:[,]\\|[.]?$\\)" end t)
1728 (make-text-button (match-beginning 1) (match-end 1)
1729 :type 'octave-help-function)))))
1730 (octave-help-mode)))))
1732 (defun octave-lookfor (str &optional all)
1733 "Search for the string STR in all function help strings.
1734 If ALL is non-nil search the entire help string else only search the first
1736 (interactive "sSearch for: \nP")
1737 (inferior-octave-send-list-and-digest
1738 (list (format "lookfor (%s'%s');\n"
1739 (if all "'-all', " "")
1741 (let ((lines inferior-octave-output-list))
1742 (when (and (stringp (car lines))
1743 (string-match "error: \\(.*\\)$" (car lines)))
1744 (error "%s" (match-string 1 (car lines))))
1745 (with-help-window octave-help-buffer
1746 (with-current-buffer octave-help-buffer
1748 (insert (mapconcat 'identity lines "\n"))
1749 (insert (format "Nothing found for \"%s\".\n" str)))
1750 ;; Bound to t so that `help-buffer' returns current buffer for
1751 ;; `help-setup-xref'.
1752 (let ((help-xref-following t))
1753 (help-setup-xref (list 'octave-lookfor str all)
1754 (called-interactively-p 'interactive)))
1755 (goto-char (point-min))
1757 (while (re-search-forward "^\\([^[:blank:]]+\\) " nil 'noerror)
1758 (make-text-button (match-beginning 1) (match-end 1)
1759 :type 'octave-help-function)))
1761 (goto-char (point-max))
1762 (insert "\nRetry with ")
1763 (insert-text-button "'-all'"
1765 'action #'(lambda (_b)
1766 (octave-lookfor str '-all)))
1768 (octave-help-mode)))))
1770 (defcustom octave-source-directories nil
1771 "A list of directories for Octave sources.
1772 If the environment variable OCTAVE_SRCDIR is set, it is searched first."
1773 :type '(repeat directory)
1777 (defun octave-source-directories ()
1778 (let ((srcdir (or (and inferior-octave-process
1779 (process-get inferior-octave-process 'octave-srcdir))
1780 (getenv "OCTAVE_SRCDIR"))))
1782 (cons srcdir octave-source-directories)
1783 octave-source-directories)))
1785 (defvar octave-find-definition-filename-function
1786 #'octave-find-definition-default-filename)
1788 (defun octave-find-definition-default-filename (name)
1789 "Default value for `octave-find-definition-filename-function'."
1790 (pcase (file-name-extension name)
1792 (octave-find-definition-default-filename
1793 (concat "libinterp/dldfcn/"
1794 (file-name-sans-extension (file-name-nondirectory name))
1797 (let ((file (or (locate-file name (octave-source-directories))
1798 (locate-file (file-name-nondirectory name)
1799 (octave-source-directories)))))
1800 (or (and file (file-exists-p file))
1801 (error "File `%s' not found" name))
1804 (if (yes-or-no-p (format "File `%s' may be binary; open? "
1805 (file-name-nondirectory name)))
1807 (user-error "Aborted")))
1810 (defvar find-tag-marker-ring)
1812 (defun octave-find-definition (fn)
1813 "Find the definition of FN.
1814 Functions implemented in C++ can be found if
1815 variable `octave-source-directories' is set correctly."
1816 (interactive (list (octave-completing-read)))
1818 (let ((orig (point)))
1819 (if (and (derived-mode-p 'octave-mode)
1820 (octave-goto-function-definition fn))
1821 (ring-insert find-tag-marker-ring (copy-marker orig))
1822 (inferior-octave-send-list-and-digest
1823 ;; help NAME is more verbose
1825 if iskeyword('%s') disp('`%s'' is a keyword') else which('%s') endif\n"
1828 ;; Skip garbage lines such as
1829 ;; warning: fmincg.m: possible Matlab-style ....
1830 (while (and (not file) (consp inferior-octave-output-list))
1831 (setq line (pop inferior-octave-output-list))
1832 (when (string-match "from the file \\(.*\\)$" line)
1833 (setq file (match-string 1 line))))
1835 (user-error "%s" (or line (format "`%s' not found" fn)))
1836 (ring-insert find-tag-marker-ring (point-marker))
1837 (setq file (funcall octave-find-definition-filename-function file))
1840 (octave-goto-function-definition fn)))))))
1843 ;;; octave.el ends here