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)))
43 (unless (fboundp 'setq-local)
44 (defmacro setq-local (var val)
45 "Set variable VAR to value VAL in current buffer."
46 (list 'set (list 'make-local-variable (list 'quote var)) val))))
49 "Editing Octave code."
50 :link '(custom-group-link :tag "Font Lock Faces group" font-lock-faces)
53 (define-obsolete-function-alias 'octave-submit-bug-report
54 'report-emacs-bug "24.4")
56 (define-abbrev-table 'octave-abbrev-table nil
57 "Abbrev table for Octave's reserved words.
58 Used in `octave-mode' and `inferior-octave-mode' buffers.")
60 (defvar octave-comment-char ?#
61 "Character to start an Octave comment.")
63 (defvar octave-comment-start
64 (string octave-comment-char ?\s)
65 "String to insert to start a new Octave in-line comment.")
67 (defvar octave-comment-start-skip "\\(?:%!\\|\\s<+\\)\\s-*"
68 "Regexp to match the start of an Octave comment up to its body.")
70 (defvar octave-begin-keywords
71 '("classdef" "do" "enumeration" "events" "for" "function" "if" "methods"
72 "parfor" "properties" "switch" "try" "unwind_protect" "while"))
74 (defvar octave-else-keywords
75 '("case" "catch" "else" "elseif" "otherwise" "unwind_protect_cleanup"))
77 (defvar octave-end-keywords
78 '("endclassdef" "endenumeration" "endevents" "endfor" "endfunction" "endif"
79 "endmethods" "endparfor" "endproperties" "endswitch" "end_try_catch"
80 "end_unwind_protect" "endwhile" "until" "end"))
82 (defvar octave-reserved-words
83 (append octave-begin-keywords
86 '("break" "continue" "global" "persistent" "return"))
87 "Reserved words in Octave.")
89 (defvar octave-function-header-regexp
90 (concat "^\\s-*\\_<\\(function\\)\\_>"
91 "\\([^=;\n]*=[ \t]*\\|[ \t]*\\)\\(\\(?:\\w\\|\\s_\\)+\\)\\_>")
92 "Regexp to match an Octave function header.
93 The string `function' and its name are given by the first and third
94 parenthetical grouping.")
97 (defvar octave-mode-map
98 (let ((map (make-sparse-keymap)))
99 (define-key map "\M-." 'octave-find-definition)
100 (define-key map "\M-\C-j" 'octave-indent-new-comment-line)
101 (define-key map "\C-c\C-p" 'octave-previous-code-line)
102 (define-key map "\C-c\C-n" 'octave-next-code-line)
103 (define-key map "\C-c\C-a" 'octave-beginning-of-line)
104 (define-key map "\C-c\C-e" 'octave-end-of-line)
105 (define-key map [remap down-list] 'smie-down-list)
106 (define-key map "\C-c\M-\C-h" 'octave-mark-block)
107 (define-key map "\C-c]" 'smie-close-block)
108 (define-key map "\C-c/" 'smie-close-block)
109 (define-key map "\C-c;" 'octave-update-function-file-comment)
110 (define-key map "\C-hd" 'octave-help)
111 (define-key map "\C-c\C-f" 'octave-insert-defun)
112 (define-key map "\C-c\C-il" 'octave-send-line)
113 (define-key map "\C-c\C-ib" 'octave-send-block)
114 (define-key map "\C-c\C-if" 'octave-send-defun)
115 (define-key map "\C-c\C-ir" 'octave-send-region)
116 (define-key map "\C-c\C-is" 'octave-show-process-buffer)
117 (define-key map "\C-c\C-iq" 'octave-hide-process-buffer)
118 (define-key map "\C-c\C-ik" 'octave-kill-process)
119 (define-key map "\C-c\C-i\C-l" 'octave-send-line)
120 (define-key map "\C-c\C-i\C-b" 'octave-send-block)
121 (define-key map "\C-c\C-i\C-f" 'octave-send-defun)
122 (define-key map "\C-c\C-i\C-r" 'octave-send-region)
123 (define-key map "\C-c\C-i\C-s" 'octave-show-process-buffer)
124 (define-key map "\C-c\C-i\C-q" 'octave-hide-process-buffer)
125 (define-key map "\C-c\C-i\C-k" 'octave-kill-process)
127 "Keymap used in Octave mode.")
131 (easy-menu-define octave-mode-menu octave-mode-map
132 "Menu for Octave mode."
135 ["Previous Code Line" octave-previous-code-line t]
136 ["Next Code Line" octave-next-code-line t]
137 ["Begin of Continuation" octave-beginning-of-line t]
138 ["End of Continuation" octave-end-of-line t]
139 ["Split Line at Point" octave-indent-new-comment-line t])
141 ["Mark Block" octave-mark-block t]
142 ["Close Block" smie-close-block t])
144 ["Insert Function" octave-insert-defun t]
145 ["Update function file comment" octave-update-function-file-comment t])
148 ["Send Current Line" octave-send-line t]
149 ["Send Current Block" octave-send-block t]
150 ["Send Current Function" octave-send-defun t]
151 ["Send Region" octave-send-region t]
152 ["Show Process Buffer" octave-show-process-buffer t]
153 ["Hide Process Buffer" octave-hide-process-buffer t]
154 ["Kill Process" octave-kill-process t])
156 ["Indent Line" indent-according-to-mode t]
157 ["Complete Symbol" completion-at-point t]
158 ["Toggle Auto-Fill Mode" auto-fill-mode
159 :style toggle :selected auto-fill-function]
161 ["Describe Octave Mode" describe-mode t]
162 ["Lookup Octave Index" info-lookup-symbol t]
163 ["Customize Octave" (customize-group 'octave) t]
165 ["Submit Bug Report" report-emacs-bug t]))
167 (defvar octave-mode-syntax-table
168 (let ((table (make-syntax-table)))
169 (modify-syntax-entry ?\r " " table)
170 (modify-syntax-entry ?+ "." table)
171 (modify-syntax-entry ?- "." table)
172 (modify-syntax-entry ?= "." table)
173 (modify-syntax-entry ?* "." table)
174 (modify-syntax-entry ?/ "." table)
175 (modify-syntax-entry ?> "." table)
176 (modify-syntax-entry ?< "." table)
177 (modify-syntax-entry ?& "." table)
178 (modify-syntax-entry ?| "." table)
179 (modify-syntax-entry ?! "." table)
180 (modify-syntax-entry ?\\ "." table)
181 (modify-syntax-entry ?\' "." table)
182 ;; Was "w" for abbrevs, but now that it's not necessary any more,
183 (modify-syntax-entry ?\` "." table)
184 (modify-syntax-entry ?\" "\"" table)
185 (modify-syntax-entry ?. "_" table)
186 (modify-syntax-entry ?_ "_" table)
187 ;; The "b" flag only applies to the second letter of the comstart
188 ;; and the first letter of the comend, i.e. the "4b" below is ineffective.
189 ;; If we try to put `b' on the single-line comments, we get a similar
190 ;; problem where the % and # chars appear as first chars of the 2-char
191 ;; comend, so the multi-line ender is also turned into style-b.
192 ;; So we need the new "c" comment style.
193 (modify-syntax-entry ?\% "< 13" table)
194 (modify-syntax-entry ?\# "< 13" table)
195 (modify-syntax-entry ?\{ "(} 2c" table)
196 (modify-syntax-entry ?\} "){ 4c" table)
197 (modify-syntax-entry ?\n ">" table)
199 "Syntax table in use in `octave-mode' buffers.")
201 (defcustom octave-font-lock-texinfo-comment t
202 "Control whether to highlight the texinfo comment block."
207 (defcustom octave-blink-matching-block t
208 "Control the blinking of matching Octave block keywords.
209 Non-nil means show matching begin of block when inserting a space,
210 newline or semicolon after an else or end keyword."
214 (defcustom octave-block-offset 2
215 "Extra indentation applied to statements in Octave block structures."
219 (defvar octave-block-comment-start
220 (concat (make-string 2 octave-comment-char) " ")
221 "String to insert to start a new Octave comment on an empty line.")
223 (defcustom octave-continuation-offset 4
224 "Extra indentation applied to Octave continuation lines."
229 (defconst octave-continuation-marker-regexp "\\\\\\|\\.\\.\\."))
231 (defvar octave-continuation-regexp
232 (concat "[^#%\n]*\\(" octave-continuation-marker-regexp
233 "\\)\\s-*\\(\\s<.*\\)?$"))
235 ;; Char \ is considered a bad decision for continuing a line.
236 (defconst octave-continuation-string "..."
237 "Character string used for Octave continuation lines.")
239 (defvar octave-mode-imenu-generic-expression
242 (list nil octave-function-header-regexp 3))
243 "Imenu expression for Octave mode. See `imenu-generic-expression'.")
245 (defcustom octave-mode-hook nil
246 "Hook to be run when Octave mode is started."
250 (defcustom octave-send-show-buffer t
251 "Non-nil means display `inferior-octave-buffer' after sending to it."
255 (defcustom octave-send-line-auto-forward t
256 "Control auto-forward after sending to the inferior Octave process.
257 Non-nil means always go to the next Octave code line after sending."
261 (defcustom octave-send-echo-input t
262 "Non-nil means echo input sent to the inferior Octave process."
271 ;; Use '__operators__' in Octave REPL to get a full list.
272 (defconst octave-operator-table
273 '((assoc ";" "\n") (assoc ",") ; The doc claims they have equal precedence!?
274 (right "=" "+=" "-=" "*=" "/=")
275 (assoc "&&") (assoc "||") ; The doc claims they have equal precedence!?
276 (assoc "&") (assoc "|") ; The doc claims they have equal precedence!?
277 (nonassoc "<" "<=" "==" ">=" ">" "!=" "~=")
278 (nonassoc ":") ;No idea what this is.
280 (assoc "*" "/" "\\" ".\\" ".*" "./")
282 (nonassoc "++" "--" "!" "~") ;And unary "+" and "-".
283 (right "^" "**" ".^" ".**")
284 ;; It's not really an operator, but for indentation purposes it
285 ;; could be convenient to treat it as one.
288 (defconst octave-smie-bnf-table
290 ;; We can't distinguish the first element in a sequence with
291 ;; precedence grammars, so we can't distinguish the condition
292 ;; if the `if' from the subsequent body, for example.
293 ;; This has to be done later in the indentation rules.
295 ;; We need to mention at least one of the operators in this part
296 ;; of the grammar: if the BNF and the operator table have
297 ;; no overlap, SMIE can't know how they relate.
299 ("try" exp "catch" exp "end_try_catch")
300 ("try" exp "catch" exp "end")
301 ("unwind_protect" exp
302 "unwind_protect_cleanup" exp "end_unwind_protect")
303 ("unwind_protect" exp "unwind_protect_cleanup" exp "end")
306 ("parfor" exp "endparfor")
308 ("do" exp "until" atom)
309 ("while" exp "endwhile")
312 ("if" exp "else" exp "endif")
313 ("if" exp "elseif" exp "else" exp "endif")
314 ("if" exp "elseif" exp "elseif" exp "else" exp "endif")
315 ("if" exp "elseif" exp "elseif" exp "else" exp "end")
316 ("switch" exp "case" exp "endswitch")
317 ("switch" exp "case" exp "otherwise" exp "endswitch")
318 ("switch" exp "case" exp "case" exp "otherwise" exp "endswitch")
319 ("switch" exp "case" exp "case" exp "otherwise" exp "end")
320 ("function" exp "endfunction")
321 ("function" exp "end")
322 ("enumeration" exp "endenumeration")
323 ("enumeration" exp "end")
324 ("events" exp "endevents")
326 ("methods" exp "endmethods")
327 ("methods" exp "end")
328 ("properties" exp "endproperties")
329 ("properties" exp "end")
330 ("classdef" exp "endclassdef")
331 ("classdef" exp "end"))
332 ;; (fundesc (atom "=" atom))
335 (defconst octave-smie-grammar
338 (smie-bnf->prec2 octave-smie-bnf-table
341 (smie-precs->prec2 octave-operator-table))))
343 ;; Tokenizing needs to be refined so that ";;" is treated as two
344 ;; tokens and also so as to recognize the \n separator (and
345 ;; corresponding continuation lines).
347 (defconst octave-operator-regexp
348 (regexp-opt (apply 'append (mapcar 'cdr octave-operator-table))))
350 (defun octave-smie-backward-token ()
352 (forward-comment (- (point)))
354 ((and (not (eq (char-before) ?\;)) ;Coalesce ";" and "\n".
355 (> pos (line-end-position))
356 (if (looking-back octave-continuation-marker-regexp (- (point) 3))
358 (goto-char (match-beginning 0))
359 (forward-comment (- (point)))
362 ;; Ignore it if it's within parentheses.
363 (let ((ppss (syntax-ppss)))
364 (not (and (nth 1 ppss)
365 (eq ?\( (char-after (nth 1 ppss)))))))
366 (skip-chars-forward " \t")
367 ;; Why bother distinguishing \n and ;?
369 ((and (looking-back octave-operator-regexp (- (point) 3) 'greedy)
370 ;; Don't mistake a string quote for a transpose.
371 (not (looking-back "\\s\"" (1- (point)))))
372 (goto-char (match-beginning 0))
373 (match-string-no-properties 0))
375 (smie-default-backward-token)))))
377 (defun octave-smie-forward-token ()
378 (skip-chars-forward " \t")
379 (when (looking-at (eval-when-compile
380 (concat "\\(" octave-continuation-marker-regexp
381 "\\)[ \t]*\\($\\|[%#]\\)")))
382 (goto-char (match-end 1))
385 ((and (looking-at "[%#\n]")
386 (not (or (save-excursion (skip-chars-backward " \t")
387 ;; Only add implicit ; when needed.
388 (or (bolp) (eq (char-before) ?\;)))
389 ;; Ignore it if it's within parentheses.
390 (let ((ppss (syntax-ppss)))
392 (eq ?\( (char-after (nth 1 ppss))))))))
393 (if (eolp) (forward-char 1) (forward-comment 1))
394 ;; Why bother distinguishing \n and ;?
396 ((progn (forward-comment (point-max)) nil))
397 ((looking-at ";[ \t]*\\($\\|[%#]\\)")
398 ;; Combine the ; with the subsequent \n.
399 (goto-char (match-beginning 1))
402 ((and (looking-at octave-operator-regexp)
403 ;; Don't mistake a string quote for a transpose.
404 (not (looking-at "\\s\"")))
405 (goto-char (match-end 0))
406 (match-string-no-properties 0))
408 (smie-default-forward-token))))
410 (defun octave-smie-rules (kind token)
411 (pcase (cons kind token)
412 ;; We could set smie-indent-basic instead, but that would have two
414 ;; - changes to octave-block-offset wouldn't take effect immediately.
415 ;; - edebug wouldn't show the use of this variable.
416 (`(:elem . basic) octave-block-offset)
417 ;; Since "case" is in the same BNF rules as switch..end, SMIE by default
418 ;; aligns it with "switch".
419 (`(:before . "case") (if (not (smie-rule-sibling-p)) octave-block-offset))
421 (if (smie-rule-parent-p "classdef" "events" "enumeration" "function" "if"
422 "while" "else" "elseif" "for" "parfor"
423 "properties" "methods" "otherwise" "case"
424 "try" "catch" "unwind_protect"
425 "unwind_protect_cleanup")
426 (smie-rule-parent octave-block-offset)
427 ;; For (invalid) code between switch and case.
428 ;; (if (smie-parent-p "switch") 4)
431 (defun octave-indent-comment ()
432 "A function for `smie-indent-functions' (which see)."
434 (back-to-indentation)
436 ((octave-in-string-or-comment-p) nil)
437 ((looking-at-p "\\s<\\{3,\\}")
439 ;; Exclude %{, %} and %!.
440 ((and (looking-at-p "\\s<\\(?:[^{}!]\\|$\\)")
441 (not (looking-at-p "\\s<\\s<")))
442 (comment-choose-indent)))))
445 (defvar octave-font-lock-keywords
447 ;; Fontify all builtin keywords.
448 (cons (concat "\\_<\\("
449 (regexp-opt octave-reserved-words)
451 'font-lock-keyword-face)
452 ;; Note: 'end' also serves as the last index in an indexing expression.
453 ;; Ref: http://www.mathworks.com/help/matlab/ref/end.html
454 (list (lambda (limit)
455 (while (re-search-forward "\\_<end\\_>" limit 'move)
456 (let ((beg (match-beginning 0))
458 (unless (octave-in-string-or-comment-p)
463 (when (memq (char-after) '(?\( ?\[ ?\{))
464 (put-text-property beg end 'face nil))
466 (error (goto-char end))))))
468 ;; Fontify all operators.
469 (cons octave-operator-regexp 'font-lock-builtin-face)
470 ;; Fontify all function declarations.
471 (list octave-function-header-regexp
472 '(1 font-lock-keyword-face)
473 '(3 font-lock-function-name-face nil t)))
474 "Additional Octave expressions to highlight.")
476 (defun octave-syntax-propertize-function (start end)
478 (octave-syntax-propertize-sqs end)
479 (funcall (syntax-propertize-rules
480 ("\\\\" (0 (when (eq (nth 3 (save-excursion
481 (syntax-ppss (match-beginning 0))))
483 (string-to-syntax "\\"))))
484 ;; Try to distinguish the string-quotes from the transpose-quotes.
485 ("\\(?:^\\|[[({,; ]\\)\\('\\)"
486 (1 (prog1 "\"'" (octave-syntax-propertize-sqs end)))))
489 (defun octave-syntax-propertize-sqs (end)
490 "Propertize the content/end of single-quote strings."
491 (when (eq (nth 3 (syntax-ppss)) ?\')
493 (when (re-search-forward
494 "\\(?:\\=\\|[^']\\)\\(?:''\\)*\\('\\)\\($\\|[^']\\)" end 'move)
495 (goto-char (match-beginning 2))
496 (when (eq (char-before (match-beginning 1)) ?\\)
497 ;; Backslash cannot escape a single quote.
498 (put-text-property (1- (match-beginning 1)) (match-beginning 1)
499 'syntax-table (string-to-syntax ".")))
500 (put-text-property (match-beginning 1) (match-end 1)
501 'syntax-table (string-to-syntax "\"'")))))
503 (defvar electric-layout-rules)
506 (define-derived-mode octave-mode prog-mode "Octave"
507 "Major mode for editing Octave code.
509 Octave is a high-level language, primarily intended for numerical
510 computations. It provides a convenient command line interface
511 for solving linear and nonlinear problems numerically. Function
512 definitions can also be stored in files and used in batch mode."
513 :abbrev-table octave-abbrev-table
515 (smie-setup octave-smie-grammar #'octave-smie-rules
516 :forward-token #'octave-smie-forward-token
517 :backward-token #'octave-smie-backward-token)
518 (setq-local smie-indent-basic 'octave-block-offset)
519 (add-hook 'smie-indent-functions #'octave-indent-comment nil t)
521 (setq-local smie-blink-matching-triggers
522 (cons ?\; smie-blink-matching-triggers))
523 (unless octave-blink-matching-block
524 (remove-hook 'post-self-insert-hook #'smie-blink-matching-open 'local))
526 (setq-local electric-indent-chars
527 (cons ?\; electric-indent-chars))
528 ;; IIUC matlab-mode takes the opposite approach: it makes RET insert
529 ;; a ";" at those places where it's correct (i.e. outside of parens).
530 (setq-local electric-layout-rules '((?\; . after)))
532 (setq-local comment-start octave-comment-start)
533 (setq-local comment-end "")
534 (setq-local comment-start-skip octave-comment-start-skip)
535 (setq-local comment-add 1)
537 (setq-local parse-sexp-ignore-comments t)
538 (setq-local paragraph-start (concat "\\s-*$\\|" page-delimiter))
539 (setq-local paragraph-separate paragraph-start)
540 (setq-local paragraph-ignore-fill-prefix t)
541 (setq-local fill-paragraph-function 'octave-fill-paragraph)
542 ;; FIXME: Why disable it?
543 ;; (setq-local adaptive-fill-regexp nil)
544 ;; Again, this is not a property of the language, don't set it here.
545 ;; (setq fill-column 72)
546 (setq-local normal-auto-fill-function 'octave-auto-fill)
548 (setq font-lock-defaults '(octave-font-lock-keywords))
550 (setq-local syntax-propertize-function #'octave-syntax-propertize-function)
552 (setq-local imenu-generic-expression octave-mode-imenu-generic-expression)
553 (setq-local imenu-case-fold-search nil)
555 (add-hook 'completion-at-point-functions 'octave-completion-at-point nil t)
556 (add-hook 'before-save-hook 'octave-sync-function-file-names nil t)
557 (setq-local beginning-of-defun-function 'octave-beginning-of-defun)
558 (and octave-font-lock-texinfo-comment (octave-font-lock-texinfo-comment))
559 (setq-local eldoc-documentation-function 'octave-eldoc-function)
561 (easy-menu-add octave-mode-menu))
564 (defcustom inferior-octave-program "octave"
565 "Program invoked by `inferior-octave'."
569 (defcustom inferior-octave-buffer "*Inferior Octave*"
570 "Name of buffer for running an inferior Octave process."
574 (defcustom inferior-octave-prompt
575 "\\(^octave\\(\\|.bin\\|.exe\\)\\(-[.0-9]+\\)?\\(:[0-9]+\\)?\\|^debug\\|^\\)>+ "
576 "Regexp to match prompts for the inferior Octave process."
580 (defcustom inferior-octave-prompt-read-only comint-prompt-read-only
581 "If non-nil, the Octave prompt is read only.
582 See `comint-prompt-read-only' for details."
587 (defcustom inferior-octave-startup-file
588 (convert-standard-filename
589 (concat "~/.emacs-" (file-name-nondirectory inferior-octave-program)))
590 "Name of the inferior Octave startup file.
591 The contents of this file are sent to the inferior Octave process on
593 :type '(choice (const :tag "None" nil) file)
597 (defcustom inferior-octave-startup-args nil
598 "List of command line arguments for the inferior Octave process.
599 For example, for suppressing the startup message and using `traditional'
600 mode, set this to (\"-q\" \"--traditional\")."
601 :type '(repeat string)
604 (defcustom inferior-octave-mode-hook nil
605 "Hook to be run when Inferior Octave mode is started."
609 (defvar inferior-octave-process nil)
611 (defvar inferior-octave-mode-map
612 (let ((map (make-sparse-keymap)))
613 (set-keymap-parent map comint-mode-map)
614 (define-key map "\M-." 'octave-find-definition)
615 (define-key map "\t" 'completion-at-point)
616 (define-key map "\C-hd" 'octave-help)
617 ;; Same as in `shell-mode'.
618 (define-key map "\M-?" 'comint-dynamic-list-filename-completions)
619 (define-key map "\C-c\C-l" 'inferior-octave-dynamic-list-input-ring)
620 (define-key map [menu-bar inout list-history]
621 '("List Input History" . inferior-octave-dynamic-list-input-ring))
623 "Keymap used in Inferior Octave mode.")
625 (defvar inferior-octave-mode-syntax-table
626 (let ((table (make-syntax-table octave-mode-syntax-table)))
628 "Syntax table in use in inferior-octave-mode buffers.")
630 (defvar inferior-octave-font-lock-keywords
632 (cons inferior-octave-prompt 'font-lock-type-face))
633 ;; Could certainly do more font locking in inferior Octave ...
634 "Additional expressions to highlight in Inferior Octave mode.")
636 (defvar inferior-octave-output-list nil)
637 (defvar inferior-octave-output-string nil)
638 (defvar inferior-octave-receive-in-progress nil)
640 (define-obsolete-variable-alias 'inferior-octave-startup-hook
641 'inferior-octave-mode-hook "24.4")
643 (defvar inferior-octave-dynamic-complete-functions
644 '(inferior-octave-completion-at-point comint-filename-completion)
645 "List of functions called to perform completion for inferior Octave.
646 This variable is used to initialize `comint-dynamic-complete-functions'
647 in the Inferior Octave buffer.")
649 (defvar info-lookup-mode)
651 (define-derived-mode inferior-octave-mode comint-mode "Inferior Octave"
652 "Major mode for interacting with an inferior Octave process."
653 :abbrev-table octave-abbrev-table
654 (setq comint-prompt-regexp inferior-octave-prompt)
656 (setq-local comment-start octave-comment-start)
657 (setq-local comment-end "")
658 (setq comment-column 32)
659 (setq-local comment-start-skip octave-comment-start-skip)
661 (setq font-lock-defaults '(inferior-octave-font-lock-keywords nil nil))
663 (setq-local info-lookup-mode 'octave-mode)
664 (setq-local eldoc-documentation-function 'octave-eldoc-function)
666 (setq comint-input-ring-file-name
667 (or (getenv "OCTAVE_HISTFILE") "~/.octave_hist")
668 comint-input-ring-size (or (getenv "OCTAVE_HISTSIZE") 1024))
669 (setq-local comint-dynamic-complete-functions
670 inferior-octave-dynamic-complete-functions)
671 (setq-local comint-prompt-read-only inferior-octave-prompt-read-only)
672 (add-hook 'comint-input-filter-functions
673 'inferior-octave-directory-tracker nil t)
674 (comint-read-input-ring t))
677 (defun inferior-octave (&optional arg)
678 "Run an inferior Octave process, I/O via `inferior-octave-buffer'.
679 This buffer is put in Inferior Octave mode. See `inferior-octave-mode'.
681 Unless ARG is non-nil, switches to this buffer.
683 The elements of the list `inferior-octave-startup-args' are sent as
684 command line arguments to the inferior Octave process on startup.
686 Additional commands to be executed on startup can be provided either in
687 the file specified by `inferior-octave-startup-file' or by the default
688 startup file, `~/.emacs-octave'."
690 (let ((buffer (get-buffer-create inferior-octave-buffer)))
691 (unless (comint-check-proc buffer)
692 (with-current-buffer buffer
693 (inferior-octave-startup)
694 (inferior-octave-mode)))
696 (pop-to-buffer buffer))
700 (defalias 'run-octave 'inferior-octave)
702 (defun inferior-octave-startup ()
703 "Start an inferior Octave process."
704 (let ((proc (comint-exec-1
705 (substring inferior-octave-buffer 1 -1)
706 inferior-octave-buffer
707 inferior-octave-program
708 (append (list "-i" "--no-line-editing")
709 inferior-octave-startup-args))))
710 (set-process-filter proc 'inferior-octave-output-digest)
711 (setq inferior-octave-process proc
712 inferior-octave-output-list nil
713 inferior-octave-output-string nil
714 inferior-octave-receive-in-progress t)
716 ;; This may look complicated ... However, we need to make sure that
717 ;; we additional startup code only AFTER Octave is ready (otherwise,
718 ;; output may be mixed up). Hence, we need to digest the Octave
719 ;; output to see when it issues a prompt.
720 (while inferior-octave-receive-in-progress
721 (accept-process-output inferior-octave-process))
722 (goto-char (point-max))
723 (set-marker (process-mark proc) (point))
724 (insert-before-markers
726 (if (not (bobp)) "
\f\n")
727 (if inferior-octave-output-list
729 'identity inferior-octave-output-list "\n")
732 ;; An empty secondary prompt, as e.g. obtained by '--braindead',
734 (inferior-octave-send-list-and-digest (list "PS2\n"))
735 (when (string-match "\\(PS2\\|ans\\) = *$"
736 (car inferior-octave-output-list))
737 (inferior-octave-send-list-and-digest (list "PS2 (\"> \");\n")))
739 (inferior-octave-send-list-and-digest
740 (list "if exist(\"__octave_srcdir__\") disp(__octave_srcdir__) endif\n"))
741 (process-put proc 'octave-srcdir (car inferior-octave-output-list))
743 ;; O.K., now we are ready for the Inferior Octave startup commands.
744 (inferior-octave-send-list-and-digest
746 (unless (equal inferior-octave-output-string ">> ")
747 "PS1 (\"\\\\s> \");\n")
748 (when (and inferior-octave-startup-file
749 (file-exists-p inferior-octave-startup-file))
750 (format "source (\"%s\");\n" inferior-octave-startup-file))))
751 (insert-before-markers
753 (if inferior-octave-output-list
755 'identity inferior-octave-output-list "\n")
757 inferior-octave-output-string))
759 ;; And finally, everything is back to normal.
760 (set-process-filter proc 'comint-output-filter)
761 ;; Just in case, to be sure a cd in the startup file
762 ;; won't have detrimental effects.
763 (inferior-octave-resync-dirs)
764 ;; A trick to get the prompt highlighted.
765 (comint-send-string proc "\n")))
767 (defvar inferior-octave-completion-table
769 ;; Use cache to avoid repetitive computation of completions due to
770 ;; bug#11906 - http://debbugs.gnu.org/11906 - which may cause
771 ;; noticeable delay. CACHE: (CMD TIME VALUE).
773 (completion-table-dynamic
775 (unless (and (equal (car cache) command)
776 (< (float-time) (+ 5 (cadr cache))))
777 (inferior-octave-send-list-and-digest
778 (list (concat "completion_matches (\"" command "\");\n")))
779 (setq cache (list command (float-time)
780 (sort (delete-dups inferior-octave-output-list)
782 (car (cddr cache))))))
784 (defun inferior-octave-completion-at-point ()
785 "Return the data to complete the Octave symbol at point."
786 ;; http://debbugs.gnu.org/14300
787 (let* ((filecomp (string-match-p
788 "/" (or (comint--match-partial-filename) "")))
793 (skip-syntax-backward "w_" (comint-line-beginning-position))
795 (when (and start (> end start))
796 (list start end (completion-table-in-turn
797 inferior-octave-completion-table
798 'comint-completion-file-name-table)))))
800 (define-obsolete-function-alias 'inferior-octave-complete
801 'completion-at-point "24.1")
803 (defun inferior-octave-dynamic-list-input-ring ()
804 "List the buffer's input history in a help buffer."
805 ;; We cannot use `comint-dynamic-list-input-ring', because it replaces
806 ;; "completion" by "history reference" ...
808 (if (or (not (ring-p comint-input-ring))
809 (ring-empty-p comint-input-ring))
810 (message "No history")
812 (history-buffer " *Input History*")
813 (index (1- (ring-length comint-input-ring)))
814 (conf (current-window-configuration)))
815 ;; We have to build up a list ourselves from the ring vector.
817 (setq history (cons (ring-ref comint-input-ring index) history)
819 ;; Change "completion" to "history reference"
820 ;; to make the display accurate.
821 (with-output-to-temp-buffer history-buffer
822 (display-completion-list history)
823 (set-buffer history-buffer))
824 (message "Hit space to flush")
825 (let ((ch (read-event)))
827 (set-window-configuration conf)
828 (setq unread-command-events (list ch)))))))
830 (defun inferior-octave-output-digest (_proc string)
831 "Special output filter for the inferior Octave process.
832 Save all output between newlines into `inferior-octave-output-list', and
833 the rest to `inferior-octave-output-string'."
834 (setq string (concat inferior-octave-output-string string))
835 (while (string-match "\n" string)
836 (setq inferior-octave-output-list
837 (append inferior-octave-output-list
838 (list (substring string 0 (match-beginning 0))))
839 string (substring string (match-end 0))))
840 (if (string-match inferior-octave-prompt string)
841 (setq inferior-octave-receive-in-progress nil))
842 (setq inferior-octave-output-string string))
844 (defun inferior-octave-check-process ()
845 (or (and inferior-octave-process
846 (process-live-p inferior-octave-process))
847 (error (substitute-command-keys
848 "No inferior octave process running. Type \\[run-octave]"))))
850 (defun inferior-octave-send-list-and-digest (list)
851 "Send LIST to the inferior Octave process and digest the output.
852 The elements of LIST have to be strings and are sent one by one. All
853 output is passed to the filter `inferior-octave-output-digest'."
854 (inferior-octave-check-process)
855 (let* ((proc inferior-octave-process)
856 (filter (process-filter proc))
858 (set-process-filter proc 'inferior-octave-output-digest)
859 (setq inferior-octave-output-list nil)
861 (while (setq string (car list))
862 (setq inferior-octave-output-string nil
863 inferior-octave-receive-in-progress t)
864 (comint-send-string proc string)
865 (while inferior-octave-receive-in-progress
866 (accept-process-output proc))
867 (setq list (cdr list)))
868 (set-process-filter proc filter))))
870 (defun inferior-octave-directory-tracker (string)
871 "Tracks `cd' commands issued to the inferior Octave process.
872 Use \\[inferior-octave-resync-dirs] to resync if Emacs gets confused."
874 ((string-match "^[ \t]*cd[ \t;]*$" string)
876 ((string-match "^[ \t]*cd[ \t]+\\([^ \t\n;]*\\)[ \t\n;]*" string)
877 (with-demoted-errors ; in case directory doesn't exist
878 (cd (substring string (match-beginning 1) (match-end 1)))))))
880 (defun inferior-octave-resync-dirs ()
881 "Resync the buffer's idea of the current directory.
882 This command queries the inferior Octave process about its current
883 directory and makes this the current buffer's default directory."
885 (inferior-octave-send-list-and-digest '("disp (pwd ())\n"))
886 (cd (car inferior-octave-output-list)))
889 ;;; Miscellaneous useful functions
891 (defun octave-in-comment-p ()
892 "Return non-nil if point is inside an Octave comment."
893 (nth 4 (syntax-ppss)))
895 (defun octave-in-string-p ()
896 "Return non-nil if point is inside an Octave string."
897 (nth 3 (syntax-ppss)))
899 (defun octave-in-string-or-comment-p ()
900 "Return non-nil if point is inside an Octave string or comment."
901 (nth 8 (syntax-ppss)))
903 (defun octave-looking-at-kw (regexp)
904 "Like `looking-at', but sets `case-fold-search' nil."
905 (let ((case-fold-search nil))
906 (looking-at regexp)))
908 (defun octave-maybe-insert-continuation-string ()
909 (if (or (octave-in-comment-p)
912 (looking-at octave-continuation-regexp)))
914 (delete-horizontal-space)
915 (insert (concat " " octave-continuation-string))))
917 (defun octave-completing-read ()
918 (let ((def (or (thing-at-point 'symbol)
920 (skip-syntax-backward "-(")
921 (thing-at-point 'symbol)))))
923 (format (if def "Function (default %s): "
925 inferior-octave-completion-table
926 nil nil nil nil def)))
928 (defun octave-goto-function-definition (fn)
929 "Go to the function definition of FN in current buffer."
930 (goto-char (point-min))
934 (while (and (not done) (re-search-forward re nil t))
935 (when (and (equal (match-string sub) fn)
936 (not (nth 8 (syntax-ppss))))
938 (or done (goto-char (point-min)))))))
939 (pcase (file-name-extension (buffer-file-name))
940 (`"cc" (funcall search
941 "\\_<DEFUN\\s-*(\\s-*\\(\\(?:\\sw\\|\\s_\\)+\\)" 1))
942 (t (funcall search octave-function-header-regexp 3)))))
944 (defun octave-function-file-p ()
945 "Return non-nil if the first token is \"function\".
946 The value is (START END NAME-START NAME-END) of the function."
948 (goto-char (point-min))
949 (when (equal (funcall smie-forward-token-function) "function")
951 (let* ((start (point))
952 (end (progn (forward-sexp 1) (point)))
955 (re-search-forward octave-function-header-regexp
957 (list (match-beginning 3) (match-end 3)))))
958 (cons start (cons end name))))))
960 ;; Like forward-comment but stop at non-comment blank
961 (defun octave-skip-comment-forward (limit)
962 (let ((ppss (syntax-ppss)))
964 (goto-char (nth 8 ppss))
965 (goto-char (or (comment-search-forward limit t) (point)))))
966 (while (and (< (point) limit) (looking-at-p "\\s<"))
967 (forward-comment 1)))
969 ;;; First non-copyright comment block
970 (defun octave-function-file-comment ()
971 "Beginning and end positions of the function file comment."
973 (goto-char (point-min))
974 ;; Copyright block: octave/libinterp/parse-tree/lex.ll around line 1634
975 (while (save-excursion
976 (when (comment-search-forward (point-max) t)
977 (when (eq (char-after) ?\{) ; case of block comment
979 (skip-syntax-forward "-")
980 (let ((case-fold-search t))
981 (looking-at-p "\\(?:copyright\\|author\\)\\_>"))))
982 (octave-skip-comment-forward (point-max)))
983 (let ((beg (comment-search-forward (point-max) t)))
986 (octave-skip-comment-forward (point-max))
987 (list beg (point))))))
989 (defun octave-sync-function-file-names ()
990 "Ensure function name agree with function file name.
991 See Info node `(octave)Function Files'."
993 (when buffer-file-name
994 (pcase-let ((`(,start ,_end ,name-start ,name-end)
995 (octave-function-file-p)))
996 (when (and start name-start)
997 (let* ((func (buffer-substring name-start name-end))
998 (file (file-name-sans-extension
999 (file-name-nondirectory buffer-file-name)))
1000 (help-form (format "\
1001 a: Use function name `%s'
1002 b: Use file name `%s'
1003 q: Don't fix\n" func file))
1004 (c (unless (equal file func)
1005 (save-window-excursion
1008 "Which name to use? (a/b/q) " '(?a ?b ?q))))))
1010 (`?a (let ((newname (expand-file-name
1011 (concat func (file-name-extension
1012 buffer-file-name t)))))
1013 (when (or (not (file-exists-p newname))
1015 (format "Target file %s exists; proceed? " newname)))
1016 (when (file-exists-p buffer-file-name)
1017 (rename-file buffer-file-name newname t))
1018 (set-visited-file-name newname))))
1019 (`?b (save-excursion
1020 (goto-char name-start)
1021 (delete-region name-start name-end)
1022 (insert file)))))))))
1024 (defun octave-update-function-file-comment (beg end)
1025 "Query replace function names in function file comment."
1028 (barf-if-buffer-read-only)
1030 (list (region-beginning) (region-end))
1031 (or (octave-function-file-comment)
1032 (error "No function file comment found")))))
1034 (let* ((bounds (or (octave-function-file-p)
1035 (error "Not in a function file buffer")))
1036 (func (if (cddr bounds)
1037 (apply #'buffer-substring (cddr bounds))
1038 (error "Function name not found")))
1041 (when (re-search-forward
1042 "[=}]\\s-*\\(\\(?:\\sw\\|\\s_\\)+\\)\\_>"
1043 (min (line-end-position 4) end)
1046 (old-func (read-string (format (if old-func
1047 "Name to replace (default %s): "
1048 "Name to replace: ")
1051 (if (and func old-func (not (equal func old-func)))
1052 (perform-replace old-func func 'query
1053 nil 'delimited nil nil beg end)
1054 (message "Function names match")))))
1056 (defface octave-function-comment-block
1057 '((t (:inherit font-lock-doc-face)))
1058 "Face used to highlight function comment block."
1061 (eval-when-compile (require 'texinfo))
1063 (defun octave-font-lock-texinfo-comment ()
1068 (if (numberp (nth 1 kw))
1069 `(,(nth 0 kw) ,(nth 1 kw) ,(nth 2 kw) prepend)
1070 (message "Ignoring Texinfo highlight: %S" kw)))
1071 texinfo-font-lock-keywords)))))
1072 (font-lock-add-keywords
1075 (while (and (< (point) limit)
1076 (search-forward "-*- texinfo -*-" limit t)
1077 (octave-in-comment-p))
1078 (let ((beg (nth 8 (syntax-ppss)))
1080 (octave-skip-comment-forward (point-max))
1082 (put-text-property beg end 'font-lock-multiline t)
1083 (font-lock-prepend-text-property
1084 beg end 'face 'octave-function-comment-block)
1087 (while (re-search-forward (car kw) end 'move)
1088 (font-lock-apply-highlight (cdr kw))))))
1095 (defun octave-indent-new-comment-line ()
1096 "Break Octave line at point, continuing comment if within one.
1097 If within code, insert `octave-continuation-string' before breaking the
1098 line. If within a string, signal an error.
1099 The new line is properly indented."
1101 (delete-horizontal-space)
1103 ((octave-in-comment-p)
1104 (indent-new-comment-line))
1105 ((octave-in-string-p)
1106 (error "Cannot split a code line inside a string"))
1108 (insert (concat " " octave-continuation-string))
1109 (reindent-then-newline-and-indent))))
1111 (define-obsolete-function-alias
1112 'octave-indent-defun 'prog-indent-sexp "24.4")
1116 (defun octave-next-code-line (&optional arg)
1117 "Move ARG lines of Octave code forward (backward if ARG is negative).
1118 Skips past all empty and comment lines. Default for ARG is 1.
1120 On success, return 0. Otherwise, go as far as possible and return -1."
1122 (or arg (setq arg 1))
1125 (inc (if (> arg 0) 1 -1)))
1126 (while (and (/= arg 0) (= n 0))
1127 (setq n (forward-line inc))
1129 (looking-at "\\s-*\\($\\|\\s<\\)"))
1130 (setq n (forward-line inc)))
1131 (setq arg (- arg inc)))
1134 (defun octave-previous-code-line (&optional arg)
1135 "Move ARG lines of Octave code backward (forward if ARG is negative).
1136 Skips past all empty and comment lines. Default for ARG is 1.
1138 On success, return 0. Otherwise, go as far as possible and return -1."
1140 (or arg (setq arg 1))
1141 (octave-next-code-line (- arg)))
1143 (defun octave-beginning-of-line ()
1144 "Move point to beginning of current Octave line.
1145 If on an empty or comment line, go to the beginning of that line.
1146 Otherwise, move backward to the beginning of the first Octave code line
1147 which is not inside a continuation statement, i.e., which does not
1148 follow a code line ending with `...' or is inside an open
1152 (unless (looking-at "\\s-*\\($\\|\\s<\\)")
1153 (while (or (when (cadr (syntax-ppss))
1154 (goto-char (cadr (syntax-ppss)))
1157 (and (or (looking-at "\\s-*\\($\\|\\s<\\)")
1159 (if (zerop (octave-previous-code-line))
1160 (looking-at octave-continuation-regexp))))
1161 (zerop (forward-line -1)))))))
1163 (defun octave-end-of-line ()
1164 "Move point to end of current Octave line.
1165 If on an empty or comment line, go to the end of that line.
1166 Otherwise, move forward to the end of the first Octave code line which
1167 does not end with `...' or is inside an open parenthesis list."
1170 (unless (save-excursion
1172 (looking-at "\\s-*\\($\\|\\s<\\)"))
1173 (while (or (when (cadr (syntax-ppss))
1180 (and (save-excursion
1182 (or (looking-at "\\s-*\\($\\|\\s<\\)")
1183 (looking-at octave-continuation-regexp)))
1184 (zerop (forward-line 1)))))
1187 (defun octave-mark-block ()
1188 "Put point at the beginning of this Octave block, mark at the end.
1189 The block marked is the one that contains point or follows point."
1191 (if (and (looking-at "\\sw\\|\\s_")
1192 (looking-back "\\sw\\|\\s_" (1- (point))))
1193 (skip-syntax-forward "w_"))
1194 (unless (or (looking-at "\\s(")
1196 (let* ((token (funcall smie-forward-token-function))
1197 (level (assoc token smie-grammar)))
1198 (and level (not (numberp (cadr level)))))))
1199 (backward-up-list 1))
1202 (defun octave-beginning-of-defun (&optional arg)
1203 "Octave-specific `beginning-of-defun-function' (which see)."
1204 (or arg (setq arg 1))
1205 ;; Move out of strings or comments.
1206 (when (octave-in-string-or-comment-p)
1207 (goto-char (octave-in-string-or-comment-p)))
1208 (letrec ((orig (point))
1209 (toplevel (lambda (pos)
1212 (backward-up-list 1)
1213 (funcall toplevel (point)))
1214 (scan-error pos)))))
1215 (goto-char (funcall toplevel (point)))
1216 (when (and (> arg 0) (/= orig (point)))
1217 (setq arg (1- arg)))
1218 (forward-sexp (- arg))
1223 (defun octave-auto-fill ()
1224 "Perform auto-fill in Octave mode.
1225 Returns nil if no feasible place to break the line could be found, and t
1228 (if (or (null (setq fc (current-fill-column)))
1231 (and auto-fill-inhibit-regexp
1232 (octave-looking-at-kw auto-fill-inhibit-regexp))))
1233 nil ; Can't do anything
1234 (if (and (not (octave-in-comment-p))
1235 (> (current-column) fc))
1236 (setq fc (- fc (+ (length octave-continuation-string) 1))))
1237 (while (and (not give-up) (> (current-column) fc))
1238 (let* ((opoint (point))
1241 (move-to-column (+ fc 1))
1242 (skip-chars-backward "^ \t\n")
1243 ;; If we're at the beginning of the line, break after
1246 (re-search-forward "[ \t]" opoint t))
1247 ;; If we're in a comment line, don't break after the
1250 (skip-syntax-backward " <")
1252 (re-search-forward "[ \t]" (line-end-position)
1254 ;; If we're not in a comment line and just ahead the
1255 ;; continuation string, don't break here.
1256 (if (and (not (octave-in-comment-p))
1260 octave-continuation-string)
1263 (skip-chars-backward " \t")
1267 (not (or (bolp) (eolp))))
1268 (let ((prev-column (current-column)))
1270 (skip-chars-backward " \t")
1273 (octave-maybe-insert-continuation-string)
1274 (indent-new-comment-line t))
1277 (octave-maybe-insert-continuation-string)
1278 (indent-new-comment-line t)))
1279 (if (>= (current-column) prev-column)
1284 (defun octave-fill-paragraph (&optional _arg)
1285 "Fill paragraph of Octave code, handling Octave comments."
1286 ;; FIXME: difference with generic fill-paragraph:
1287 ;; - code lines are only split, never joined.
1288 ;; - \n that end comments are never removed.
1289 ;; - insert continuation marker when splitting code lines.
1292 (let ((end (progn (forward-paragraph) (copy-marker (point) t)))
1294 (forward-paragraph -1)
1295 (skip-chars-forward " \t\n")
1298 (cfc (current-fill-column))
1301 (while (< (point) end)
1303 (indent-according-to-mode)
1305 (move-to-column cfc)
1306 ;; First check whether we need to combine non-empty comment lines
1307 (if (and (< (current-column) cfc)
1308 (octave-in-comment-p)
1309 (not (save-excursion
1311 (looking-at "^\\s-*\\s<+\\s-*$"))))
1312 ;; This is a nonempty comment line which does not extend
1313 ;; past the fill column. If it is followed by a nonempty
1314 ;; comment line with the same comment prefix, try to
1315 ;; combine them, and repeat this until either we reach the
1316 ;; fill-column or there is nothing more to combine.
1318 ;; Get the comment prefix
1321 (while (and (re-search-forward "\\s<+")
1322 (not (octave-in-comment-p))))
1323 (setq comment-prefix (match-string 0)))
1324 ;; And keep combining ...
1325 (while (and (< (current-column) cfc)
1337 (re-search-forward comment-prefix)
1338 (delete-region (match-beginning 0) (match-end 0))
1340 (move-to-column cfc))))
1341 ;; We might also try to combine continued code lines> Perhaps
1342 ;; some other time ...
1343 (skip-chars-forward "^ \t\n")
1344 (delete-horizontal-space)
1345 (if (or (< (current-column) cfc)
1346 (and (= (current-column) cfc) (eolp)))
1348 (if (not (eolp)) (insert " "))
1349 (or (octave-auto-fill)
1356 (defun octave-completion-at-point ()
1357 "Find the text to complete and the corresponding table."
1358 (let* ((beg (save-excursion (skip-syntax-backward "w_") (point)))
1361 ;; Extend region past point, if applicable.
1362 (save-excursion (skip-syntax-forward "w_")
1363 (setq end (point))))
1365 (list beg end (or (and inferior-octave-process
1366 (process-live-p inferior-octave-process)
1367 inferior-octave-completion-table)
1368 octave-reserved-words)))))
1370 (define-obsolete-function-alias 'octave-complete-symbol
1371 'completion-at-point "24.1")
1373 ;;; Electric characters && friends
1374 (define-skeleton octave-insert-defun
1375 "Insert an Octave function skeleton.
1376 Prompt for the function's name, arguments and return values (to be
1377 entered without parens)."
1378 (let* ((defname (file-name-sans-extension (buffer-name)))
1379 (name (read-string (format "Function name (default %s): " defname)
1381 (args (read-string "Arguments: "))
1382 (vals (read-string "Return values: ")))
1385 ((string-equal vals "") vals)
1386 ((string-match "[ ,]" vals) (concat "[" vals "] = "))
1387 (t (concat vals " = ")))
1390 \n octave-block-comment-start "usage: " str \n
1391 octave-block-comment-start '(delete-horizontal-space) \n
1392 octave-block-comment-start '(delete-horizontal-space) \n
1393 "function " > str \n
1397 ;;; Communication with the inferior Octave process
1398 (defun octave-kill-process ()
1399 "Kill inferior Octave process and its buffer."
1401 (if inferior-octave-process
1403 (process-send-string inferior-octave-process "quit;\n")
1404 (accept-process-output inferior-octave-process)))
1405 (if inferior-octave-buffer
1406 (kill-buffer inferior-octave-buffer)))
1408 (defun octave-show-process-buffer ()
1409 "Make sure that `inferior-octave-buffer' is displayed."
1411 (if (get-buffer inferior-octave-buffer)
1412 (display-buffer inferior-octave-buffer)
1413 (message "No buffer named %s" inferior-octave-buffer)))
1415 (defun octave-hide-process-buffer ()
1416 "Delete all windows that display `inferior-octave-buffer'."
1418 (if (get-buffer inferior-octave-buffer)
1419 (delete-windows-on inferior-octave-buffer)
1420 (message "No buffer named %s" inferior-octave-buffer)))
1422 (defun octave-send-region (beg end)
1423 "Send current region to the inferior Octave process."
1426 (let ((proc inferior-octave-process)
1427 (string (buffer-substring-no-properties beg end))
1429 (with-current-buffer inferior-octave-buffer
1430 (setq inferior-octave-output-list nil)
1431 (while (not (string-equal string ""))
1432 (if (string-match "\n" string)
1433 (setq line (substring string 0 (match-beginning 0))
1434 string (substring string (match-end 0)))
1435 (setq line string string ""))
1436 (setq inferior-octave-receive-in-progress t)
1437 (inferior-octave-send-list-and-digest (list (concat line "\n")))
1438 (while inferior-octave-receive-in-progress
1439 (accept-process-output proc))
1440 (insert-before-markers
1441 (mapconcat 'identity
1443 (if octave-send-echo-input (list line) (list ""))
1444 inferior-octave-output-list
1445 (list inferior-octave-output-string))
1447 (if octave-send-show-buffer
1448 (display-buffer inferior-octave-buffer)))
1450 (defun octave-send-block ()
1451 "Send current Octave block to the inferior Octave process."
1455 (octave-send-region (point) (mark))))
1457 (defun octave-send-defun ()
1458 "Send current Octave function to the inferior Octave process."
1462 (octave-send-region (point) (mark))))
1464 (defun octave-send-line (&optional arg)
1465 "Send current Octave code line to the inferior Octave process.
1466 With positive prefix ARG, send that many lines.
1467 If `octave-send-line-auto-forward' is non-nil, go to the next unsent
1470 (or arg (setq arg 1))
1475 (octave-next-code-line (- arg 1))
1478 (if octave-send-line-auto-forward
1479 (octave-next-code-line 1))
1480 (octave-send-region beg end))))
1482 (defun octave-eval-print-last-sexp ()
1483 "Evaluate Octave sexp before point and print value into current buffer."
1486 (let ((standard-output (current-buffer))
1487 (print-escape-newlines nil)
1493 (inferior-octave-send-list-and-digest
1494 (list (concat (buffer-substring-no-properties (point) opoint)
1496 (mapconcat 'identity inferior-octave-output-list "\n")))
1501 (defcustom octave-eldoc-message-style 'auto
1502 "Octave eldoc message style: auto, oneline, multiline."
1503 :type '(choice (const :tag "Automatic" auto)
1504 (const :tag "One Line" oneline)
1505 (const :tag "Multi Line" multiline))
1509 ;; (FN SIGNATURE1 SIGNATURE2 ...)
1510 (defvar octave-eldoc-cache nil)
1512 (defun octave-eldoc-function-signatures (fn)
1513 (unless (equal fn (car octave-eldoc-cache))
1514 (inferior-octave-send-list-and-digest
1516 if ismember(exist(\"%s\"), [2 3 5 103]) print_usage(\"%s\") endif\n"
1519 (dolist (line inferior-octave-output-list)
1521 "\\s-*\\(?:--[^:]+\\|usage\\):\\s-*\\(.*\\)$"
1523 (push (match-string 1 line) result)))
1524 (setq octave-eldoc-cache
1525 (cons (substring-no-properties fn)
1526 (nreverse result)))))
1527 (cdr octave-eldoc-cache))
1529 (defun octave-eldoc-function ()
1530 "A function for `eldoc-documentation-function' (which see)."
1531 (when (and inferior-octave-process
1532 (process-live-p inferior-octave-process))
1533 (let* ((ppss (syntax-ppss))
1534 (paren-pos (cadr ppss))
1537 ;; PAREN-POS must be after the prompt
1539 (if (eq (get-buffer-process (current-buffer))
1540 inferior-octave-process)
1541 (process-mark inferior-octave-process)
1543 (or (not (eq (get-buffer-process (current-buffer))
1544 inferior-octave-process))
1545 (< (process-mark inferior-octave-process)
1547 (eq (char-after paren-pos) ?\())
1548 (goto-char paren-pos)
1549 (setq paren-pos nil))
1550 (when (or (< (skip-syntax-backward "-") 0) paren-pos)
1551 (thing-at-point 'symbol))))
1552 (sigs (and fn (octave-eldoc-function-signatures fn)))
1553 (oneline (mapconcat 'identity sigs
1554 (propertize " | " 'face 'warning)))
1555 (multiline (mapconcat (lambda (s) (concat "-- " s)) sigs "\n")))
1557 ;; Return the value according to style.
1558 (pcase octave-eldoc-message-style
1559 (`auto (if (< (length oneline) (window-width (minibuffer-window)))
1563 (`multiline multiline)))))
1565 (defcustom octave-help-buffer "*Octave Help*"
1566 "Buffer name for `octave-help'."
1571 (define-button-type 'octave-help-file
1573 'action #'help-button-action
1574 'help-function 'octave-find-definition)
1576 (define-button-type 'octave-help-function
1580 (buffer-substring (button-start b) (button-end b)))))
1582 (defvar help-xref-following)
1584 (defun octave-help (fn)
1585 "Display the documentation of FN."
1586 (interactive (list (octave-completing-read)))
1587 (inferior-octave-send-list-and-digest
1588 (list (format "help \"%s\"\n" fn)))
1589 (let ((lines inferior-octave-output-list))
1590 (when (string-match "error: \\(.*\\)$" (car lines))
1591 (error "%s" (match-string 1 (car lines))))
1592 (with-help-window octave-help-buffer
1593 (princ (mapconcat 'identity lines "\n"))
1594 (with-current-buffer octave-help-buffer
1595 ;; Bound to t so that `help-buffer' returns current buffer for
1596 ;; `help-setup-xref'.
1597 (let ((help-xref-following t))
1598 (help-setup-xref (list 'octave-help fn)
1599 (called-interactively-p 'interactive)))
1600 (setq-local info-lookup-mode 'octave-mode)
1601 ;; Note: can be turned off by suppress_verbose_help_message.
1603 ;; Remove boring trailing text: Additional help for built-in functions
1604 ;; and operators ...
1605 (goto-char (point-max))
1606 (when (search-backward "\n\n\n" nil t)
1607 (goto-char (match-beginning 0))
1608 (delete-region (point) (point-max)))
1609 ;; File name highlight
1610 (goto-char (point-min))
1611 (when (re-search-forward "from the file \\(.*\\)$"
1614 (let ((file (match-string 1)))
1615 (replace-match "" nil nil nil 1)
1617 (help-insert-xref-button (file-name-nondirectory file)
1618 'octave-help-file fn)
1620 ;; Make 'See also' clickable
1621 (with-syntax-table octave-mode-syntax-table
1622 (when (re-search-forward "^\\s-*See also:" nil t)
1623 (while (re-search-forward "\\_<\\(?:\\sw\\|\\s_\\)+\\_>" nil t)
1624 (make-text-button (match-beginning 0)
1626 :type 'octave-help-function))))))))
1628 (defcustom octave-source-directories nil
1629 "A list of directories for Octave sources."
1630 :type '(repeat directory)
1634 (defun octave-source-directories ()
1635 (inferior-octave-check-process)
1636 (let ((srcdir (process-get inferior-octave-process 'octave-srcdir)))
1638 (cons srcdir octave-source-directories)
1639 octave-source-directories)))
1641 (defvar octave-find-definition-filename-function
1642 #'octave-find-definition-default-filename)
1644 (defun octave-find-definition-default-filename (name)
1645 "Default value for `octave-find-definition-filename-function'."
1646 (pcase (file-name-extension name)
1648 (octave-find-definition-default-filename
1649 (concat "libinterp/dldfcn/"
1650 (file-name-sans-extension (file-name-nondirectory name))
1653 (let ((file (or (locate-file name (octave-source-directories))
1654 (locate-file (file-name-nondirectory name)
1655 (octave-source-directories)))))
1656 (or (and file (file-exists-p file))
1657 (error "File `%s' not found" name))
1660 (if (yes-or-no-p (format "File `%s' may be binary; open? "
1661 (file-name-nondirectory name)))
1663 (user-error "Aborted")))
1666 (defvar find-tag-marker-ring)
1668 (defun octave-find-definition (fn)
1669 "Find the definition of FN.
1670 Definitions for functions implemented in C++ can be found if
1671 `octave-source-directories' is set correctly."
1672 (interactive (list (octave-completing-read)))
1673 (inferior-octave-send-list-and-digest
1674 ;; help NAME is more verbose
1676 if iskeyword(\"%s\") disp(\"`%s' is a keyword\") else which(\"%s\") endif\n"
1678 (let* ((line (car inferior-octave-output-list))
1679 (file (when (and line (string-match "from the file \\(.*\\)$" line))
1680 (match-string 1 line))))
1682 (user-error "%s" (or line (format "`%s' not found" fn)))
1684 (ring-insert find-tag-marker-ring (point-marker))
1685 (setq file (funcall octave-find-definition-filename-function file))
1688 (octave-goto-function-definition fn)))))
1692 ;;; octave.el ends here