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