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