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