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