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