* progmodes/octave.el (inferior-octave-directory-tracker-resync):
[bpt/emacs.git] / lisp / progmodes / octave.el
1 ;;; octave.el --- editing octave source files under emacs -*- lexical-binding: t; -*-
2
3 ;; Copyright (C) 1997, 2001-2013 Free Software Foundation, Inc.
4
5 ;; Author: Kurt Hornik <Kurt.Hornik@wu-wien.ac.at>
6 ;; John Eaton <jwe@octave.org>
7 ;; Maintainer: FSF
8 ;; Keywords: languages
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24
25 ;;; Commentary:
26
27 ;; This package provides emacs support for Octave. It defines a major
28 ;; mode for editing Octave code and contains code for interacting with
29 ;; an inferior Octave process using comint.
30
31 ;; See the documentation of `octave-mode' and `run-octave' for further
32 ;; information on usage and customization.
33
34 ;;; Code:
35 (require 'comint)
36
37 ;;; For emacs < 24.3.
38 (require 'newcomment)
39 (eval-and-compile
40 (unless (fboundp 'user-error)
41 (defalias 'user-error 'error))
42 (unless (fboundp 'delete-consecutive-dups)
43 (defalias 'delete-consecutive-dups 'delete-dups)))
44 (eval-when-compile
45 (unless (fboundp 'setq-local)
46 (defmacro setq-local (var val)
47 "Set variable VAR to value VAL in current buffer."
48 (list 'set (list 'make-local-variable (list 'quote var)) val))))
49
50 (defgroup octave nil
51 "Editing Octave code."
52 :link '(custom-group-link :tag "Font Lock Faces group" font-lock-faces)
53 :group 'languages)
54
55 (define-obsolete-function-alias 'octave-submit-bug-report
56 'report-emacs-bug "24.4")
57
58 (define-abbrev-table 'octave-abbrev-table nil
59 "Abbrev table for Octave's reserved words.
60 Used in `octave-mode' and `inferior-octave-mode' buffers.")
61
62 (defvar octave-comment-char ?#
63 "Character to start an Octave comment.")
64
65 (defvar octave-comment-start (char-to-string octave-comment-char)
66 "Octave-specific `comment-start' (which see).")
67
68 (defvar octave-comment-start-skip "\\(^\\|\\S<\\)\\(?:%!\\|\\s<+\\)\\s-*"
69 "Octave-specific `comment-start-skip' (which see).")
70
71 (defvar octave-begin-keywords
72 '("classdef" "do" "enumeration" "events" "for" "function" "if" "methods"
73 "parfor" "properties" "switch" "try" "unwind_protect" "while"))
74
75 (defvar octave-else-keywords
76 '("case" "catch" "else" "elseif" "otherwise" "unwind_protect_cleanup"))
77
78 (defvar octave-end-keywords
79 '("endclassdef" "endenumeration" "endevents" "endfor" "endfunction" "endif"
80 "endmethods" "endparfor" "endproperties" "endswitch" "end_try_catch"
81 "end_unwind_protect" "endwhile" "until" "end"))
82
83 (defvar octave-reserved-words
84 (append octave-begin-keywords
85 octave-else-keywords
86 octave-end-keywords
87 '("break" "continue" "global" "persistent" "return"))
88 "Reserved words in Octave.")
89
90 (defvar octave-function-header-regexp
91 (concat "^\\s-*\\_<\\(function\\)\\_>"
92 "\\([^=;\n]*=[ \t]*\\|[ \t]*\\)\\(\\(?:\\w\\|\\s_\\)+\\)\\_>")
93 "Regexp to match an Octave function header.
94 The string `function' and its name are given by the first and third
95 parenthetical grouping.")
96
97 \f
98 (defvar octave-mode-map
99 (let ((map (make-sparse-keymap)))
100 (define-key map "\M-." 'octave-find-definition)
101 (define-key map "\M-\C-j" 'octave-indent-new-comment-line)
102 (define-key map "\C-c\C-p" 'octave-previous-code-line)
103 (define-key map "\C-c\C-n" 'octave-next-code-line)
104 (define-key map "\C-c\C-a" 'octave-beginning-of-line)
105 (define-key map "\C-c\C-e" 'octave-end-of-line)
106 (define-key map [remap down-list] 'smie-down-list)
107 (define-key map "\C-c\M-\C-h" 'octave-mark-block)
108 (define-key map "\C-c]" 'smie-close-block)
109 (define-key map "\C-c/" 'smie-close-block)
110 (define-key map "\C-c;" 'octave-update-function-file-comment)
111 (define-key map "\C-hd" 'octave-help)
112 (define-key map "\C-c\C-f" 'octave-insert-defun)
113 (define-key map "\C-c\C-il" 'octave-send-line)
114 (define-key map "\C-c\C-ib" 'octave-send-block)
115 (define-key map "\C-c\C-if" 'octave-send-defun)
116 (define-key map "\C-c\C-ir" 'octave-send-region)
117 (define-key map "\C-c\C-is" 'octave-show-process-buffer)
118 (define-key map "\C-c\C-iq" 'octave-hide-process-buffer)
119 (define-key map "\C-c\C-ik" 'octave-kill-process)
120 (define-key map "\C-c\C-i\C-l" 'octave-send-line)
121 (define-key map "\C-c\C-i\C-b" 'octave-send-block)
122 (define-key map "\C-c\C-i\C-f" 'octave-send-defun)
123 (define-key map "\C-c\C-i\C-r" 'octave-send-region)
124 (define-key map "\C-c\C-i\C-s" 'octave-show-process-buffer)
125 (define-key map "\C-c\C-i\C-q" 'octave-hide-process-buffer)
126 (define-key map "\C-c\C-i\C-k" 'octave-kill-process)
127 map)
128 "Keymap used in Octave mode.")
129
130
131
132 (easy-menu-define octave-mode-menu octave-mode-map
133 "Menu for Octave mode."
134 '("Octave"
135 ["Split Line at Point" octave-indent-new-comment-line t]
136 ["Previous Code Line" octave-previous-code-line t]
137 ["Next Code Line" octave-next-code-line t]
138 ["Begin of Line" octave-beginning-of-line t]
139 ["End of Line" octave-end-of-line t]
140 ["Mark Block" octave-mark-block t]
141 ["Close Block" smie-close-block t]
142 "---"
143 ["Start Octave Process" run-octave t]
144 ["Documentation Lookup" info-lookup-symbol t]
145 ["Help on Function" octave-help t]
146 ["Find Function Definition" octave-find-definition t]
147 ["Insert Function" octave-insert-defun t]
148 ["Update Function File Comment" octave-update-function-file-comment t]
149 "---"
150 ["Function Syntax Hints" (call-interactively
151 (if (fboundp 'eldoc-post-insert-mode)
152 'eldoc-post-insert-mode
153 'eldoc-mode))
154 :style toggle :selected (or eldoc-post-insert-mode eldoc-mode)
155 :help "Display function signatures after typing `SPC' or `('"]
156 ["Delimiter Matching" 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 nil))))
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 (setq-local fill-nobreak-predicate
556 (lambda () (eq (octave-in-string-p) ?')))
557 (add-function :around (local 'comment-line-break-function)
558 #'octave--indent-new-comment-line)
559
560 (setq font-lock-defaults '(octave-font-lock-keywords))
561
562 (setq-local syntax-propertize-function #'octave-syntax-propertize-function)
563
564 (setq-local imenu-generic-expression octave-mode-imenu-generic-expression)
565 (setq-local imenu-case-fold-search nil)
566
567 (add-hook 'completion-at-point-functions 'octave-completion-at-point nil t)
568 (add-hook 'before-save-hook 'octave-sync-function-file-names nil t)
569 (setq-local beginning-of-defun-function 'octave-beginning-of-defun)
570 (and octave-font-lock-texinfo-comment (octave-font-lock-texinfo-comment))
571 (setq-local eldoc-documentation-function 'octave-eldoc-function)
572
573 (easy-menu-add octave-mode-menu))
574
575 \f
576 (defcustom inferior-octave-program "octave"
577 "Program invoked by `inferior-octave'."
578 :type 'string
579 :group 'octave)
580
581 (defcustom inferior-octave-buffer "*Inferior Octave*"
582 "Name of buffer for running an inferior Octave process."
583 :type 'string
584 :group 'octave)
585
586 (defcustom inferior-octave-prompt
587 "\\(^octave\\(\\|.bin\\|.exe\\)\\(-[.0-9]+\\)?\\(:[0-9]+\\)?\\|^debug\\|^\\)>+ "
588 "Regexp to match prompts for the inferior Octave process."
589 :type 'regexp
590 :group 'octave)
591
592 (defcustom inferior-octave-prompt-read-only comint-prompt-read-only
593 "If non-nil, the Octave prompt is read only.
594 See `comint-prompt-read-only' for details."
595 :type 'boolean
596 :group 'octave
597 :version "24.4")
598
599 (defcustom inferior-octave-startup-file
600 (convert-standard-filename
601 (concat "~/.emacs-" (file-name-nondirectory inferior-octave-program)))
602 "Name of the inferior Octave startup file.
603 The contents of this file are sent to the inferior Octave process on
604 startup."
605 :type '(choice (const :tag "None" nil) file)
606 :group 'octave
607 :version "24.4")
608
609 (defcustom inferior-octave-startup-args nil
610 "List of command line arguments for the inferior Octave process.
611 For example, for suppressing the startup message and using `traditional'
612 mode, set this to (\"-q\" \"--traditional\")."
613 :type '(repeat string)
614 :group 'octave)
615
616 (defcustom inferior-octave-mode-hook nil
617 "Hook to be run when Inferior Octave mode is started."
618 :type 'hook
619 :group 'octave)
620
621 (defvar inferior-octave-process nil)
622
623 (defvar inferior-octave-mode-map
624 (let ((map (make-sparse-keymap)))
625 (set-keymap-parent map comint-mode-map)
626 (define-key map "\M-." 'octave-find-definition)
627 (define-key map "\t" 'completion-at-point)
628 (define-key map "\C-hd" 'octave-help)
629 ;; Same as in `shell-mode'.
630 (define-key map "\M-?" 'comint-dynamic-list-filename-completions)
631 (define-key map "\C-c\C-l" 'inferior-octave-dynamic-list-input-ring)
632 (define-key map [menu-bar inout list-history]
633 '("List Input History" . inferior-octave-dynamic-list-input-ring))
634 map)
635 "Keymap used in Inferior Octave mode.")
636
637 (defvar inferior-octave-mode-syntax-table
638 (let ((table (make-syntax-table octave-mode-syntax-table)))
639 table)
640 "Syntax table in use in inferior-octave-mode buffers.")
641
642 (defvar inferior-octave-font-lock-keywords
643 (list
644 (cons inferior-octave-prompt 'font-lock-type-face))
645 ;; Could certainly do more font locking in inferior Octave ...
646 "Additional expressions to highlight in Inferior Octave mode.")
647
648 (defvar inferior-octave-output-list nil)
649 (defvar inferior-octave-output-string nil)
650 (defvar inferior-octave-receive-in-progress nil)
651
652 (define-obsolete-variable-alias 'inferior-octave-startup-hook
653 'inferior-octave-mode-hook "24.4")
654
655 (defvar inferior-octave-dynamic-complete-functions
656 '(inferior-octave-completion-at-point comint-filename-completion)
657 "List of functions called to perform completion for inferior Octave.
658 This variable is used to initialize `comint-dynamic-complete-functions'
659 in the Inferior Octave buffer.")
660
661 (defvar info-lookup-mode)
662
663 (define-derived-mode inferior-octave-mode comint-mode "Inferior Octave"
664 "Major mode for interacting with an inferior Octave process."
665 :abbrev-table octave-abbrev-table
666 (setq comint-prompt-regexp inferior-octave-prompt)
667
668 (setq-local comment-start octave-comment-start)
669 (setq-local comment-end "")
670 (setq comment-column 32)
671 (setq-local comment-start-skip octave-comment-start-skip)
672
673 (setq font-lock-defaults '(inferior-octave-font-lock-keywords nil nil))
674
675 (setq-local info-lookup-mode 'octave-mode)
676 (setq-local eldoc-documentation-function 'octave-eldoc-function)
677
678 (setq comint-input-ring-file-name
679 (or (getenv "OCTAVE_HISTFILE") "~/.octave_hist")
680 comint-input-ring-size (or (getenv "OCTAVE_HISTSIZE") 1024))
681 (setq-local comint-dynamic-complete-functions
682 inferior-octave-dynamic-complete-functions)
683 (setq-local comint-prompt-read-only inferior-octave-prompt-read-only)
684 (add-hook 'comint-input-filter-functions
685 'inferior-octave-directory-tracker nil t)
686 (comint-read-input-ring t))
687
688 ;;;###autoload
689 (defun inferior-octave (&optional arg)
690 "Run an inferior Octave process, I/O via `inferior-octave-buffer'.
691 This buffer is put in Inferior Octave mode. See `inferior-octave-mode'.
692
693 Unless ARG is non-nil, switches to this buffer.
694
695 The elements of the list `inferior-octave-startup-args' are sent as
696 command line arguments to the inferior Octave process on startup.
697
698 Additional commands to be executed on startup can be provided either in
699 the file specified by `inferior-octave-startup-file' or by the default
700 startup file, `~/.emacs-octave'."
701 (interactive "P")
702 (let ((buffer (get-buffer-create inferior-octave-buffer)))
703 (unless arg
704 (pop-to-buffer buffer))
705 (unless (comint-check-proc buffer)
706 (with-current-buffer buffer
707 (inferior-octave-startup)
708 (inferior-octave-mode)))
709 buffer))
710
711 ;;;###autoload
712 (defalias 'run-octave 'inferior-octave)
713
714 (defun inferior-octave-startup ()
715 "Start an inferior Octave process."
716 (let ((proc (comint-exec-1
717 (substring inferior-octave-buffer 1 -1)
718 inferior-octave-buffer
719 inferior-octave-program
720 (append (list "-i" "--no-line-editing")
721 ;; --no-gui is introduced in Octave > 3.7
722 (when (zerop (process-file inferior-octave-program
723 nil nil nil
724 "--no-gui" "--help"))
725 (list "--no-gui"))
726 inferior-octave-startup-args))))
727 (set-process-filter proc 'inferior-octave-output-digest)
728 (setq inferior-octave-process proc
729 inferior-octave-output-list nil
730 inferior-octave-output-string nil
731 inferior-octave-receive-in-progress t)
732
733 ;; This may look complicated ... However, we need to make sure that
734 ;; we additional startup code only AFTER Octave is ready (otherwise,
735 ;; output may be mixed up). Hence, we need to digest the Octave
736 ;; output to see when it issues a prompt.
737 (while inferior-octave-receive-in-progress
738 (or (process-live-p inferior-octave-process)
739 (error "Process `%s' died" inferior-octave-process))
740 (accept-process-output inferior-octave-process))
741 (goto-char (point-max))
742 (set-marker (process-mark proc) (point))
743 (insert-before-markers
744 (concat
745 (if (not (bobp)) "\f\n")
746 (if inferior-octave-output-list
747 (concat (mapconcat
748 'identity inferior-octave-output-list "\n")
749 "\n"))))
750
751 ;; An empty secondary prompt, as e.g. obtained by '--braindead',
752 ;; means trouble.
753 (inferior-octave-send-list-and-digest (list "PS2\n"))
754 (when (string-match "\\(PS2\\|ans\\) = *$"
755 (car inferior-octave-output-list))
756 (inferior-octave-send-list-and-digest (list "PS2 (\"> \");\n")))
757
758 (inferior-octave-send-list-and-digest
759 (list "disp(getenv(\"OCTAVE_SRCDIR\"))\n"))
760 (process-put proc 'octave-srcdir
761 (unless (equal (car inferior-octave-output-list) "")
762 (car inferior-octave-output-list)))
763
764 ;; O.K., now we are ready for the Inferior Octave startup commands.
765 (inferior-octave-send-list-and-digest
766 (list "more off;\n"
767 (unless (equal inferior-octave-output-string ">> ")
768 "PS1 (\"\\\\s> \");\n")
769 (when (and inferior-octave-startup-file
770 (file-exists-p inferior-octave-startup-file))
771 (format "source (\"%s\");\n" inferior-octave-startup-file))))
772 (when inferior-octave-output-list
773 (insert-before-markers
774 (mapconcat 'identity inferior-octave-output-list "\n")))
775
776 ;; And finally, everything is back to normal.
777 (set-process-filter proc 'comint-output-filter)
778 ;; Just in case, to be sure a cd in the startup file
779 ;; won't have detrimental effects.
780 (inferior-octave-resync-dirs)
781 ;; Generate a proper prompt, which is critical to
782 ;; `comint-history-isearch-backward-regexp'. Bug#14433.
783 (comint-send-string proc "\n")))
784
785 (defvar inferior-octave-completion-table
786 ;;
787 ;; Use cache to avoid repetitive computation of completions due to
788 ;; bug#11906 - http://debbugs.gnu.org/11906 - which may cause
789 ;; noticeable delay. CACHE: (CMD TIME VALUE).
790 (let ((cache))
791 (completion-table-dynamic
792 (lambda (command)
793 (unless (and (equal (car cache) command)
794 (< (float-time) (+ 5 (cadr cache))))
795 (inferior-octave-send-list-and-digest
796 (list (concat "completion_matches (\"" command "\");\n")))
797 (setq cache (list command (float-time)
798 (delete-consecutive-dups
799 (sort inferior-octave-output-list 'string-lessp)))))
800 (car (cddr cache))))))
801
802 (defun inferior-octave-completion-at-point ()
803 "Return the data to complete the Octave symbol at point."
804 ;; http://debbugs.gnu.org/14300
805 (let* ((filecomp (string-match-p
806 "/" (or (comint--match-partial-filename) "")))
807 (end (point))
808 (start
809 (unless filecomp
810 (save-excursion
811 (skip-syntax-backward "w_" (comint-line-beginning-position))
812 (point)))))
813 (when (and start (> end start))
814 (list start end (completion-table-in-turn
815 inferior-octave-completion-table
816 'comint-completion-file-name-table)))))
817
818 (define-obsolete-function-alias 'inferior-octave-complete
819 'completion-at-point "24.1")
820
821 (defun inferior-octave-dynamic-list-input-ring ()
822 "List the buffer's input history in a help buffer."
823 ;; We cannot use `comint-dynamic-list-input-ring', because it replaces
824 ;; "completion" by "history reference" ...
825 (interactive)
826 (if (or (not (ring-p comint-input-ring))
827 (ring-empty-p comint-input-ring))
828 (message "No history")
829 (let ((history nil)
830 (history-buffer " *Input History*")
831 (index (1- (ring-length comint-input-ring)))
832 (conf (current-window-configuration)))
833 ;; We have to build up a list ourselves from the ring vector.
834 (while (>= index 0)
835 (setq history (cons (ring-ref comint-input-ring index) history)
836 index (1- index)))
837 ;; Change "completion" to "history reference"
838 ;; to make the display accurate.
839 (with-output-to-temp-buffer history-buffer
840 (display-completion-list history)
841 (set-buffer history-buffer))
842 (message "Hit space to flush")
843 (let ((ch (read-event)))
844 (if (eq ch ?\ )
845 (set-window-configuration conf)
846 (setq unread-command-events (list ch)))))))
847
848 (defun inferior-octave-output-digest (_proc string)
849 "Special output filter for the inferior Octave process.
850 Save all output between newlines into `inferior-octave-output-list', and
851 the rest to `inferior-octave-output-string'."
852 (setq string (concat inferior-octave-output-string string))
853 (while (string-match "\n" string)
854 (setq inferior-octave-output-list
855 (append inferior-octave-output-list
856 (list (substring string 0 (match-beginning 0))))
857 string (substring string (match-end 0))))
858 (if (string-match inferior-octave-prompt string)
859 (setq inferior-octave-receive-in-progress nil))
860 (setq inferior-octave-output-string string))
861
862 (defun inferior-octave-check-process ()
863 (or (and inferior-octave-process
864 (process-live-p inferior-octave-process))
865 (error (substitute-command-keys
866 "No inferior octave process running. Type \\[run-octave]"))))
867
868 (defun inferior-octave-send-list-and-digest (list)
869 "Send LIST to the inferior Octave process and digest the output.
870 The elements of LIST have to be strings and are sent one by one. All
871 output is passed to the filter `inferior-octave-output-digest'."
872 (inferior-octave-check-process)
873 (let* ((proc inferior-octave-process)
874 (filter (process-filter proc))
875 string)
876 (set-process-filter proc 'inferior-octave-output-digest)
877 (setq inferior-octave-output-list nil)
878 (unwind-protect
879 (while (setq string (car list))
880 (setq inferior-octave-output-string nil
881 inferior-octave-receive-in-progress t)
882 (comint-send-string proc string)
883 (while inferior-octave-receive-in-progress
884 (accept-process-output proc))
885 (setq list (cdr list)))
886 (set-process-filter proc filter))))
887
888 (defvar inferior-octave-directory-tracker-resync nil)
889 (make-variable-buffer-local 'inferior-octave-directory-tracker-resync)
890
891 (defun inferior-octave-directory-tracker (string)
892 "Tracks `cd' commands issued to the inferior Octave process.
893 Use \\[inferior-octave-resync-dirs] to resync if Emacs gets confused."
894 (when inferior-octave-directory-tracker-resync
895 (setq inferior-octave-directory-tracker-resync nil)
896 (inferior-octave-resync-dirs))
897 (cond
898 ((string-match "^[ \t]*cd[ \t;]*$" string)
899 (cd "~"))
900 ((string-match "^[ \t]*cd[ \t]+\\([^ \t\n;]*\\)[ \t\n;]*" string)
901 (condition-case err
902 (cd (match-string 1 string))
903 (error (setq inferior-octave-directory-tracker-resync t)
904 (message "%s: `%s'"
905 (error-message-string err)
906 (match-string 1 string)))))))
907
908 (defun inferior-octave-resync-dirs ()
909 "Resync the buffer's idea of the current directory.
910 This command queries the inferior Octave process about its current
911 directory and makes this the current buffer's default directory."
912 (interactive)
913 (inferior-octave-send-list-and-digest '("disp (pwd ())\n"))
914 (cd (car inferior-octave-output-list)))
915
916 \f
917 ;;; Miscellaneous useful functions
918
919 (defun octave-in-comment-p ()
920 "Return non-nil if point is inside an Octave comment."
921 (nth 4 (syntax-ppss)))
922
923 (defun octave-in-string-p ()
924 "Return non-nil if point is inside an Octave string."
925 (nth 3 (syntax-ppss)))
926
927 (defun octave-in-string-or-comment-p ()
928 "Return non-nil if point is inside an Octave string or comment."
929 (nth 8 (syntax-ppss)))
930
931 (defun octave-looking-at-kw (regexp)
932 "Like `looking-at', but sets `case-fold-search' nil."
933 (let ((case-fold-search nil))
934 (looking-at regexp)))
935
936 (defun octave-maybe-insert-continuation-string ()
937 (if (or (octave-in-comment-p)
938 (save-excursion
939 (beginning-of-line)
940 (looking-at octave-continuation-regexp)))
941 nil
942 (delete-horizontal-space)
943 (insert (concat " " octave-continuation-string))))
944
945 (defun octave-completing-read ()
946 (let ((def (or (thing-at-point 'symbol)
947 (save-excursion
948 (skip-syntax-backward "-(")
949 (thing-at-point 'symbol)))))
950 (completing-read
951 (format (if def "Function (default %s): "
952 "Function: ") def)
953 inferior-octave-completion-table
954 nil nil nil nil def)))
955
956 (defun octave-goto-function-definition (fn)
957 "Go to the function definition of FN in current buffer."
958 (goto-char (point-min))
959 (let ((search
960 (lambda (re sub)
961 (let (done)
962 (while (and (not done) (re-search-forward re nil t))
963 (when (and (equal (match-string sub) fn)
964 (not (nth 8 (syntax-ppss))))
965 (setq done t)))
966 (or done (goto-char (point-min)))))))
967 (pcase (file-name-extension (buffer-file-name))
968 (`"cc" (funcall search
969 "\\_<DEFUN\\(?:_DLD\\)?\\s-*(\\s-*\\(\\(?:\\sw\\|\\s_\\)+\\)" 1))
970 (t (funcall search octave-function-header-regexp 3)))))
971
972 (defun octave-function-file-p ()
973 "Return non-nil if the first token is \"function\".
974 The value is (START END NAME-START NAME-END) of the function."
975 (save-excursion
976 (goto-char (point-min))
977 (when (equal (funcall smie-forward-token-function) "function")
978 (forward-word -1)
979 (let* ((start (point))
980 (end (progn (forward-sexp 1) (point)))
981 (name (when (progn
982 (goto-char start)
983 (re-search-forward octave-function-header-regexp
984 end t))
985 (list (match-beginning 3) (match-end 3)))))
986 (cons start (cons end name))))))
987
988 ;; Like forward-comment but stop at non-comment blank
989 (defun octave-skip-comment-forward (limit)
990 (let ((ppss (syntax-ppss)))
991 (if (nth 4 ppss)
992 (goto-char (nth 8 ppss))
993 (goto-char (or (comment-search-forward limit t) (point)))))
994 (while (and (< (point) limit) (looking-at-p "\\s<"))
995 (forward-comment 1)))
996
997 ;;; First non-copyright comment block
998 (defun octave-function-file-comment ()
999 "Beginning and end positions of the function file comment."
1000 (save-excursion
1001 (goto-char (point-min))
1002 ;; Copyright block: octave/libinterp/parse-tree/lex.ll around line 1634
1003 (while (save-excursion
1004 (when (comment-search-forward (point-max) t)
1005 (when (eq (char-after) ?\{) ; case of block comment
1006 (forward-char 1))
1007 (skip-syntax-forward "-")
1008 (let ((case-fold-search t))
1009 (looking-at-p "\\(?:copyright\\|author\\)\\_>"))))
1010 (octave-skip-comment-forward (point-max)))
1011 (let ((beg (comment-search-forward (point-max) t)))
1012 (when beg
1013 (goto-char beg)
1014 (octave-skip-comment-forward (point-max))
1015 (list beg (point))))))
1016
1017 (defun octave-sync-function-file-names ()
1018 "Ensure function name agree with function file name.
1019 See Info node `(octave)Function Files'."
1020 (interactive)
1021 (when buffer-file-name
1022 (pcase-let ((`(,start ,_end ,name-start ,name-end)
1023 (octave-function-file-p)))
1024 (when (and start name-start)
1025 (let* ((func (buffer-substring name-start name-end))
1026 (file (file-name-sans-extension
1027 (file-name-nondirectory buffer-file-name)))
1028 (help-form (format "\
1029 a: Use function name `%s'
1030 b: Use file name `%s'
1031 q: Don't fix\n" func file))
1032 (c (unless (equal file func)
1033 (save-window-excursion
1034 (help-form-show)
1035 (read-char-choice
1036 "Which name to use? (a/b/q) " '(?a ?b ?q))))))
1037 (pcase c
1038 (`?a (let ((newname (expand-file-name
1039 (concat func (file-name-extension
1040 buffer-file-name t)))))
1041 (when (or (not (file-exists-p newname))
1042 (yes-or-no-p
1043 (format "Target file %s exists; proceed? " newname)))
1044 (when (file-exists-p buffer-file-name)
1045 (rename-file buffer-file-name newname t))
1046 (set-visited-file-name newname))))
1047 (`?b (save-excursion
1048 (goto-char name-start)
1049 (delete-region name-start name-end)
1050 (insert file)))))))))
1051
1052 (defun octave-update-function-file-comment (beg end)
1053 "Query replace function names in function file comment."
1054 (interactive
1055 (progn
1056 (barf-if-buffer-read-only)
1057 (if (use-region-p)
1058 (list (region-beginning) (region-end))
1059 (or (octave-function-file-comment)
1060 (error "No function file comment found")))))
1061 (save-excursion
1062 (let* ((bounds (or (octave-function-file-p)
1063 (error "Not in a function file buffer")))
1064 (func (if (cddr bounds)
1065 (apply #'buffer-substring (cddr bounds))
1066 (error "Function name not found")))
1067 (old-func (progn
1068 (goto-char beg)
1069 (when (re-search-forward
1070 "[=}]\\s-*\\(\\(?:\\sw\\|\\s_\\)+\\)\\_>"
1071 (min (line-end-position 4) end)
1072 t)
1073 (match-string 1))))
1074 (old-func (read-string (format (if old-func
1075 "Name to replace (default %s): "
1076 "Name to replace: ")
1077 old-func)
1078 nil nil old-func)))
1079 (if (and func old-func (not (equal func old-func)))
1080 (perform-replace old-func func 'query
1081 nil 'delimited nil nil beg end)
1082 (message "Function names match")))))
1083
1084 (defface octave-function-comment-block
1085 '((t (:inherit font-lock-doc-face)))
1086 "Face used to highlight function comment block."
1087 :group 'octave)
1088
1089 (eval-when-compile (require 'texinfo))
1090
1091 (defun octave-font-lock-texinfo-comment ()
1092 (let ((kws
1093 (eval-when-compile
1094 (delq nil (mapcar
1095 (lambda (kw)
1096 (if (numberp (nth 1 kw))
1097 `(,(nth 0 kw) ,(nth 1 kw) ,(nth 2 kw) prepend)
1098 (message "Ignoring Texinfo highlight: %S" kw)))
1099 texinfo-font-lock-keywords)))))
1100 (font-lock-add-keywords
1101 nil
1102 `((,(lambda (limit)
1103 (while (and (< (point) limit)
1104 (search-forward "-*- texinfo -*-" limit t)
1105 (octave-in-comment-p))
1106 (let ((beg (nth 8 (syntax-ppss)))
1107 (end (progn
1108 (octave-skip-comment-forward (point-max))
1109 (point))))
1110 (put-text-property beg end 'font-lock-multiline t)
1111 (font-lock-prepend-text-property
1112 beg end 'face 'octave-function-comment-block)
1113 (dolist (kw kws)
1114 (goto-char beg)
1115 (while (re-search-forward (car kw) end 'move)
1116 (font-lock-apply-highlight (cdr kw))))))
1117 nil)))
1118 'append)))
1119
1120 \f
1121 ;;; Indentation
1122
1123 (defun octave-indent-new-comment-line (&optional soft)
1124 ;; FIXME: C-M-j should probably be bound globally to a function like
1125 ;; this one.
1126 "Break Octave line at point, continuing comment if within one.
1127 Insert `octave-continuation-string' before breaking the line
1128 unless inside a list. Signal an error if within a single-quoted
1129 string."
1130 (interactive)
1131 (funcall comment-line-break-function soft))
1132
1133 (defun octave--indent-new-comment-line (orig &rest args)
1134 (cond
1135 ((octave-in-comment-p) nil)
1136 ((eq (octave-in-string-p) ?')
1137 (error "Cannot split a single-quoted string"))
1138 ((eq (octave-in-string-p) ?\")
1139 (insert octave-continuation-string))
1140 (t
1141 (delete-horizontal-space)
1142 (unless (and (cadr (syntax-ppss))
1143 (eq (char-after (cadr (syntax-ppss))) ?\())
1144 (insert " " octave-continuation-string))))
1145 (apply orig args)
1146 (indent-according-to-mode))
1147
1148 (define-obsolete-function-alias
1149 'octave-indent-defun 'prog-indent-sexp "24.4")
1150
1151 \f
1152 ;;; Motion
1153 (defun octave-next-code-line (&optional arg)
1154 "Move ARG lines of Octave code forward (backward if ARG is negative).
1155 Skips past all empty and comment lines. Default for ARG is 1.
1156
1157 On success, return 0. Otherwise, go as far as possible and return -1."
1158 (interactive "p")
1159 (or arg (setq arg 1))
1160 (beginning-of-line)
1161 (let ((n 0)
1162 (inc (if (> arg 0) 1 -1)))
1163 (while (and (/= arg 0) (= n 0))
1164 (setq n (forward-line inc))
1165 (while (and (= n 0)
1166 (looking-at "\\s-*\\($\\|\\s<\\)"))
1167 (setq n (forward-line inc)))
1168 (setq arg (- arg inc)))
1169 n))
1170
1171 (defun octave-previous-code-line (&optional arg)
1172 "Move ARG lines of Octave code backward (forward if ARG is negative).
1173 Skips past all empty and comment lines. Default for ARG is 1.
1174
1175 On success, return 0. Otherwise, go as far as possible and return -1."
1176 (interactive "p")
1177 (or arg (setq arg 1))
1178 (octave-next-code-line (- arg)))
1179
1180 (defun octave-beginning-of-line ()
1181 "Move point to beginning of current Octave line.
1182 If on an empty or comment line, go to the beginning of that line.
1183 Otherwise, move backward to the beginning of the first Octave code line
1184 which is not inside a continuation statement, i.e., which does not
1185 follow a code line ending with `...' or is inside an open
1186 parenthesis list."
1187 (interactive)
1188 (beginning-of-line)
1189 (unless (looking-at "\\s-*\\($\\|\\s<\\)")
1190 (while (or (when (cadr (syntax-ppss))
1191 (goto-char (cadr (syntax-ppss)))
1192 (beginning-of-line)
1193 t)
1194 (and (or (looking-at "\\s-*\\($\\|\\s<\\)")
1195 (save-excursion
1196 (if (zerop (octave-previous-code-line))
1197 (looking-at octave-continuation-regexp))))
1198 (zerop (forward-line -1)))))))
1199
1200 (defun octave-end-of-line ()
1201 "Move point to end of current Octave line.
1202 If on an empty or comment line, go to the end of that line.
1203 Otherwise, move forward to the end of the first Octave code line which
1204 does not end with `...' or is inside an open parenthesis list."
1205 (interactive)
1206 (end-of-line)
1207 (unless (save-excursion
1208 (beginning-of-line)
1209 (looking-at "\\s-*\\($\\|\\s<\\)"))
1210 (while (or (when (cadr (syntax-ppss))
1211 (condition-case nil
1212 (progn
1213 (up-list 1)
1214 (end-of-line)
1215 t)
1216 (error nil)))
1217 (and (save-excursion
1218 (beginning-of-line)
1219 (or (looking-at "\\s-*\\($\\|\\s<\\)")
1220 (looking-at octave-continuation-regexp)))
1221 (zerop (forward-line 1)))))
1222 (end-of-line)))
1223
1224 (defun octave-mark-block ()
1225 "Put point at the beginning of this Octave block, mark at the end.
1226 The block marked is the one that contains point or follows point."
1227 (interactive)
1228 (if (and (looking-at "\\sw\\|\\s_")
1229 (looking-back "\\sw\\|\\s_" (1- (point))))
1230 (skip-syntax-forward "w_"))
1231 (unless (or (looking-at "\\s(")
1232 (save-excursion
1233 (let* ((token (funcall smie-forward-token-function))
1234 (level (assoc token smie-grammar)))
1235 (and level (not (numberp (cadr level)))))))
1236 (backward-up-list 1))
1237 (mark-sexp))
1238
1239 (defun octave-beginning-of-defun (&optional arg)
1240 "Octave-specific `beginning-of-defun-function' (which see)."
1241 (or arg (setq arg 1))
1242 ;; Move out of strings or comments.
1243 (when (octave-in-string-or-comment-p)
1244 (goto-char (octave-in-string-or-comment-p)))
1245 (letrec ((orig (point))
1246 (toplevel (lambda (pos)
1247 (condition-case nil
1248 (progn
1249 (backward-up-list 1)
1250 (funcall toplevel (point)))
1251 (scan-error pos)))))
1252 (goto-char (funcall toplevel (point)))
1253 (when (and (> arg 0) (/= orig (point)))
1254 (setq arg (1- arg)))
1255 (forward-sexp (- arg))
1256 (and (< arg 0) (forward-sexp -1))
1257 (/= orig (point))))
1258
1259 (defun octave-fill-paragraph (&optional _arg)
1260 "Fill paragraph of Octave code, handling Octave comments."
1261 ;; FIXME: difference with generic fill-paragraph:
1262 ;; - code lines are only split, never joined.
1263 ;; - \n that end comments are never removed.
1264 ;; - insert continuation marker when splitting code lines.
1265 (interactive "P")
1266 (save-excursion
1267 (let ((end (progn (forward-paragraph) (copy-marker (point) t)))
1268 (beg (progn
1269 (forward-paragraph -1)
1270 (skip-chars-forward " \t\n")
1271 (beginning-of-line)
1272 (point)))
1273 (cfc (current-fill-column))
1274 comment-prefix)
1275 (goto-char beg)
1276 (while (< (point) end)
1277 (condition-case nil
1278 (indent-according-to-mode)
1279 (error nil))
1280 (move-to-column cfc)
1281 ;; First check whether we need to combine non-empty comment lines
1282 (if (and (< (current-column) cfc)
1283 (octave-in-comment-p)
1284 (not (save-excursion
1285 (beginning-of-line)
1286 (looking-at "^\\s-*\\s<+\\s-*$"))))
1287 ;; This is a nonempty comment line which does not extend
1288 ;; past the fill column. If it is followed by a nonempty
1289 ;; comment line with the same comment prefix, try to
1290 ;; combine them, and repeat this until either we reach the
1291 ;; fill-column or there is nothing more to combine.
1292 (progn
1293 ;; Get the comment prefix
1294 (save-excursion
1295 (beginning-of-line)
1296 (while (and (re-search-forward "\\s<+")
1297 (not (octave-in-comment-p))))
1298 (setq comment-prefix (match-string 0)))
1299 ;; And keep combining ...
1300 (while (and (< (current-column) cfc)
1301 (save-excursion
1302 (forward-line 1)
1303 (and (looking-at
1304 (concat "^\\s-*"
1305 comment-prefix
1306 "\\S<"))
1307 (not (looking-at
1308 (concat "^\\s-*"
1309 comment-prefix
1310 "\\s-*$"))))))
1311 (delete-char 1)
1312 (re-search-forward comment-prefix)
1313 (delete-region (match-beginning 0) (match-end 0))
1314 (fixup-whitespace)
1315 (move-to-column cfc))))
1316 ;; We might also try to combine continued code lines> Perhaps
1317 ;; some other time ...
1318 (skip-chars-forward "^ \t\n")
1319 (delete-horizontal-space)
1320 (if (or (< (current-column) cfc)
1321 (and (= (current-column) cfc) (eolp)))
1322 (forward-line 1)
1323 (if (not (eolp)) (insert " "))
1324 (or (funcall normal-auto-fill-function)
1325 (forward-line 1))))
1326 t)))
1327
1328 ;;; Completions
1329
1330 (defun octave-completion-at-point ()
1331 "Find the text to complete and the corresponding table."
1332 (let* ((beg (save-excursion (skip-syntax-backward "w_") (point)))
1333 (end (point)))
1334 (if (< beg (point))
1335 ;; Extend region past point, if applicable.
1336 (save-excursion (skip-syntax-forward "w_")
1337 (setq end (point))))
1338 (when (> end beg)
1339 (list beg end (or (and inferior-octave-process
1340 (process-live-p inferior-octave-process)
1341 inferior-octave-completion-table)
1342 octave-reserved-words)))))
1343
1344 (define-obsolete-function-alias 'octave-complete-symbol
1345 'completion-at-point "24.1")
1346 \f
1347 ;;; Electric characters && friends
1348 (define-skeleton octave-insert-defun
1349 "Insert an Octave function skeleton.
1350 Prompt for the function's name, arguments and return values (to be
1351 entered without parens)."
1352 (let* ((defname (file-name-sans-extension (buffer-name)))
1353 (name (read-string (format "Function name (default %s): " defname)
1354 nil nil defname))
1355 (args (read-string "Arguments: "))
1356 (vals (read-string "Return values: ")))
1357 (format "%s%s (%s)"
1358 (cond
1359 ((string-equal vals "") vals)
1360 ((string-match "[ ,]" vals) (concat "[" vals "] = "))
1361 (t (concat vals " = ")))
1362 name
1363 args))
1364 \n octave-block-comment-start "usage: " str \n
1365 octave-block-comment-start '(delete-horizontal-space) \n
1366 octave-block-comment-start '(delete-horizontal-space) \n
1367 "function " > str \n
1368 _ \n
1369 "endfunction" > \n)
1370 \f
1371 ;;; Communication with the inferior Octave process
1372 (defun octave-kill-process ()
1373 "Kill inferior Octave process and its buffer."
1374 (interactive)
1375 (if inferior-octave-process
1376 (progn
1377 (process-send-string inferior-octave-process "quit;\n")
1378 (accept-process-output inferior-octave-process)))
1379 (if inferior-octave-buffer
1380 (kill-buffer inferior-octave-buffer)))
1381
1382 (defun octave-show-process-buffer ()
1383 "Make sure that `inferior-octave-buffer' is displayed."
1384 (interactive)
1385 (if (get-buffer inferior-octave-buffer)
1386 (display-buffer inferior-octave-buffer)
1387 (message "No buffer named %s" inferior-octave-buffer)))
1388
1389 (defun octave-hide-process-buffer ()
1390 "Delete all windows that display `inferior-octave-buffer'."
1391 (interactive)
1392 (if (get-buffer inferior-octave-buffer)
1393 (delete-windows-on inferior-octave-buffer)
1394 (message "No buffer named %s" inferior-octave-buffer)))
1395
1396 (defun octave-send-region (beg end)
1397 "Send current region to the inferior Octave process."
1398 (interactive "r")
1399 (inferior-octave t)
1400 (let ((proc inferior-octave-process)
1401 (string (buffer-substring-no-properties beg end))
1402 line)
1403 (with-current-buffer inferior-octave-buffer
1404 (setq inferior-octave-output-list nil)
1405 (while (not (string-equal string ""))
1406 (if (string-match "\n" string)
1407 (setq line (substring string 0 (match-beginning 0))
1408 string (substring string (match-end 0)))
1409 (setq line string string ""))
1410 (setq inferior-octave-receive-in-progress t)
1411 (inferior-octave-send-list-and-digest (list (concat line "\n")))
1412 (while inferior-octave-receive-in-progress
1413 (accept-process-output proc))
1414 (insert-before-markers
1415 (mapconcat 'identity
1416 (append
1417 (if octave-send-echo-input (list line) (list ""))
1418 inferior-octave-output-list
1419 (list inferior-octave-output-string))
1420 "\n")))))
1421 (if octave-send-show-buffer
1422 (display-buffer inferior-octave-buffer)))
1423
1424 (defun octave-send-block ()
1425 "Send current Octave block to the inferior Octave process."
1426 (interactive)
1427 (save-excursion
1428 (octave-mark-block)
1429 (octave-send-region (point) (mark))))
1430
1431 (defun octave-send-defun ()
1432 "Send current Octave function to the inferior Octave process."
1433 (interactive)
1434 (save-excursion
1435 (mark-defun)
1436 (octave-send-region (point) (mark))))
1437
1438 (defun octave-send-line (&optional arg)
1439 "Send current Octave code line to the inferior Octave process.
1440 With positive prefix ARG, send that many lines.
1441 If `octave-send-line-auto-forward' is non-nil, go to the next unsent
1442 code line."
1443 (interactive "P")
1444 (or arg (setq arg 1))
1445 (if (> arg 0)
1446 (let (beg end)
1447 (beginning-of-line)
1448 (setq beg (point))
1449 (octave-next-code-line (- arg 1))
1450 (end-of-line)
1451 (setq end (point))
1452 (if octave-send-line-auto-forward
1453 (octave-next-code-line 1))
1454 (octave-send-region beg end))))
1455
1456 (defun octave-eval-print-last-sexp ()
1457 "Evaluate Octave sexp before point and print value into current buffer."
1458 (interactive)
1459 (inferior-octave t)
1460 (let ((standard-output (current-buffer))
1461 (print-escape-newlines nil)
1462 (opoint (point)))
1463 (terpri)
1464 (prin1
1465 (save-excursion
1466 (forward-sexp -1)
1467 (inferior-octave-send-list-and-digest
1468 (list (concat (buffer-substring-no-properties (point) opoint)
1469 "\n")))
1470 (mapconcat 'identity inferior-octave-output-list "\n")))
1471 (terpri)))
1472
1473 \f
1474
1475 (defcustom octave-eldoc-message-style 'auto
1476 "Octave eldoc message style: auto, oneline, multiline."
1477 :type '(choice (const :tag "Automatic" auto)
1478 (const :tag "One Line" oneline)
1479 (const :tag "Multi Line" multiline))
1480 :group 'octave
1481 :version "24.4")
1482
1483 ;; (FN SIGNATURE1 SIGNATURE2 ...)
1484 (defvar octave-eldoc-cache nil)
1485
1486 (defun octave-eldoc-function-signatures (fn)
1487 (unless (equal fn (car octave-eldoc-cache))
1488 (inferior-octave-send-list-and-digest
1489 (list (format "\
1490 if ismember(exist(\"%s\"), [2 3 5 103]) print_usage(\"%s\") endif\n"
1491 fn fn)))
1492 (let (result)
1493 (dolist (line inferior-octave-output-list)
1494 (when (string-match
1495 "\\s-*\\(?:--[^:]+\\|usage\\):\\s-*\\(.*\\)$"
1496 line)
1497 (push (match-string 1 line) result)))
1498 (setq octave-eldoc-cache
1499 (cons (substring-no-properties fn)
1500 (nreverse result)))))
1501 (cdr octave-eldoc-cache))
1502
1503 (defun octave-eldoc-function ()
1504 "A function for `eldoc-documentation-function' (which see)."
1505 (when (and inferior-octave-process
1506 (process-live-p inferior-octave-process))
1507 (let* ((ppss (syntax-ppss))
1508 (paren-pos (cadr ppss))
1509 (fn (save-excursion
1510 (if (and paren-pos
1511 ;; PAREN-POS must be after the prompt
1512 (>= paren-pos
1513 (if (eq (get-buffer-process (current-buffer))
1514 inferior-octave-process)
1515 (process-mark inferior-octave-process)
1516 (point-min)))
1517 (or (not (eq (get-buffer-process (current-buffer))
1518 inferior-octave-process))
1519 (< (process-mark inferior-octave-process)
1520 paren-pos))
1521 (eq (char-after paren-pos) ?\())
1522 (goto-char paren-pos)
1523 (setq paren-pos nil))
1524 (when (or (< (skip-syntax-backward "-") 0) paren-pos)
1525 (thing-at-point 'symbol))))
1526 (sigs (and fn (octave-eldoc-function-signatures fn)))
1527 (oneline (mapconcat 'identity sigs
1528 (propertize " | " 'face 'warning)))
1529 (multiline (mapconcat (lambda (s) (concat "-- " s)) sigs "\n")))
1530 ;;
1531 ;; Return the value according to style.
1532 (pcase octave-eldoc-message-style
1533 (`auto (if (< (length oneline) (window-width (minibuffer-window)))
1534 oneline
1535 multiline))
1536 (`oneline oneline)
1537 (`multiline multiline)))))
1538
1539 (defcustom octave-help-buffer "*Octave Help*"
1540 "Buffer name for `octave-help'."
1541 :type 'string
1542 :group 'octave
1543 :version "24.4")
1544
1545 (define-button-type 'octave-help-file
1546 'follow-link t
1547 'action #'help-button-action
1548 'help-function 'octave-find-definition)
1549
1550 (define-button-type 'octave-help-function
1551 'follow-link t
1552 'action (lambda (b)
1553 (octave-help
1554 (buffer-substring (button-start b) (button-end b)))))
1555
1556 (defvar octave-help-mode-map
1557 (let ((map (make-sparse-keymap)))
1558 (define-key map "\M-." 'octave-find-definition)
1559 (define-key map "\C-hd" 'octave-help)
1560 map))
1561
1562 (define-derived-mode octave-help-mode help-mode "OctHelp"
1563 "Major mode for displaying Octave documentation."
1564 :abbrev-table nil
1565 :syntax-table octave-mode-syntax-table
1566 (eval-and-compile (require 'help-mode))
1567 ;; Mostly stolen from `help-make-xrefs'.
1568 (let ((inhibit-read-only t))
1569 (setq-local info-lookup-mode 'octave-mode)
1570 ;; Delete extraneous newlines at the end of the docstring
1571 (goto-char (point-max))
1572 (while (and (not (bobp)) (bolp))
1573 (delete-char -1))
1574 (insert "\n")
1575 (when (or help-xref-stack help-xref-forward-stack)
1576 (insert "\n"))
1577 (when help-xref-stack
1578 (help-insert-xref-button help-back-label 'help-back
1579 (current-buffer)))
1580 (when help-xref-forward-stack
1581 (when help-xref-stack
1582 (insert "\t"))
1583 (help-insert-xref-button help-forward-label 'help-forward
1584 (current-buffer)))
1585 (when (or help-xref-stack help-xref-forward-stack)
1586 (insert "\n"))))
1587
1588 (defvar octave-help-mode-finish-hook nil
1589 "Octave specific hook for `temp-buffer-show-hook'.")
1590
1591 (defun octave-help-mode-finish ()
1592 (when (eq major-mode 'octave-help-mode)
1593 (run-hooks 'octave-help-mode-finish-hook)))
1594
1595 (add-hook 'temp-buffer-show-hook 'octave-help-mode-finish)
1596
1597 (defun octave-help (fn)
1598 "Display the documentation of FN."
1599 (interactive (list (octave-completing-read)))
1600 (inferior-octave-send-list-and-digest
1601 (list (format "help \"%s\"\n" fn)))
1602 (let ((lines inferior-octave-output-list)
1603 (inhibit-read-only t))
1604 (when (string-match "error: \\(.*\\)$" (car lines))
1605 (error "%s" (match-string 1 (car lines))))
1606 (with-help-window octave-help-buffer
1607 (princ (mapconcat 'identity lines "\n"))
1608 (with-current-buffer octave-help-buffer
1609 ;; Bound to t so that `help-buffer' returns current buffer for
1610 ;; `help-setup-xref'.
1611 (let ((help-xref-following t))
1612 (help-setup-xref (list 'octave-help fn)
1613 (called-interactively-p 'interactive)))
1614 ;; Note: can be turned off by suppress_verbose_help_message.
1615 ;;
1616 ;; Remove boring trailing text: Additional help for built-in functions
1617 ;; and operators ...
1618 (goto-char (point-max))
1619 (when (search-backward "\n\n\n" nil t)
1620 (goto-char (match-beginning 0))
1621 (delete-region (point) (point-max)))
1622 ;; File name highlight
1623 (goto-char (point-min))
1624 (when (re-search-forward "from the file \\(.*\\)$"
1625 (line-end-position)
1626 t)
1627 (let* ((file (match-string 1))
1628 (dir (file-name-directory
1629 (directory-file-name (file-name-directory file)))))
1630 (replace-match "" nil nil nil 1)
1631 (insert "`")
1632 ;; Include the parent directory which may be regarded as
1633 ;; the category for the FN.
1634 (help-insert-xref-button (file-relative-name file dir)
1635 'octave-help-file fn)
1636 (insert "'")))
1637 ;; Make 'See also' clickable
1638 (with-syntax-table octave-mode-syntax-table
1639 (when (re-search-forward "^\\s-*See also:" nil t)
1640 (let ((end (or (save-excursion (re-search-forward "^\\s-*$" nil t))
1641 (point-max))))
1642 (while (re-search-forward "\\_<\\(?:\\sw\\|\\s_\\)+\\_>" end t)
1643 (make-text-button (match-beginning 0)
1644 ;; If the match ends with . exclude it.
1645 (if (eq (char-before (match-end 0)) ?.)
1646 (1- (match-end 0))
1647 (match-end 0))
1648 :type 'octave-help-function)))))
1649 (octave-help-mode)))))
1650
1651 (defcustom octave-source-directories nil
1652 "A list of directories for Octave sources.
1653 If the environment variable OCTAVE_SRCDIR is set, it is searched first."
1654 :type '(repeat directory)
1655 :group 'octave
1656 :version "24.4")
1657
1658 (defun octave-source-directories ()
1659 (let ((srcdir (or (and inferior-octave-process
1660 (process-get inferior-octave-process 'octave-srcdir))
1661 (getenv "OCTAVE_SRCDIR"))))
1662 (if srcdir
1663 (cons srcdir octave-source-directories)
1664 octave-source-directories)))
1665
1666 (defvar octave-find-definition-filename-function
1667 #'octave-find-definition-default-filename)
1668
1669 (defun octave-find-definition-default-filename (name)
1670 "Default value for `octave-find-definition-filename-function'."
1671 (pcase (file-name-extension name)
1672 (`"oct"
1673 (octave-find-definition-default-filename
1674 (concat "libinterp/dldfcn/"
1675 (file-name-sans-extension (file-name-nondirectory name))
1676 ".cc")))
1677 (`"cc"
1678 (let ((file (or (locate-file name (octave-source-directories))
1679 (locate-file (file-name-nondirectory name)
1680 (octave-source-directories)))))
1681 (or (and file (file-exists-p file))
1682 (error "File `%s' not found" name))
1683 file))
1684 (`"mex"
1685 (if (yes-or-no-p (format "File `%s' may be binary; open? "
1686 (file-name-nondirectory name)))
1687 name
1688 (user-error "Aborted")))
1689 (t name)))
1690
1691 (defvar find-tag-marker-ring)
1692
1693 (defun octave-find-definition (fn)
1694 "Find the definition of FN.
1695 Functions implemented in C++ can be found if
1696 `octave-source-directories' is set correctly."
1697 (interactive (list (octave-completing-read)))
1698 (inferior-octave-send-list-and-digest
1699 ;; help NAME is more verbose
1700 (list (format "\
1701 if iskeyword(\"%s\") disp(\"`%s' is a keyword\") else which(\"%s\") endif\n"
1702 fn fn fn)))
1703 (let* ((line (car inferior-octave-output-list))
1704 (file (when (and line (string-match "from the file \\(.*\\)$" line))
1705 (match-string 1 line))))
1706 (if (not file)
1707 (user-error "%s" (or line (format "`%s' not found" fn)))
1708 (require 'etags)
1709 (ring-insert find-tag-marker-ring (point-marker))
1710 (setq file (funcall octave-find-definition-filename-function file))
1711 (when file
1712 (find-file file)
1713 (octave-goto-function-definition fn)))))
1714
1715
1716 (provide 'octave)
1717 ;;; octave.el ends here