* lisp/progmodes/octave.el (octave-mode-map): Add key binding for
[emacs.git] / lisp / progmodes / octave.el
bloba5e59b744a6836b191851f62f324e655d20079b0
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>
7 ;; Maintainer: FSF
8 ;; Keywords: languages
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;; Commentary:
27 ;; This package provides emacs support for Octave. 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.
34 ;;; Code:
35 (require 'comint)
37 ;;; For emacs < 24.3.
38 (require 'newcomment)
39 (eval-and-compile
40 (unless (fboundp 'user-error)
41 (defalias 'user-error 'error))
42 (unless (fboundp 'delete-consecutive-dups)
43 (defalias 'delete-consecutive-dups 'delete-dups)))
44 (eval-when-compile
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))))
50 (defgroup octave nil
51 "Editing Octave code."
52 :link '(custom-group-link :tag "Font Lock Faces group" font-lock-faces)
53 :group 'languages)
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
85 octave-else-keywords
86 octave-end-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-f" 'octave-insert-defun)
114 (define-key map "\C-c\C-il" 'octave-send-line)
115 (define-key map "\C-c\C-ib" 'octave-send-block)
116 (define-key map "\C-c\C-if" 'octave-send-defun)
117 (define-key map "\C-c\C-ir" 'octave-send-region)
118 (define-key map "\C-c\C-is" 'octave-show-process-buffer)
119 (define-key map "\C-c\C-iq" 'octave-hide-process-buffer)
120 (define-key map "\C-c\C-ik" 'octave-kill-process)
121 (define-key map "\C-c\C-i\C-l" 'octave-send-line)
122 (define-key map "\C-c\C-i\C-b" 'octave-send-block)
123 (define-key map "\C-c\C-i\C-f" 'octave-send-defun)
124 (define-key map "\C-c\C-i\C-r" 'octave-send-region)
125 (define-key map "\C-c\C-i\C-s" 'octave-show-process-buffer)
126 (define-key map "\C-c\C-i\C-q" 'octave-hide-process-buffer)
127 (define-key map "\C-c\C-i\C-k" 'octave-kill-process)
128 map)
129 "Keymap used in Octave mode.")
133 (easy-menu-define octave-mode-menu octave-mode-map
134 "Menu for Octave mode."
135 '("Octave"
136 ["Split Line at Point" octave-indent-new-comment-line t]
137 ["Previous Code Line" octave-previous-code-line t]
138 ["Next Code Line" octave-next-code-line t]
139 ["Begin of Line" octave-beginning-of-line t]
140 ["End of Line" octave-end-of-line t]
141 ["Mark Block" octave-mark-block t]
142 ["Close Block" smie-close-block t]
143 "---"
144 ["Start Octave Process" run-octave t]
145 ["Documentation Lookup" info-lookup-symbol t]
146 ["Help on Function" octave-help t]
147 ["Search help" octave-lookfor t]
148 ["Find Function Definition" octave-find-definition t]
149 ["Insert Function" octave-insert-defun t]
150 ["Update Function File Comment" octave-update-function-file-comment t]
151 "---"
152 ["Function Syntax Hints" (call-interactively
153 (if (fboundp 'eldoc-post-insert-mode)
154 'eldoc-post-insert-mode
155 'eldoc-mode))
156 :style toggle :selected (or eldoc-post-insert-mode eldoc-mode)
157 :help "Display function signatures after typing `SPC' or `('"]
158 ["Delimiter Matching" show-paren-mode
159 :style toggle :selected show-paren-mode
160 :help "Highlight matched pairs such as `if ... end'"
161 :visible (fboundp 'smie--matching-block-data)]
162 ["Auto Fill" auto-fill-mode
163 :style toggle :selected auto-fill-function
164 :help "Automatic line breaking"]
165 ["Electric Layout" electric-layout-mode
166 :style toggle :selected electric-layout-mode
167 :help "Automatically insert newlines around some chars"]
168 "---"
169 ("Debug"
170 ["Send Current Line" octave-send-line t]
171 ["Send Current Block" octave-send-block t]
172 ["Send Current Function" octave-send-defun t]
173 ["Send Region" octave-send-region t]
174 ["Show Process Buffer" octave-show-process-buffer t]
175 ["Hide Process Buffer" octave-hide-process-buffer t]
176 ["Kill Process" octave-kill-process t])
177 "---"
178 ["Customize Octave" (customize-group 'octave) t]
179 ["Submit Bug Report" report-emacs-bug t]))
181 (defvar octave-mode-syntax-table
182 (let ((table (make-syntax-table)))
183 (modify-syntax-entry ?\r " " table)
184 (modify-syntax-entry ?+ "." table)
185 (modify-syntax-entry ?- "." table)
186 (modify-syntax-entry ?= "." table)
187 (modify-syntax-entry ?* "." table)
188 (modify-syntax-entry ?/ "." 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 ;; The "b" flag only applies to the second letter of the comstart
201 ;; and the first letter of the comend, i.e. the "4b" below is ineffective.
202 ;; If we try to put `b' on the single-line comments, we get a similar
203 ;; problem where the % and # chars appear as first chars of the 2-char
204 ;; comend, so the multi-line ender is also turned into style-b.
205 ;; So we need the new "c" comment style.
206 (modify-syntax-entry ?\% "< 13" table)
207 (modify-syntax-entry ?\# "< 13" table)
208 (modify-syntax-entry ?\{ "(} 2c" table)
209 (modify-syntax-entry ?\} "){ 4c" table)
210 (modify-syntax-entry ?\n ">" table)
211 table)
212 "Syntax table in use in `octave-mode' buffers.")
214 (defcustom octave-font-lock-texinfo-comment t
215 "Control whether to highlight the texinfo comment block."
216 :type 'boolean
217 :group 'octave
218 :version "24.4")
220 (defcustom octave-blink-matching-block t
221 "Control the blinking of matching Octave block keywords.
222 Non-nil means show matching begin of block when inserting a space,
223 newline or semicolon after an else or end keyword."
224 :type 'boolean
225 :group 'octave)
227 (defcustom octave-block-offset 2
228 "Extra indentation applied to statements in Octave block structures."
229 :type 'integer
230 :group 'octave)
232 (defvar octave-block-comment-start
233 (concat (make-string 2 octave-comment-char) " ")
234 "String to insert to start a new Octave comment on an empty line.")
236 (defcustom octave-continuation-offset 4
237 "Extra indentation applied to Octave continuation lines."
238 :type 'integer
239 :group 'octave)
241 (eval-and-compile
242 (defconst octave-continuation-marker-regexp "\\\\\\|\\.\\.\\."))
244 (defvar octave-continuation-regexp
245 (concat "[^#%\n]*\\(" octave-continuation-marker-regexp
246 "\\)\\s-*\\(\\s<.*\\)?$"))
248 ;; Char \ is considered a bad decision for continuing a line.
249 (defconst octave-continuation-string "..."
250 "Character string used for Octave continuation lines.")
252 (defvar octave-mode-imenu-generic-expression
253 (list
254 ;; Functions
255 (list nil octave-function-header-regexp 3))
256 "Imenu expression for Octave mode. See `imenu-generic-expression'.")
258 (defcustom octave-mode-hook nil
259 "Hook to be run when Octave mode is started."
260 :type 'hook
261 :group 'octave)
263 (defcustom octave-send-show-buffer t
264 "Non-nil means display `inferior-octave-buffer' after sending to it."
265 :type 'boolean
266 :group 'octave)
268 (defcustom octave-send-line-auto-forward t
269 "Control auto-forward after sending to the inferior Octave process.
270 Non-nil means always go to the next Octave code line after sending."
271 :type 'boolean
272 :group 'octave)
274 (defcustom octave-send-echo-input t
275 "Non-nil means echo input sent to the inferior Octave process."
276 :type 'boolean
277 :group 'octave)
280 ;;; SMIE indentation
282 (require 'smie)
284 ;; Use '__operators__' in Octave REPL to get a full list.
285 (defconst octave-operator-table
286 '((assoc ";" "\n") (assoc ",") ; The doc claims they have equal precedence!?
287 (right "=" "+=" "-=" "*=" "/=")
288 (assoc "&&") (assoc "||") ; The doc claims they have equal precedence!?
289 (assoc "&") (assoc "|") ; The doc claims they have equal precedence!?
290 (nonassoc "<" "<=" "==" ">=" ">" "!=" "~=")
291 (nonassoc ":") ;No idea what this is.
292 (assoc "+" "-")
293 (assoc "*" "/" "\\" ".\\" ".*" "./")
294 (nonassoc "'" ".'")
295 (nonassoc "++" "--" "!" "~") ;And unary "+" and "-".
296 (right "^" "**" ".^" ".**")
297 ;; It's not really an operator, but for indentation purposes it
298 ;; could be convenient to treat it as one.
299 (assoc "...")))
301 (defconst octave-smie-bnf-table
302 '((atom)
303 ;; We can't distinguish the first element in a sequence with
304 ;; precedence grammars, so we can't distinguish the condition
305 ;; if the `if' from the subsequent body, for example.
306 ;; This has to be done later in the indentation rules.
307 (exp (exp "\n" exp)
308 ;; We need to mention at least one of the operators in this part
309 ;; of the grammar: if the BNF and the operator table have
310 ;; no overlap, SMIE can't know how they relate.
311 (exp ";" exp)
312 ("try" exp "catch" exp "end_try_catch")
313 ("try" exp "catch" exp "end")
314 ("unwind_protect" exp
315 "unwind_protect_cleanup" exp "end_unwind_protect")
316 ("unwind_protect" exp "unwind_protect_cleanup" exp "end")
317 ("for" exp "endfor")
318 ("for" exp "end")
319 ("parfor" exp "endparfor")
320 ("parfor" exp "end")
321 ("do" exp "until" atom)
322 ("while" exp "endwhile")
323 ("while" exp "end")
324 ("if" exp "endif")
325 ("if" exp "else" exp "endif")
326 ("if" exp "elseif" exp "else" exp "endif")
327 ("if" exp "elseif" exp "elseif" exp "else" exp "endif")
328 ("if" exp "elseif" exp "elseif" exp "else" exp "end")
329 ("switch" exp "case" exp "endswitch")
330 ("switch" exp "case" exp "otherwise" exp "endswitch")
331 ("switch" exp "case" exp "case" exp "otherwise" exp "endswitch")
332 ("switch" exp "case" exp "case" exp "otherwise" exp "end")
333 ("function" exp "endfunction")
334 ("function" exp "end")
335 ("enumeration" exp "endenumeration")
336 ("enumeration" exp "end")
337 ("events" exp "endevents")
338 ("events" exp "end")
339 ("methods" exp "endmethods")
340 ("methods" exp "end")
341 ("properties" exp "endproperties")
342 ("properties" exp "end")
343 ("classdef" exp "endclassdef")
344 ("classdef" exp "end"))
345 ;; (fundesc (atom "=" atom))
348 (defconst octave-smie-grammar
349 (smie-prec2->grammar
350 (smie-merge-prec2s
351 (smie-bnf->prec2 octave-smie-bnf-table
352 '((assoc "\n" ";")))
354 (smie-precs->prec2 octave-operator-table))))
356 ;; Tokenizing needs to be refined so that ";;" is treated as two
357 ;; tokens and also so as to recognize the \n separator (and
358 ;; corresponding continuation lines).
360 (defconst octave-operator-regexp
361 (regexp-opt (apply 'append (mapcar 'cdr octave-operator-table))))
363 (defun octave-smie-backward-token ()
364 (let ((pos (point)))
365 (forward-comment (- (point)))
366 (cond
367 ((and (not (eq (char-before) ?\;)) ;Coalesce ";" and "\n".
368 (> pos (line-end-position))
369 (if (looking-back octave-continuation-marker-regexp (- (point) 3))
370 (progn
371 (goto-char (match-beginning 0))
372 (forward-comment (- (point)))
373 nil)
375 ;; Ignore it if it's within parentheses.
376 (let ((ppss (syntax-ppss)))
377 (not (and (nth 1 ppss)
378 (eq ?\( (char-after (nth 1 ppss)))))))
379 (skip-chars-forward " \t")
380 ;; Why bother distinguishing \n and ;?
381 ";") ;;"\n"
382 ((and (looking-back octave-operator-regexp (- (point) 3) 'greedy)
383 ;; Don't mistake a string quote for a transpose.
384 (not (looking-back "\\s\"" (1- (point)))))
385 (goto-char (match-beginning 0))
386 (match-string-no-properties 0))
388 (smie-default-backward-token)))))
390 (defun octave-smie-forward-token ()
391 (skip-chars-forward " \t")
392 (when (looking-at (eval-when-compile
393 (concat "\\(" octave-continuation-marker-regexp
394 "\\)[ \t]*\\($\\|[%#]\\)")))
395 (goto-char (match-end 1))
396 (forward-comment 1))
397 (cond
398 ((and (looking-at "[%#\n]")
399 (not (or (save-excursion (skip-chars-backward " \t")
400 ;; Only add implicit ; when needed.
401 (or (bolp) (eq (char-before) ?\;)))
402 ;; Ignore it if it's within parentheses.
403 (let ((ppss (syntax-ppss)))
404 (and (nth 1 ppss)
405 (eq ?\( (char-after (nth 1 ppss))))))))
406 (if (eolp) (forward-char 1) (forward-comment 1))
407 ;; Why bother distinguishing \n and ;?
408 ";") ;;"\n"
409 ((progn (forward-comment (point-max)) nil))
410 ((looking-at ";[ \t]*\\($\\|[%#]\\)")
411 ;; Combine the ; with the subsequent \n.
412 (goto-char (match-beginning 1))
413 (forward-comment 1)
414 ";")
415 ((and (looking-at octave-operator-regexp)
416 ;; Don't mistake a string quote for a transpose.
417 (not (looking-at "\\s\"")))
418 (goto-char (match-end 0))
419 (match-string-no-properties 0))
421 (smie-default-forward-token))))
423 (defun octave-smie-rules (kind token)
424 (pcase (cons kind token)
425 ;; We could set smie-indent-basic instead, but that would have two
426 ;; disadvantages:
427 ;; - changes to octave-block-offset wouldn't take effect immediately.
428 ;; - edebug wouldn't show the use of this variable.
429 (`(:elem . basic) octave-block-offset)
430 ;; Since "case" is in the same BNF rules as switch..end, SMIE by default
431 ;; aligns it with "switch".
432 (`(:before . "case") (if (not (smie-rule-sibling-p)) octave-block-offset))
433 (`(:after . ";")
434 (if (smie-rule-parent-p "classdef" "events" "enumeration" "function" "if"
435 "while" "else" "elseif" "for" "parfor"
436 "properties" "methods" "otherwise" "case"
437 "try" "catch" "unwind_protect"
438 "unwind_protect_cleanup")
439 (smie-rule-parent octave-block-offset)
440 ;; For (invalid) code between switch and case.
441 ;; (if (smie-parent-p "switch") 4)
442 nil))))
444 (defun octave-indent-comment ()
445 "A function for `smie-indent-functions' (which see)."
446 (save-excursion
447 (back-to-indentation)
448 (cond
449 ((octave-in-string-or-comment-p) nil)
450 ((looking-at-p "\\(\\s<\\)\\1\\{2,\\}")
452 ;; Exclude %{, %} and %!.
453 ((and (looking-at-p "\\s<\\(?:[^{}!]\\|$\\)")
454 (not (looking-at-p "\\(\\s<\\)\\1")))
455 (comment-choose-indent)))))
458 (defvar octave-font-lock-keywords
459 (list
460 ;; Fontify all builtin keywords.
461 (cons (concat "\\_<\\("
462 (regexp-opt octave-reserved-words)
463 "\\)\\_>")
464 'font-lock-keyword-face)
465 ;; Note: 'end' also serves as the last index in an indexing expression.
466 ;; Ref: http://www.mathworks.com/help/matlab/ref/end.html
467 (list (lambda (limit)
468 (while (re-search-forward "\\_<end\\_>" limit 'move)
469 (let ((beg (match-beginning 0))
470 (end (match-end 0)))
471 (unless (octave-in-string-or-comment-p)
472 (condition-case nil
473 (progn
474 (goto-char beg)
475 (backward-up-list)
476 (when (memq (char-after) '(?\( ?\[ ?\{))
477 (put-text-property beg end 'face nil))
478 (goto-char end))
479 (error (goto-char end))))))
480 nil))
481 ;; Fontify all operators.
482 (cons octave-operator-regexp 'font-lock-builtin-face)
483 ;; Fontify all function declarations.
484 (list octave-function-header-regexp
485 '(1 font-lock-keyword-face)
486 '(3 font-lock-function-name-face nil t)))
487 "Additional Octave expressions to highlight.")
489 (defun octave-syntax-propertize-function (start end)
490 (goto-char start)
491 (octave-syntax-propertize-sqs end)
492 (funcall (syntax-propertize-rules
493 ("\\\\" (0 (when (eq (nth 3 (save-excursion
494 (syntax-ppss (match-beginning 0))))
495 ?\")
496 (string-to-syntax "\\"))))
497 ;; Try to distinguish the string-quotes from the transpose-quotes.
498 ("\\(?:^\\|[[({,; ]\\)\\('\\)"
499 (1 (prog1 "\"'" (octave-syntax-propertize-sqs end)))))
500 (point) end))
502 (defun octave-syntax-propertize-sqs (end)
503 "Propertize the content/end of single-quote strings."
504 (when (eq (nth 3 (syntax-ppss)) ?\')
505 ;; A '..' string.
506 (when (re-search-forward
507 "\\(?:\\=\\|[^']\\)\\(?:''\\)*\\('\\)\\($\\|[^']\\)" end 'move)
508 (goto-char (match-beginning 2))
509 (when (eq (char-before (match-beginning 1)) ?\\)
510 ;; Backslash cannot escape a single quote.
511 (put-text-property (1- (match-beginning 1)) (match-beginning 1)
512 'syntax-table (string-to-syntax ".")))
513 (put-text-property (match-beginning 1) (match-end 1)
514 'syntax-table (string-to-syntax "\"'")))))
516 (defvar electric-layout-rules)
518 ;;;###autoload
519 (define-derived-mode octave-mode prog-mode "Octave"
520 "Major mode for editing Octave code.
522 Octave is a high-level language, primarily intended for numerical
523 computations. It provides a convenient command line interface
524 for solving linear and nonlinear problems numerically. Function
525 definitions can also be stored in files and used in batch mode."
526 :abbrev-table octave-abbrev-table
528 (smie-setup octave-smie-grammar #'octave-smie-rules
529 :forward-token #'octave-smie-forward-token
530 :backward-token #'octave-smie-backward-token)
531 (setq-local smie-indent-basic 'octave-block-offset)
532 (add-hook 'smie-indent-functions #'octave-indent-comment nil t)
534 (setq-local smie-blink-matching-triggers
535 (cons ?\; smie-blink-matching-triggers))
536 (unless octave-blink-matching-block
537 (remove-hook 'post-self-insert-hook #'smie-blink-matching-open 'local))
539 (setq-local electric-indent-chars
540 (cons ?\; electric-indent-chars))
541 ;; IIUC matlab-mode takes the opposite approach: it makes RET insert
542 ;; a ";" at those places where it's correct (i.e. outside of parens).
543 (setq-local electric-layout-rules '((?\; . after)))
545 (setq-local comment-use-global-state t)
546 (setq-local comment-start octave-comment-start)
547 (setq-local comment-end "")
548 (setq-local comment-start-skip octave-comment-start-skip)
549 (setq-local comment-add 1)
551 (setq-local parse-sexp-ignore-comments t)
552 (setq-local paragraph-start (concat "\\s-*$\\|" page-delimiter))
553 (setq-local paragraph-separate paragraph-start)
554 (setq-local paragraph-ignore-fill-prefix t)
555 (setq-local fill-paragraph-function 'octave-fill-paragraph)
557 (setq-local fill-nobreak-predicate
558 (lambda () (eq (octave-in-string-p) ?')))
559 (with-no-warnings
560 (if (fboundp 'add-function) ; new in 24.4
561 (add-function :around (local 'comment-line-break-function)
562 #'octave--indent-new-comment-line)
563 (setq-local comment-line-break-function
564 (apply-partially #'octave--indent-new-comment-line
565 #'comment-indent-new-line))))
567 (setq font-lock-defaults '(octave-font-lock-keywords))
569 (setq-local syntax-propertize-function #'octave-syntax-propertize-function)
571 (setq-local imenu-generic-expression octave-mode-imenu-generic-expression)
572 (setq-local imenu-case-fold-search nil)
574 (setq-local add-log-current-defun-function #'octave-add-log-current-defun)
576 (add-hook 'completion-at-point-functions 'octave-completion-at-point nil t)
577 (add-hook 'before-save-hook 'octave-sync-function-file-names nil t)
578 (setq-local beginning-of-defun-function 'octave-beginning-of-defun)
579 (and octave-font-lock-texinfo-comment (octave-font-lock-texinfo-comment))
580 (setq-local eldoc-documentation-function 'octave-eldoc-function)
582 (easy-menu-add octave-mode-menu))
585 (defcustom inferior-octave-program "octave"
586 "Program invoked by `inferior-octave'."
587 :type 'string
588 :group 'octave)
590 (defcustom inferior-octave-buffer "*Inferior Octave*"
591 "Name of buffer for running an inferior Octave process."
592 :type 'string
593 :group 'octave)
595 (defcustom inferior-octave-prompt
596 "\\(^octave\\(\\|.bin\\|.exe\\)\\(-[.0-9]+\\)?\\(:[0-9]+\\)?\\|^debug\\|^\\)>+ "
597 "Regexp to match prompts for the inferior Octave process."
598 :type 'regexp
599 :group 'octave)
601 (defcustom inferior-octave-prompt-read-only comint-prompt-read-only
602 "If non-nil, the Octave prompt is read only.
603 See `comint-prompt-read-only' for details."
604 :type 'boolean
605 :group 'octave
606 :version "24.4")
608 (defcustom inferior-octave-startup-file
609 (convert-standard-filename
610 (concat "~/.emacs-" (file-name-nondirectory inferior-octave-program)))
611 "Name of the inferior Octave startup file.
612 The contents of this file are sent to the inferior Octave process on
613 startup."
614 :type '(choice (const :tag "None" nil) file)
615 :group 'octave
616 :version "24.4")
618 (defcustom inferior-octave-startup-args '("-i" "--no-line-editing")
619 "List of command line arguments for the inferior Octave process.
620 For example, for suppressing the startup message and using `traditional'
621 mode, include \"-q\" and \"--traditional\"."
622 :type '(repeat string)
623 :group 'octave
624 :version "24.4")
626 (defcustom inferior-octave-mode-hook nil
627 "Hook to be run when Inferior Octave mode is started."
628 :type 'hook
629 :group 'octave)
631 (defvar inferior-octave-process nil)
633 (defvar inferior-octave-mode-map
634 (let ((map (make-sparse-keymap)))
635 (set-keymap-parent map comint-mode-map)
636 (define-key map "\M-." 'octave-find-definition)
637 (define-key map "\t" 'completion-at-point)
638 (define-key map "\C-hd" 'octave-help)
639 (define-key map "\C-ha" 'octave-lookfor)
640 ;; Same as in `shell-mode'.
641 (define-key map "\M-?" 'comint-dynamic-list-filename-completions)
642 (define-key map "\C-c\C-l" 'inferior-octave-dynamic-list-input-ring)
643 (define-key map [menu-bar inout list-history]
644 '("List Input History" . inferior-octave-dynamic-list-input-ring))
645 map)
646 "Keymap used in Inferior Octave mode.")
648 (defvar inferior-octave-mode-syntax-table
649 (let ((table (make-syntax-table octave-mode-syntax-table)))
650 table)
651 "Syntax table in use in inferior-octave-mode buffers.")
653 (defvar inferior-octave-font-lock-keywords
654 (list
655 (cons inferior-octave-prompt 'font-lock-type-face))
656 ;; Could certainly do more font locking in inferior Octave ...
657 "Additional expressions to highlight in Inferior Octave mode.")
659 (defvar inferior-octave-output-list nil)
660 (defvar inferior-octave-output-string nil)
661 (defvar inferior-octave-receive-in-progress nil)
663 (define-obsolete-variable-alias 'inferior-octave-startup-hook
664 'inferior-octave-mode-hook "24.4")
666 (defvar inferior-octave-dynamic-complete-functions
667 '(inferior-octave-completion-at-point comint-filename-completion)
668 "List of functions called to perform completion for inferior Octave.
669 This variable is used to initialize `comint-dynamic-complete-functions'
670 in the Inferior Octave buffer.")
672 (defvar info-lookup-mode)
674 (define-derived-mode inferior-octave-mode comint-mode "Inferior Octave"
675 "Major mode for interacting with an inferior Octave process."
676 :abbrev-table octave-abbrev-table
677 (setq comint-prompt-regexp inferior-octave-prompt)
679 (setq-local comment-use-global-state t)
680 (setq-local comment-start octave-comment-start)
681 (setq-local comment-end "")
682 (setq comment-column 32)
683 (setq-local comment-start-skip octave-comment-start-skip)
685 (setq font-lock-defaults '(inferior-octave-font-lock-keywords nil nil))
687 (setq-local info-lookup-mode 'octave-mode)
688 (setq-local eldoc-documentation-function 'octave-eldoc-function)
690 (setq comint-input-ring-file-name
691 (or (getenv "OCTAVE_HISTFILE") "~/.octave_hist")
692 comint-input-ring-size (or (getenv "OCTAVE_HISTSIZE") 1024))
693 (setq-local comint-dynamic-complete-functions
694 inferior-octave-dynamic-complete-functions)
695 (setq-local comint-prompt-read-only inferior-octave-prompt-read-only)
696 (add-hook 'comint-input-filter-functions
697 'inferior-octave-directory-tracker nil t)
698 ;; http://thread.gmane.org/gmane.comp.gnu.octave.general/48572
699 (add-hook 'window-configuration-change-hook
700 'inferior-octave-track-window-width-change nil t)
701 (comint-read-input-ring t))
703 ;;;###autoload
704 (defun inferior-octave (&optional arg)
705 "Run an inferior Octave process, I/O via `inferior-octave-buffer'.
706 This buffer is put in Inferior Octave mode. See `inferior-octave-mode'.
708 Unless ARG is non-nil, switches to this buffer.
710 The elements of the list `inferior-octave-startup-args' are sent as
711 command line arguments to the inferior Octave process on startup.
713 Additional commands to be executed on startup can be provided either in
714 the file specified by `inferior-octave-startup-file' or by the default
715 startup file, `~/.emacs-octave'."
716 (interactive "P")
717 (let ((buffer (get-buffer-create inferior-octave-buffer)))
718 (unless arg
719 (pop-to-buffer buffer))
720 (unless (comint-check-proc buffer)
721 (with-current-buffer buffer
722 (inferior-octave-startup)
723 (inferior-octave-mode)))
724 buffer))
726 ;;;###autoload
727 (defalias 'run-octave 'inferior-octave)
729 (defun inferior-octave-startup ()
730 "Start an inferior Octave process."
731 (let ((proc (comint-exec-1
732 (substring inferior-octave-buffer 1 -1)
733 inferior-octave-buffer
734 inferior-octave-program
735 (append
736 inferior-octave-startup-args
737 ;; --no-gui is introduced in Octave > 3.7
738 (and (not (member "--no-gui" inferior-octave-startup-args))
739 (zerop (process-file inferior-octave-program
740 nil nil nil "--no-gui" "--help"))
741 '("--no-gui"))))))
742 (set-process-filter proc 'inferior-octave-output-digest)
743 (setq inferior-octave-process proc
744 inferior-octave-output-list nil
745 inferior-octave-output-string nil
746 inferior-octave-receive-in-progress t)
748 ;; This may look complicated ... However, we need to make sure that
749 ;; we additional startup code only AFTER Octave is ready (otherwise,
750 ;; output may be mixed up). Hence, we need to digest the Octave
751 ;; output to see when it issues a prompt.
752 (while inferior-octave-receive-in-progress
753 (or (process-live-p inferior-octave-process)
754 (error "Process `%s' died" inferior-octave-process))
755 (accept-process-output inferior-octave-process))
756 (goto-char (point-max))
757 (set-marker (process-mark proc) (point))
758 (insert-before-markers
759 (concat
760 (if (not (bobp)) "\f\n")
761 (if inferior-octave-output-list
762 (concat (mapconcat
763 'identity inferior-octave-output-list "\n")
764 "\n"))))
766 ;; An empty secondary prompt, as e.g. obtained by '--braindead',
767 ;; means trouble.
768 (inferior-octave-send-list-and-digest (list "PS2\n"))
769 (when (string-match "\\(PS2\\|ans\\) = *$"
770 (car inferior-octave-output-list))
771 (inferior-octave-send-list-and-digest (list "PS2 ('> ');\n")))
773 (inferior-octave-send-list-and-digest
774 (list "disp (getenv ('OCTAVE_SRCDIR'))\n"))
775 (process-put proc 'octave-srcdir
776 (unless (equal (car inferior-octave-output-list) "")
777 (car inferior-octave-output-list)))
779 ;; O.K., now we are ready for the Inferior Octave startup commands.
780 (inferior-octave-send-list-and-digest
781 (list "more off;\n"
782 (unless (equal inferior-octave-output-string ">> ")
783 "PS1 ('\\s> ');\n")
784 (when (and inferior-octave-startup-file
785 (file-exists-p inferior-octave-startup-file))
786 (format "source ('%s');\n" inferior-octave-startup-file))))
787 (when inferior-octave-output-list
788 (insert-before-markers
789 (mapconcat 'identity inferior-octave-output-list "\n")))
791 ;; And finally, everything is back to normal.
792 (set-process-filter proc 'comint-output-filter)
793 ;; Just in case, to be sure a cd in the startup file won't have
794 ;; detrimental effects.
795 (with-demoted-errors (inferior-octave-resync-dirs))
796 ;; Generate a proper prompt, which is critical to
797 ;; `comint-history-isearch-backward-regexp'. Bug#14433.
798 (comint-send-string proc "\n")))
800 (defvar inferior-octave-completion-table
802 ;; Use cache to avoid repetitive computation of completions due to
803 ;; bug#11906 - http://debbugs.gnu.org/11906 - which may cause
804 ;; noticeable delay. CACHE: (CMD TIME VALUE).
805 (let ((cache))
806 (completion-table-dynamic
807 (lambda (command)
808 (unless (and (equal (car cache) command)
809 (< (float-time) (+ 5 (cadr cache))))
810 (inferior-octave-send-list-and-digest
811 (list (format "completion_matches ('%s');\n" command)))
812 (setq cache (list command (float-time)
813 (delete-consecutive-dups
814 (sort inferior-octave-output-list 'string-lessp)))))
815 (car (cddr cache))))))
817 (defun inferior-octave-completion-at-point ()
818 "Return the data to complete the Octave symbol at point."
819 ;; http://debbugs.gnu.org/14300
820 (let* ((filecomp (string-match-p
821 "/" (or (comint--match-partial-filename) "")))
822 (end (point))
823 (start
824 (unless filecomp
825 (save-excursion
826 (skip-syntax-backward "w_" (comint-line-beginning-position))
827 (point)))))
828 (when (and start (> end start))
829 (list start end (completion-table-in-turn
830 inferior-octave-completion-table
831 'comint-completion-file-name-table)))))
833 (define-obsolete-function-alias 'inferior-octave-complete
834 'completion-at-point "24.1")
836 (defun inferior-octave-dynamic-list-input-ring ()
837 "List the buffer's input history in a help buffer."
838 ;; We cannot use `comint-dynamic-list-input-ring', because it replaces
839 ;; "completion" by "history reference" ...
840 (interactive)
841 (if (or (not (ring-p comint-input-ring))
842 (ring-empty-p comint-input-ring))
843 (message "No history")
844 (let ((history nil)
845 (history-buffer " *Input History*")
846 (index (1- (ring-length comint-input-ring)))
847 (conf (current-window-configuration)))
848 ;; We have to build up a list ourselves from the ring vector.
849 (while (>= index 0)
850 (setq history (cons (ring-ref comint-input-ring index) history)
851 index (1- index)))
852 ;; Change "completion" to "history reference"
853 ;; to make the display accurate.
854 (with-output-to-temp-buffer history-buffer
855 (display-completion-list history)
856 (set-buffer history-buffer))
857 (message "Hit space to flush")
858 (let ((ch (read-event)))
859 (if (eq ch ?\ )
860 (set-window-configuration conf)
861 (setq unread-command-events (list ch)))))))
863 (defun inferior-octave-output-digest (_proc string)
864 "Special output filter for the inferior Octave process.
865 Save all output between newlines into `inferior-octave-output-list', and
866 the rest to `inferior-octave-output-string'."
867 (setq string (concat inferior-octave-output-string string))
868 (while (string-match "\n" string)
869 (setq inferior-octave-output-list
870 (append inferior-octave-output-list
871 (list (substring string 0 (match-beginning 0))))
872 string (substring string (match-end 0))))
873 (if (string-match inferior-octave-prompt string)
874 (setq inferior-octave-receive-in-progress nil))
875 (setq inferior-octave-output-string string))
877 (defun inferior-octave-check-process ()
878 (or (and inferior-octave-process
879 (process-live-p inferior-octave-process))
880 (error (substitute-command-keys
881 "No inferior octave process running. Type \\[run-octave]"))))
883 (defun inferior-octave-send-list-and-digest (list)
884 "Send LIST to the inferior Octave process and digest the output.
885 The elements of LIST have to be strings and are sent one by one. All
886 output is passed to the filter `inferior-octave-output-digest'."
887 (inferior-octave-check-process)
888 (let* ((proc inferior-octave-process)
889 (filter (process-filter proc))
890 string)
891 (set-process-filter proc 'inferior-octave-output-digest)
892 (setq inferior-octave-output-list nil)
893 (unwind-protect
894 (while (setq string (car list))
895 (setq inferior-octave-output-string nil
896 inferior-octave-receive-in-progress t)
897 (comint-send-string proc string)
898 (while inferior-octave-receive-in-progress
899 (accept-process-output proc))
900 (setq list (cdr list)))
901 (set-process-filter proc filter))))
903 (defvar inferior-octave-directory-tracker-resync nil)
904 (make-variable-buffer-local 'inferior-octave-directory-tracker-resync)
906 (defun inferior-octave-directory-tracker (string)
907 "Tracks `cd' commands issued to the inferior Octave process.
908 Use \\[inferior-octave-resync-dirs] to resync if Emacs gets confused."
909 (when inferior-octave-directory-tracker-resync
910 (or (inferior-octave-resync-dirs 'noerror)
911 (setq inferior-octave-directory-tracker-resync nil)))
912 (cond
913 ((string-match "^[ \t]*cd[ \t;]*$" string)
914 (cd "~"))
915 ((string-match "^[ \t]*cd[ \t]+\\([^ \t\n;]*\\)[ \t\n;]*" string)
916 (condition-case err
917 (cd (match-string 1 string))
918 (error (setq inferior-octave-directory-tracker-resync t)
919 (message "%s: `%s'"
920 (error-message-string err)
921 (match-string 1 string)))))))
923 (defun inferior-octave-resync-dirs (&optional noerror)
924 "Resync the buffer's idea of the current directory.
925 This command queries the inferior Octave process about its current
926 directory and makes this the current buffer's default directory."
927 (interactive)
928 (inferior-octave-send-list-and-digest '("disp (pwd ())\n"))
929 (condition-case err
930 (progn
931 (cd (car inferior-octave-output-list))
933 (error (unless noerror (signal (car err) (cdr err))))))
935 (defcustom inferior-octave-minimal-columns 80
936 "The minimal column width for the inferior Octave process."
937 :type 'integer
938 :group 'octave
939 :version "24.4")
941 (defvar inferior-octave-last-column-width nil)
943 (defun inferior-octave-track-window-width-change ()
944 ;; http://thread.gmane.org/gmane.comp.gnu.octave.general/48572
945 (let ((width (max inferior-octave-minimal-columns (window-width))))
946 (unless (eq inferior-octave-last-column-width width)
947 (setq-local inferior-octave-last-column-width width)
948 (when (and inferior-octave-process
949 (process-live-p inferior-octave-process))
950 (inferior-octave-send-list-and-digest
951 (list (format "putenv ('COLUMNS', '%s');\n" width)))))))
954 ;;; Miscellaneous useful functions
956 (defun octave-in-comment-p ()
957 "Return non-nil if point is inside an Octave comment."
958 (nth 4 (syntax-ppss)))
960 (defun octave-in-string-p ()
961 "Return non-nil if point is inside an Octave string."
962 (nth 3 (syntax-ppss)))
964 (defun octave-in-string-or-comment-p ()
965 "Return non-nil if point is inside an Octave string or comment."
966 (nth 8 (syntax-ppss)))
968 (defun octave-looking-at-kw (regexp)
969 "Like `looking-at', but sets `case-fold-search' nil."
970 (let ((case-fold-search nil))
971 (looking-at regexp)))
973 (defun octave-maybe-insert-continuation-string ()
974 (if (or (octave-in-comment-p)
975 (save-excursion
976 (beginning-of-line)
977 (looking-at octave-continuation-regexp)))
979 (delete-horizontal-space)
980 (insert (concat " " octave-continuation-string))))
982 (defun octave-completing-read ()
983 (let ((def (or (thing-at-point 'symbol)
984 (save-excursion
985 (skip-syntax-backward "-(")
986 (thing-at-point 'symbol)))))
987 (completing-read
988 (format (if def "Function (default %s): "
989 "Function: ") def)
990 inferior-octave-completion-table
991 nil nil nil nil def)))
993 (defun octave-goto-function-definition (fn)
994 "Go to the function definition of FN in current buffer."
995 (let ((search
996 (lambda (re sub)
997 (let ((orig (point)) found)
998 (goto-char (point-min))
999 (while (and (not found) (re-search-forward re nil t))
1000 (when (and (equal (match-string sub) fn)
1001 (not (nth 8 (syntax-ppss))))
1002 (setq found t)))
1003 (unless found (goto-char orig))
1004 found))))
1005 (pcase (and buffer-file-name (file-name-extension buffer-file-name))
1006 (`"cc" (funcall search
1007 "\\_<DEFUN\\(?:_DLD\\)?\\s-*(\\s-*\\(\\(?:\\sw\\|\\s_\\)+\\)" 1))
1008 (t (funcall search octave-function-header-regexp 3)))))
1010 (defun octave-function-file-p ()
1011 "Return non-nil if the first token is \"function\".
1012 The value is (START END NAME-START NAME-END) of the function."
1013 (save-excursion
1014 (goto-char (point-min))
1015 (when (equal (funcall smie-forward-token-function) "function")
1016 (forward-word -1)
1017 (let* ((start (point))
1018 (end (progn (forward-sexp 1) (point)))
1019 (name (when (progn
1020 (goto-char start)
1021 (re-search-forward octave-function-header-regexp
1022 end t))
1023 (list (match-beginning 3) (match-end 3)))))
1024 (cons start (cons end name))))))
1026 ;; Like forward-comment but stop at non-comment blank
1027 (defun octave-skip-comment-forward (limit)
1028 (let ((ppss (syntax-ppss)))
1029 (if (nth 4 ppss)
1030 (goto-char (nth 8 ppss))
1031 (goto-char (or (comment-search-forward limit t) (point)))))
1032 (while (and (< (point) limit) (looking-at-p "\\s<"))
1033 (forward-comment 1)))
1035 ;;; First non-copyright comment block
1036 (defun octave-function-file-comment ()
1037 "Beginning and end positions of the function file comment."
1038 (save-excursion
1039 (goto-char (point-min))
1040 ;; Copyright block: octave/libinterp/parse-tree/lex.ll around line 1634
1041 (while (save-excursion
1042 (when (comment-search-forward (point-max) t)
1043 (when (eq (char-after) ?\{) ; case of block comment
1044 (forward-char 1))
1045 (skip-syntax-forward "-")
1046 (let ((case-fold-search t))
1047 (looking-at-p "\\(?:copyright\\|author\\)\\_>"))))
1048 (octave-skip-comment-forward (point-max)))
1049 (let ((beg (comment-search-forward (point-max) t)))
1050 (when beg
1051 (goto-char beg)
1052 (octave-skip-comment-forward (point-max))
1053 (list beg (point))))))
1055 (defun octave-sync-function-file-names ()
1056 "Ensure function name agree with function file name.
1057 See Info node `(octave)Function Files'."
1058 (interactive)
1059 (when buffer-file-name
1060 (pcase-let ((`(,start ,_end ,name-start ,name-end)
1061 (octave-function-file-p)))
1062 (when (and start name-start)
1063 (let* ((func (buffer-substring name-start name-end))
1064 (file (file-name-sans-extension
1065 (file-name-nondirectory buffer-file-name)))
1066 (help-form (format "\
1067 a: Use function name `%s'
1068 b: Use file name `%s'
1069 q: Don't fix\n" func file))
1070 (c (unless (equal file func)
1071 (save-window-excursion
1072 (help-form-show)
1073 (read-char-choice
1074 "Which name to use? (a/b/q) " '(?a ?b ?q))))))
1075 (pcase c
1076 (`?a (let ((newname (expand-file-name
1077 (concat func (file-name-extension
1078 buffer-file-name t)))))
1079 (when (or (not (file-exists-p newname))
1080 (yes-or-no-p
1081 (format "Target file %s exists; proceed? " newname)))
1082 (when (file-exists-p buffer-file-name)
1083 (rename-file buffer-file-name newname t))
1084 (set-visited-file-name newname))))
1085 (`?b (save-excursion
1086 (goto-char name-start)
1087 (delete-region name-start name-end)
1088 (insert file)))))))))
1090 (defun octave-update-function-file-comment (beg end)
1091 "Query replace function names in function file comment."
1092 (interactive
1093 (progn
1094 (barf-if-buffer-read-only)
1095 (if (use-region-p)
1096 (list (region-beginning) (region-end))
1097 (or (octave-function-file-comment)
1098 (error "No function file comment found")))))
1099 (save-excursion
1100 (let* ((bounds (or (octave-function-file-p)
1101 (error "Not in a function file buffer")))
1102 (func (if (cddr bounds)
1103 (apply #'buffer-substring (cddr bounds))
1104 (error "Function name not found")))
1105 (old-func (progn
1106 (goto-char beg)
1107 (when (re-search-forward
1108 "[=}]\\s-*\\(\\(?:\\sw\\|\\s_\\)+\\)\\_>"
1109 (min (line-end-position 4) end)
1111 (match-string 1))))
1112 (old-func (read-string (format (if old-func
1113 "Name to replace (default %s): "
1114 "Name to replace: ")
1115 old-func)
1116 nil nil old-func)))
1117 (if (and func old-func (not (equal func old-func)))
1118 (perform-replace old-func func 'query
1119 nil 'delimited nil nil beg end)
1120 (message "Function names match")))))
1122 (defface octave-function-comment-block
1123 '((t (:inherit font-lock-doc-face)))
1124 "Face used to highlight function comment block."
1125 :group 'octave)
1127 (eval-when-compile (require 'texinfo))
1129 (defun octave-font-lock-texinfo-comment ()
1130 (let ((kws
1131 (eval-when-compile
1132 (delq nil (mapcar
1133 (lambda (kw)
1134 (if (numberp (nth 1 kw))
1135 `(,(nth 0 kw) ,(nth 1 kw) ,(nth 2 kw) prepend)
1136 (message "Ignoring Texinfo highlight: %S" kw)))
1137 texinfo-font-lock-keywords)))))
1138 (font-lock-add-keywords
1140 `((,(lambda (limit)
1141 (while (and (< (point) limit)
1142 (search-forward "-*- texinfo -*-" limit t)
1143 (octave-in-comment-p))
1144 (let ((beg (nth 8 (syntax-ppss)))
1145 (end (progn
1146 (octave-skip-comment-forward (point-max))
1147 (point))))
1148 (put-text-property beg end 'font-lock-multiline t)
1149 (font-lock-prepend-text-property
1150 beg end 'face 'octave-function-comment-block)
1151 (dolist (kw kws)
1152 (goto-char beg)
1153 (while (re-search-forward (car kw) end 'move)
1154 (font-lock-apply-highlight (cdr kw))))))
1155 nil)))
1156 'append)))
1159 ;;; Indentation
1161 (defun octave-indent-new-comment-line (&optional soft)
1162 "Break Octave line at point, continuing comment if within one.
1163 Insert `octave-continuation-string' before breaking the line
1164 unless inside a list. Signal an error if within a single-quoted
1165 string."
1166 (interactive)
1167 (funcall comment-line-break-function soft))
1169 (defun octave--indent-new-comment-line (orig &rest args)
1170 (cond
1171 ((octave-in-comment-p) nil)
1172 ((eq (octave-in-string-p) ?')
1173 (error "Cannot split a single-quoted string"))
1174 ((eq (octave-in-string-p) ?\")
1175 (insert octave-continuation-string))
1177 (delete-horizontal-space)
1178 (unless (and (cadr (syntax-ppss))
1179 (eq (char-after (cadr (syntax-ppss))) ?\())
1180 (insert " " octave-continuation-string))))
1181 (apply orig args)
1182 (indent-according-to-mode))
1184 (define-obsolete-function-alias
1185 'octave-indent-defun 'prog-indent-sexp "24.4")
1188 ;;; Motion
1189 (defun octave-next-code-line (&optional arg)
1190 "Move ARG lines of Octave code forward (backward if ARG is negative).
1191 Skips past all empty and comment lines. Default for ARG is 1.
1193 On success, return 0. Otherwise, go as far as possible and return -1."
1194 (interactive "p")
1195 (or arg (setq arg 1))
1196 (beginning-of-line)
1197 (let ((n 0)
1198 (inc (if (> arg 0) 1 -1)))
1199 (while (and (/= arg 0) (= n 0))
1200 (setq n (forward-line inc))
1201 (while (and (= n 0)
1202 (looking-at "\\s-*\\($\\|\\s<\\)"))
1203 (setq n (forward-line inc)))
1204 (setq arg (- arg inc)))
1207 (defun octave-previous-code-line (&optional arg)
1208 "Move ARG lines of Octave code backward (forward if ARG is negative).
1209 Skips past all empty and comment lines. Default for ARG is 1.
1211 On success, return 0. Otherwise, go as far as possible and return -1."
1212 (interactive "p")
1213 (or arg (setq arg 1))
1214 (octave-next-code-line (- arg)))
1216 (defun octave-beginning-of-line ()
1217 "Move point to beginning of current Octave line.
1218 If on an empty or comment line, go to the beginning of that line.
1219 Otherwise, move backward to the beginning of the first Octave code line
1220 which is not inside a continuation statement, i.e., which does not
1221 follow a code line ending with `...' or is inside an open
1222 parenthesis list."
1223 (interactive)
1224 (beginning-of-line)
1225 (unless (looking-at "\\s-*\\($\\|\\s<\\)")
1226 (while (or (when (cadr (syntax-ppss))
1227 (goto-char (cadr (syntax-ppss)))
1228 (beginning-of-line)
1230 (and (or (looking-at "\\s-*\\($\\|\\s<\\)")
1231 (save-excursion
1232 (if (zerop (octave-previous-code-line))
1233 (looking-at octave-continuation-regexp))))
1234 (zerop (forward-line -1)))))))
1236 (defun octave-end-of-line ()
1237 "Move point to end of current Octave line.
1238 If on an empty or comment line, go to the end of that line.
1239 Otherwise, move forward to the end of the first Octave code line which
1240 does not end with `...' or is inside an open parenthesis list."
1241 (interactive)
1242 (end-of-line)
1243 (unless (save-excursion
1244 (beginning-of-line)
1245 (looking-at "\\s-*\\($\\|\\s<\\)"))
1246 (while (or (when (cadr (syntax-ppss))
1247 (condition-case nil
1248 (progn
1249 (up-list 1)
1250 (end-of-line)
1252 (error nil)))
1253 (and (save-excursion
1254 (beginning-of-line)
1255 (or (looking-at "\\s-*\\($\\|\\s<\\)")
1256 (looking-at octave-continuation-regexp)))
1257 (zerop (forward-line 1)))))
1258 (end-of-line)))
1260 (defun octave-mark-block ()
1261 "Put point at the beginning of this Octave block, mark at the end.
1262 The block marked is the one that contains point or follows point."
1263 (interactive)
1264 (if (and (looking-at "\\sw\\|\\s_")
1265 (looking-back "\\sw\\|\\s_" (1- (point))))
1266 (skip-syntax-forward "w_"))
1267 (unless (or (looking-at "\\s(")
1268 (save-excursion
1269 (let* ((token (funcall smie-forward-token-function))
1270 (level (assoc token smie-grammar)))
1271 (and level (not (numberp (cadr level)))))))
1272 (backward-up-list 1))
1273 (mark-sexp))
1275 (defun octave-beginning-of-defun (&optional arg)
1276 "Octave-specific `beginning-of-defun-function' (which see)."
1277 (or arg (setq arg 1))
1278 ;; Move out of strings or comments.
1279 (when (octave-in-string-or-comment-p)
1280 (goto-char (octave-in-string-or-comment-p)))
1281 (letrec ((orig (point))
1282 (toplevel (lambda (pos)
1283 (condition-case nil
1284 (progn
1285 (backward-up-list 1)
1286 (funcall toplevel (point)))
1287 (scan-error pos)))))
1288 (goto-char (funcall toplevel (point)))
1289 (when (and (> arg 0) (/= orig (point)))
1290 (setq arg (1- arg)))
1291 (forward-sexp (- arg))
1292 (and (< arg 0) (forward-sexp -1))
1293 (/= orig (point))))
1295 (defun octave-fill-paragraph (&optional _arg)
1296 "Fill paragraph of Octave code, handling Octave comments."
1297 ;; FIXME: difference with generic fill-paragraph:
1298 ;; - code lines are only split, never joined.
1299 ;; - \n that end comments are never removed.
1300 ;; - insert continuation marker when splitting code lines.
1301 (interactive "P")
1302 (save-excursion
1303 (let ((end (progn (forward-paragraph) (copy-marker (point) t)))
1304 (beg (progn
1305 (forward-paragraph -1)
1306 (skip-chars-forward " \t\n")
1307 (beginning-of-line)
1308 (point)))
1309 (cfc (current-fill-column))
1310 comment-prefix)
1311 (goto-char beg)
1312 (while (< (point) end)
1313 (condition-case nil
1314 (indent-according-to-mode)
1315 (error nil))
1316 (move-to-column cfc)
1317 ;; First check whether we need to combine non-empty comment lines
1318 (if (and (< (current-column) cfc)
1319 (octave-in-comment-p)
1320 (not (save-excursion
1321 (beginning-of-line)
1322 (looking-at "^\\s-*\\s<+\\s-*$"))))
1323 ;; This is a nonempty comment line which does not extend
1324 ;; past the fill column. If it is followed by a nonempty
1325 ;; comment line with the same comment prefix, try to
1326 ;; combine them, and repeat this until either we reach the
1327 ;; fill-column or there is nothing more to combine.
1328 (progn
1329 ;; Get the comment prefix
1330 (save-excursion
1331 (beginning-of-line)
1332 (while (and (re-search-forward "\\s<+")
1333 (not (octave-in-comment-p))))
1334 (setq comment-prefix (match-string 0)))
1335 ;; And keep combining ...
1336 (while (and (< (current-column) cfc)
1337 (save-excursion
1338 (forward-line 1)
1339 (and (looking-at
1340 (concat "^\\s-*"
1341 comment-prefix
1342 "\\S<"))
1343 (not (looking-at
1344 (concat "^\\s-*"
1345 comment-prefix
1346 "\\s-*$"))))))
1347 (delete-char 1)
1348 (re-search-forward comment-prefix)
1349 (delete-region (match-beginning 0) (match-end 0))
1350 (fixup-whitespace)
1351 (move-to-column cfc))))
1352 ;; We might also try to combine continued code lines> Perhaps
1353 ;; some other time ...
1354 (skip-chars-forward "^ \t\n")
1355 (delete-horizontal-space)
1356 (if (or (< (current-column) cfc)
1357 (and (= (current-column) cfc) (eolp)))
1358 (forward-line 1)
1359 (if (not (eolp)) (insert " "))
1360 (or (funcall normal-auto-fill-function)
1361 (forward-line 1))))
1362 t)))
1364 (defun octave-completion-at-point ()
1365 "Find the text to complete and the corresponding table."
1366 (let* ((beg (save-excursion (skip-syntax-backward "w_") (point)))
1367 (end (point)))
1368 (if (< beg (point))
1369 ;; Extend region past point, if applicable.
1370 (save-excursion (skip-syntax-forward "w_")
1371 (setq end (point))))
1372 (when (> end beg)
1373 (list beg end (or (and inferior-octave-process
1374 (process-live-p inferior-octave-process)
1375 inferior-octave-completion-table)
1376 octave-reserved-words)))))
1378 (define-obsolete-function-alias 'octave-complete-symbol
1379 'completion-at-point "24.1")
1381 (defun octave-add-log-current-defun ()
1382 "A function for `add-log-current-defun-function' (which see)."
1383 (save-excursion
1384 (end-of-line)
1385 (and (beginning-of-defun)
1386 (re-search-forward octave-function-header-regexp
1387 (line-end-position) t)
1388 (match-string 3))))
1391 ;;; Electric characters && friends
1392 (define-skeleton octave-insert-defun
1393 "Insert an Octave function skeleton.
1394 Prompt for the function's name, arguments and return values (to be
1395 entered without parens)."
1396 (let* ((defname (file-name-sans-extension (buffer-name)))
1397 (name (read-string (format "Function name (default %s): " defname)
1398 nil nil defname))
1399 (args (read-string "Arguments: "))
1400 (vals (read-string "Return values: ")))
1401 (format "%s%s (%s)"
1402 (cond
1403 ((string-equal vals "") vals)
1404 ((string-match "[ ,]" vals) (concat "[" vals "] = "))
1405 (t (concat vals " = ")))
1406 name
1407 args))
1408 \n octave-block-comment-start "usage: " str \n
1409 octave-block-comment-start '(delete-horizontal-space) \n
1410 octave-block-comment-start '(delete-horizontal-space) \n
1411 "function " > str \n
1412 _ \n
1413 "endfunction" > \n)
1415 ;;; Communication with the inferior Octave process
1416 (defun octave-kill-process ()
1417 "Kill inferior Octave process and its buffer."
1418 (interactive)
1419 (if inferior-octave-process
1420 (progn
1421 (process-send-string inferior-octave-process "quit;\n")
1422 (accept-process-output inferior-octave-process)))
1423 (if inferior-octave-buffer
1424 (kill-buffer inferior-octave-buffer)))
1426 (defun octave-show-process-buffer ()
1427 "Make sure that `inferior-octave-buffer' is displayed."
1428 (interactive)
1429 (if (get-buffer inferior-octave-buffer)
1430 (display-buffer inferior-octave-buffer)
1431 (message "No buffer named %s" inferior-octave-buffer)))
1433 (defun octave-hide-process-buffer ()
1434 "Delete all windows that display `inferior-octave-buffer'."
1435 (interactive)
1436 (if (get-buffer inferior-octave-buffer)
1437 (delete-windows-on inferior-octave-buffer)
1438 (message "No buffer named %s" inferior-octave-buffer)))
1440 (defun octave-send-region (beg end)
1441 "Send current region to the inferior Octave process."
1442 (interactive "r")
1443 (inferior-octave t)
1444 (let ((proc inferior-octave-process)
1445 (string (buffer-substring-no-properties beg end))
1446 line)
1447 (with-current-buffer inferior-octave-buffer
1448 (setq inferior-octave-output-list nil)
1449 (while (not (string-equal string ""))
1450 (if (string-match "\n" string)
1451 (setq line (substring string 0 (match-beginning 0))
1452 string (substring string (match-end 0)))
1453 (setq line string string ""))
1454 (setq inferior-octave-receive-in-progress t)
1455 (inferior-octave-send-list-and-digest (list (concat line "\n")))
1456 (while inferior-octave-receive-in-progress
1457 (accept-process-output proc))
1458 (insert-before-markers
1459 (mapconcat 'identity
1460 (append
1461 (if octave-send-echo-input (list line) (list ""))
1462 inferior-octave-output-list
1463 (list inferior-octave-output-string))
1464 "\n")))))
1465 (if octave-send-show-buffer
1466 (display-buffer inferior-octave-buffer)))
1468 (defun octave-send-block ()
1469 "Send current Octave block to the inferior Octave process."
1470 (interactive)
1471 (save-excursion
1472 (octave-mark-block)
1473 (octave-send-region (point) (mark))))
1475 (defun octave-send-defun ()
1476 "Send current Octave function to the inferior Octave process."
1477 (interactive)
1478 (save-excursion
1479 (mark-defun)
1480 (octave-send-region (point) (mark))))
1482 (defun octave-send-line (&optional arg)
1483 "Send current Octave code line to the inferior Octave process.
1484 With positive prefix ARG, send that many lines.
1485 If `octave-send-line-auto-forward' is non-nil, go to the next unsent
1486 code line."
1487 (interactive "P")
1488 (or arg (setq arg 1))
1489 (if (> arg 0)
1490 (let (beg end)
1491 (beginning-of-line)
1492 (setq beg (point))
1493 (octave-next-code-line (- arg 1))
1494 (end-of-line)
1495 (setq end (point))
1496 (if octave-send-line-auto-forward
1497 (octave-next-code-line 1))
1498 (octave-send-region beg end))))
1500 (defun octave-eval-print-last-sexp ()
1501 "Evaluate Octave sexp before point and print value into current buffer."
1502 (interactive)
1503 (inferior-octave t)
1504 (let ((standard-output (current-buffer))
1505 (print-escape-newlines nil)
1506 (opoint (point)))
1507 (terpri)
1508 (prin1
1509 (save-excursion
1510 (forward-sexp -1)
1511 (inferior-octave-send-list-and-digest
1512 (list (concat (buffer-substring-no-properties (point) opoint)
1513 "\n")))
1514 (mapconcat 'identity inferior-octave-output-list "\n")))
1515 (terpri)))
1519 (defcustom octave-eldoc-message-style 'auto
1520 "Octave eldoc message style: auto, oneline, multiline."
1521 :type '(choice (const :tag "Automatic" auto)
1522 (const :tag "One Line" oneline)
1523 (const :tag "Multi Line" multiline))
1524 :group 'octave
1525 :version "24.4")
1527 ;; (FN SIGNATURE1 SIGNATURE2 ...)
1528 (defvar octave-eldoc-cache nil)
1530 (defun octave-eldoc-function-signatures (fn)
1531 (unless (equal fn (car octave-eldoc-cache))
1532 (inferior-octave-send-list-and-digest
1533 (list (format "print_usage ('%s');\n" fn)))
1534 (let (result)
1535 (dolist (line inferior-octave-output-list)
1536 (when (string-match
1537 "\\s-*\\(?:--[^:]+\\|usage\\):\\s-*\\(.*\\)$"
1538 line)
1539 (push (match-string 1 line) result)))
1540 (setq octave-eldoc-cache
1541 (cons (substring-no-properties fn)
1542 (nreverse result)))))
1543 (cdr octave-eldoc-cache))
1545 (defun octave-eldoc-function ()
1546 "A function for `eldoc-documentation-function' (which see)."
1547 (when (and inferior-octave-process
1548 (process-live-p inferior-octave-process))
1549 (let* ((ppss (syntax-ppss))
1550 (paren-pos (cadr ppss))
1551 (fn (save-excursion
1552 (if (and paren-pos
1553 ;; PAREN-POS must be after the prompt
1554 (>= paren-pos
1555 (if (eq (get-buffer-process (current-buffer))
1556 inferior-octave-process)
1557 (process-mark inferior-octave-process)
1558 (point-min)))
1559 (or (not (eq (get-buffer-process (current-buffer))
1560 inferior-octave-process))
1561 (< (process-mark inferior-octave-process)
1562 paren-pos))
1563 (eq (char-after paren-pos) ?\())
1564 (goto-char paren-pos)
1565 (setq paren-pos nil))
1566 (when (or (< (skip-syntax-backward "-") 0) paren-pos)
1567 (thing-at-point 'symbol))))
1568 (sigs (and fn (octave-eldoc-function-signatures fn)))
1569 (oneline (mapconcat 'identity sigs
1570 (propertize " | " 'face 'warning)))
1571 (multiline (mapconcat (lambda (s) (concat "-- " s)) sigs "\n")))
1573 ;; Return the value according to style.
1574 (pcase octave-eldoc-message-style
1575 (`auto (if (< (length oneline) (window-width (minibuffer-window)))
1576 oneline
1577 multiline))
1578 (`oneline oneline)
1579 (`multiline multiline)))))
1581 (defcustom octave-help-buffer "*Octave Help*"
1582 "Buffer name for `octave-help'."
1583 :type 'string
1584 :group 'octave
1585 :version "24.4")
1587 ;; Used in a mode derived from help-mode.
1588 (declare-function help-button-action "help-mode" (button))
1590 (define-button-type 'octave-help-file
1591 'follow-link t
1592 'action #'help-button-action
1593 'help-function 'octave-find-definition)
1595 (define-button-type 'octave-help-function
1596 'follow-link t
1597 'action (lambda (b)
1598 (octave-help
1599 (buffer-substring (button-start b) (button-end b)))))
1601 (defvar octave-help-mode-map
1602 (let ((map (make-sparse-keymap)))
1603 (define-key map "\M-." 'octave-find-definition)
1604 (define-key map "\C-hd" 'octave-help)
1605 (define-key map "\C-ha" 'octave-lookfor)
1606 map))
1608 (define-derived-mode octave-help-mode help-mode "OctHelp"
1609 "Major mode for displaying Octave documentation."
1610 :abbrev-table nil
1611 :syntax-table octave-mode-syntax-table
1612 (eval-and-compile (require 'help-mode))
1613 ;; Mostly stolen from `help-make-xrefs'.
1614 (let ((inhibit-read-only t))
1615 (setq-local info-lookup-mode 'octave-mode)
1616 ;; Delete extraneous newlines at the end of the docstring
1617 (goto-char (point-max))
1618 (while (and (not (bobp)) (bolp))
1619 (delete-char -1))
1620 (insert "\n")
1621 (when (or help-xref-stack help-xref-forward-stack)
1622 (insert "\n"))
1623 (when help-xref-stack
1624 (help-insert-xref-button help-back-label 'help-back
1625 (current-buffer)))
1626 (when help-xref-forward-stack
1627 (when help-xref-stack
1628 (insert "\t"))
1629 (help-insert-xref-button help-forward-label 'help-forward
1630 (current-buffer)))
1631 (when (or help-xref-stack help-xref-forward-stack)
1632 (insert "\n"))))
1634 (defun octave-help (fn)
1635 "Display the documentation of FN."
1636 (interactive (list (octave-completing-read)))
1637 (inferior-octave-send-list-and-digest
1638 (list (format "help ('%s');\n" fn)))
1639 (let ((lines inferior-octave-output-list)
1640 (inhibit-read-only t))
1641 (when (string-match "error: \\(.*\\)$" (car lines))
1642 (error "%s" (match-string 1 (car lines))))
1643 (with-help-window octave-help-buffer
1644 (princ (mapconcat 'identity lines "\n"))
1645 (with-current-buffer octave-help-buffer
1646 ;; Bound to t so that `help-buffer' returns current buffer for
1647 ;; `help-setup-xref'.
1648 (let ((help-xref-following t))
1649 (help-setup-xref (list 'octave-help fn)
1650 (called-interactively-p 'interactive)))
1651 ;; Note: can be turned off by suppress_verbose_help_message.
1653 ;; Remove boring trailing text: Additional help for built-in functions
1654 ;; and operators ...
1655 (goto-char (point-max))
1656 (when (search-backward "\n\n\n" nil t)
1657 (goto-char (match-beginning 0))
1658 (delete-region (point) (point-max)))
1659 ;; File name highlight
1660 (goto-char (point-min))
1661 (when (re-search-forward "from the file \\(.*\\)$"
1662 (line-end-position)
1664 (let* ((file (match-string 1))
1665 (dir (file-name-directory
1666 (directory-file-name (file-name-directory file)))))
1667 (replace-match "" nil nil nil 1)
1668 (insert "`")
1669 ;; Include the parent directory which may be regarded as
1670 ;; the category for the FN.
1671 (help-insert-xref-button (file-relative-name file dir)
1672 'octave-help-file fn)
1673 (insert "'")))
1674 ;; Make 'See also' clickable.
1675 (with-syntax-table octave-mode-syntax-table
1676 (when (re-search-forward "^\\s-*See also:" nil t)
1677 (let ((end (save-excursion (re-search-forward "^\\s-*$" nil t))))
1678 (while (re-search-forward
1679 "\\s-*\\([^,\n]+?\\)\\s-*\\(?:[,]\\|[.]?$\\)" end t)
1680 (make-text-button (match-beginning 1) (match-end 1)
1681 :type 'octave-help-function)))))
1682 (octave-help-mode)))))
1684 (defun octave-lookfor (str &optional all)
1685 "Search for the string STR in all function help strings.
1686 If ALL is non-nil search the entire help string else only search the first
1687 sentence."
1688 (interactive "sSearch for: \nP")
1689 (inferior-octave-send-list-and-digest
1690 (list (format "lookfor (%s'%s');\n"
1691 (if all "'-all', " "")
1692 str)))
1693 (let ((lines inferior-octave-output-list))
1694 (when (string-match "error: \\(.*\\)$" (car lines))
1695 (error "%s" (match-string 1 (car lines))))
1696 (with-help-window octave-help-buffer
1697 (princ (mapconcat 'identity lines "\n"))
1698 (with-current-buffer octave-help-buffer
1699 ;; Bound to t so that `help-buffer' returns current buffer for
1700 ;; `help-setup-xref'.
1701 (let ((help-xref-following t))
1702 (help-setup-xref (list 'octave-lookfor str all)
1703 (called-interactively-p 'interactive)))
1704 (goto-char (point-min))
1705 (while (re-search-forward "^\\([^[:blank:]]+\\) " nil 'noerror)
1706 (make-text-button (match-beginning 1) (match-end 1)
1707 :type 'octave-help-function))
1708 (octave-help-mode)))))
1710 (defcustom octave-source-directories nil
1711 "A list of directories for Octave sources.
1712 If the environment variable OCTAVE_SRCDIR is set, it is searched first."
1713 :type '(repeat directory)
1714 :group 'octave
1715 :version "24.4")
1717 (defun octave-source-directories ()
1718 (let ((srcdir (or (and inferior-octave-process
1719 (process-get inferior-octave-process 'octave-srcdir))
1720 (getenv "OCTAVE_SRCDIR"))))
1721 (if srcdir
1722 (cons srcdir octave-source-directories)
1723 octave-source-directories)))
1725 (defvar octave-find-definition-filename-function
1726 #'octave-find-definition-default-filename)
1728 (defun octave-find-definition-default-filename (name)
1729 "Default value for `octave-find-definition-filename-function'."
1730 (pcase (file-name-extension name)
1731 (`"oct"
1732 (octave-find-definition-default-filename
1733 (concat "libinterp/dldfcn/"
1734 (file-name-sans-extension (file-name-nondirectory name))
1735 ".cc")))
1736 (`"cc"
1737 (let ((file (or (locate-file name (octave-source-directories))
1738 (locate-file (file-name-nondirectory name)
1739 (octave-source-directories)))))
1740 (or (and file (file-exists-p file))
1741 (error "File `%s' not found" name))
1742 file))
1743 (`"mex"
1744 (if (yes-or-no-p (format "File `%s' may be binary; open? "
1745 (file-name-nondirectory name)))
1746 name
1747 (user-error "Aborted")))
1748 (t name)))
1750 (defvar find-tag-marker-ring)
1752 (defun octave-find-definition (fn)
1753 "Find the definition of FN.
1754 Functions implemented in C++ can be found if
1755 `octave-source-directories' is set correctly."
1756 (interactive (list (octave-completing-read)))
1757 (require 'etags)
1758 (let ((orig (point)))
1759 (if (and (derived-mode-p 'octave-mode)
1760 (octave-goto-function-definition fn))
1761 (ring-insert find-tag-marker-ring (copy-marker orig))
1762 (inferior-octave-send-list-and-digest
1763 ;; help NAME is more verbose
1764 (list (format "\
1765 if iskeyword('%s') disp('`%s'' is a keyword') else which('%s') endif\n"
1766 fn fn fn)))
1767 (let (line file)
1768 ;; Skip garbage lines such as
1769 ;; warning: fmincg.m: possible Matlab-style ....
1770 (while (and (not file) (consp inferior-octave-output-list))
1771 (setq line (pop inferior-octave-output-list))
1772 (when (string-match "from the file \\(.*\\)$" line)
1773 (setq file (match-string 1 line))))
1774 (if (not file)
1775 (user-error "%s" (or line (format "`%s' not found" fn)))
1776 (ring-insert find-tag-marker-ring (point-marker))
1777 (setq file (funcall octave-find-definition-filename-function file))
1778 (when file
1779 (find-file file)
1780 (octave-goto-function-definition fn)))))))
1782 (provide 'octave)
1783 ;;; octave.el ends here