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