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