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