Replace "Maintainer: FSF" with the emacs-devel mailing address
[emacs.git] / lisp / progmodes / octave.el
blob123aac03eae343fda5a092540c2fb82f40a400a0
1 ;;; octave.el --- editing octave source files under emacs -*- lexical-binding: t; -*-
3 ;; Copyright (C) 1997, 2001-2014 Free Software Foundation, Inc.
5 ;; Author: Kurt Hornik <Kurt.Hornik@wu-wien.ac.at>
6 ;; John Eaton <jwe@octave.org>
7 ;; Maintainer: emacs-devel@gnu.org
8 ;; Keywords: languages
10 ;; This file is part of GNU Emacs.
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.
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.
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/>.
25 ;;; Commentary:
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.
31 ;; See the documentation of `octave-mode' and `run-octave' for further
32 ;; information on usage and customization.
34 ;;; Code:
35 (require 'comint)
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))))
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)
57 (define-obsolete-function-alias 'octave-submit-bug-report
58 'report-emacs-bug "24.4")
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.")
64 (defvar octave-comment-char ?#
65 "Character to start an Octave comment.")
67 (defvar octave-comment-start (char-to-string octave-comment-char)
68 "Octave-specific `comment-start' (which see).")
70 (defvar octave-comment-start-skip "\\(^\\|\\S<\\)\\(?:%!\\|\\s<+\\)\\s-*"
71 "Octave-specific `comment-start-skip' (which see).")
73 (defvar octave-begin-keywords
74 '("classdef" "do" "enumeration" "events" "for" "function" "if" "methods"
75 "parfor" "properties" "switch" "try" "unwind_protect" "while"))
77 (defvar octave-else-keywords
78 '("case" "catch" "else" "elseif" "otherwise" "unwind_protect_cleanup"))
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"))
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.")
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.")
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.")
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" (eldoc-mode 'toggle)
158 :style toggle :selected (bound-and-true-p eldoc-mode)
159 :help "Display function signatures after typing `SPC' or `('"]
160 ["Delimiter Matching" show-paren-mode
161 :style toggle :selected show-paren-mode
162 :help "Highlight matched pairs such as `if ... end'"
163 :visible (fboundp 'smie--matching-block-data)]
164 ["Auto Fill" auto-fill-mode
165 :style toggle :selected auto-fill-function
166 :help "Automatic line breaking"]
167 ["Electric Layout" electric-layout-mode
168 :style toggle :selected electric-layout-mode
169 :help "Automatically insert newlines around some chars"]
170 "---"
171 ("Debug"
172 ["Send Current Line" octave-send-line t]
173 ["Send Current Block" octave-send-block t]
174 ["Send Current Function" octave-send-defun t]
175 ["Send Region" octave-send-region t]
176 ["Send Buffer" octave-send-buffer t]
177 ["Source Current File" octave-source-file t]
178 ["Show Process Buffer" octave-show-process-buffer t]
179 ["Hide Process Buffer" octave-hide-process-buffer t]
180 ["Kill Process" octave-kill-process t])
181 "---"
182 ["Octave Mode Manual" (info "(octave-mode)Top") t]
183 ["Customize Octave" (customize-group 'octave) t]
184 ["Submit Bug Report" report-emacs-bug t]))
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.")
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")
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)
232 (defcustom octave-block-offset 2
233 "Extra indentation applied to statements in Octave block structures."
234 :type 'integer
235 :group 'octave)
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.")
241 (defcustom octave-continuation-offset 4
242 "Extra indentation applied to Octave continuation lines."
243 :type 'integer
244 :group 'octave)
246 (eval-and-compile
247 (defconst octave-continuation-marker-regexp "\\\\\\|\\.\\.\\."))
249 (defvar octave-continuation-regexp
250 (concat "[^#%\n]*\\(" octave-continuation-marker-regexp
251 "\\)\\s-*\\(\\s<.*\\)?$"))
253 ;; Char \ is considered a bad decision for continuing a line.
254 (defconst octave-continuation-string "..."
255 "Character string used for Octave continuation lines.")
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'.")
263 (defcustom octave-mode-hook nil
264 "Hook to be run when Octave mode is started."
265 :type 'hook
266 :group 'octave)
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)
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)
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)
285 ;;; SMIE indentation
287 (require 'smie)
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 "...")))
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))
353 (defconst octave-smie-grammar
354 (smie-prec2->grammar
355 (smie-merge-prec2s
356 (smie-bnf->prec2 octave-smie-bnf-table
357 '((assoc "\n" ";")))
359 (smie-precs->prec2 octave-operator-table))))
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).
365 (defconst octave-operator-regexp
366 (regexp-opt (remove "\n" (apply 'append
367 (mapcar 'cdr octave-operator-table)))))
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)
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))
394 (smie-default-backward-token)))))
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))
427 (smie-default-forward-token))))
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-rule-parent-p "switch") 4)
448 nil))))
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,\\}")
458 ;; Exclude %{, %} and %!.
459 ((and (looking-at-p "\\s<\\(?:[^{}!]\\|$\\)")
460 (not (looking-at-p "\\(\\s<\\)\\1")))
461 (comment-choose-indent)))))
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.")
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))
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 "\"'")))))
522 (defvar electric-layout-rules)
524 ;;;###autoload
525 (define-derived-mode octave-mode prog-mode "Octave"
526 "Major mode for editing Octave code.
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.
533 See Info node `(octave-mode) Using Octave Mode' for more details.
535 Key bindings:
536 \\{octave-mode-map}"
537 :abbrev-table octave-abbrev-table
538 :group 'octave
540 (smie-setup octave-smie-grammar #'octave-smie-rules
541 :forward-token #'octave-smie-forward-token
542 :backward-token #'octave-smie-backward-token)
543 (setq-local smie-indent-basic 'octave-block-offset)
544 (add-hook 'smie-indent-functions #'octave-indent-comment nil t)
546 (setq-local smie-blink-matching-triggers
547 (cons ?\; smie-blink-matching-triggers))
548 (unless octave-blink-matching-block
549 (remove-hook 'post-self-insert-hook #'smie-blink-matching-open 'local))
551 (setq-local electric-indent-chars
552 (cons ?\; electric-indent-chars))
553 ;; IIUC matlab-mode takes the opposite approach: it makes RET insert
554 ;; a ";" at those places where it's correct (i.e. outside of parens).
555 (setq-local electric-layout-rules '((?\; . after)))
557 (setq-local comment-use-syntax t)
558 (setq-local comment-start octave-comment-start)
559 (setq-local comment-end "")
560 (setq-local comment-start-skip octave-comment-start-skip)
561 (setq-local comment-add 1)
563 (setq-local parse-sexp-ignore-comments t)
564 (setq-local paragraph-start (concat "\\s-*$\\|" page-delimiter))
565 (setq-local paragraph-separate paragraph-start)
566 (setq-local paragraph-ignore-fill-prefix t)
567 (setq-local fill-paragraph-function 'octave-fill-paragraph)
569 (setq-local fill-nobreak-predicate
570 (lambda () (eq (octave-in-string-p) ?')))
571 (with-no-warnings
572 (if (fboundp 'add-function) ; new in 24.4
573 (add-function :around (local 'comment-line-break-function)
574 #'octave--indent-new-comment-line)
575 (setq-local comment-line-break-function
576 (apply-partially #'octave--indent-new-comment-line
577 #'comment-indent-new-line))))
579 (setq font-lock-defaults '(octave-font-lock-keywords))
581 (setq-local syntax-propertize-function #'octave-syntax-propertize-function)
583 (setq-local imenu-generic-expression octave-mode-imenu-generic-expression)
584 (setq-local imenu-case-fold-search nil)
586 (setq-local add-log-current-defun-function #'octave-add-log-current-defun)
588 (add-hook 'completion-at-point-functions 'octave-completion-at-point nil t)
589 (add-hook 'before-save-hook 'octave-sync-function-file-names nil t)
590 (setq-local beginning-of-defun-function 'octave-beginning-of-defun)
591 (and octave-font-lock-texinfo-comment (octave-font-lock-texinfo-comment))
592 (setq-local eldoc-documentation-function 'octave-eldoc-function)
594 (easy-menu-add octave-mode-menu))
597 (defcustom inferior-octave-program "octave"
598 "Program invoked by `inferior-octave'."
599 :type 'string
600 :group 'octave)
602 (defcustom inferior-octave-buffer "*Inferior Octave*"
603 "Name of buffer for running an inferior Octave process."
604 :type 'string
605 :group 'octave)
607 (defcustom inferior-octave-prompt
608 ;; For Octave >= 3.8, default is always 'octave', see
609 ;; http://hg.savannah.gnu.org/hgweb/octave/rev/708173343c50
610 "\\(?:^octave\\(?:.bin\\|.exe\\)?\\(?:-[.0-9]+\\)?\\(?::[0-9]+\\)?\\|^debug\\|^\\)>+ "
611 "Regexp to match prompts for the inferior Octave process."
612 :type 'regexp
613 :group 'octave)
615 (defcustom inferior-octave-prompt-read-only comint-prompt-read-only
616 "If non-nil, the Octave prompt is read only.
617 See `comint-prompt-read-only' for details."
618 :type 'boolean
619 :group 'octave
620 :version "24.4")
622 (defcustom inferior-octave-startup-file
623 (let ((n (file-name-nondirectory inferior-octave-program)))
624 (locate-user-emacs-file (format "init_%s.m" n) (format ".emacs-%s" n)))
625 "Name of the inferior Octave startup file.
626 The contents of this file are sent to the inferior Octave process on
627 startup."
628 :type '(choice (const :tag "None" nil) file)
629 :group 'octave
630 :version "24.4")
632 (defcustom inferior-octave-startup-args '("-i" "--no-line-editing")
633 "List of command line arguments for the inferior Octave process.
634 For example, for suppressing the startup message and using `traditional'
635 mode, include \"-q\" and \"--traditional\"."
636 :type '(repeat string)
637 :group 'octave
638 :version "24.4")
640 (defcustom inferior-octave-mode-hook nil
641 "Hook to be run when Inferior Octave mode is started."
642 :type 'hook
643 :group 'octave)
645 (defcustom inferior-octave-error-regexp-alist
646 '(("error:\\s-*\\(.*?\\) at line \\([0-9]+\\), column \\([0-9]+\\)"
647 1 2 3 2 1)
648 ("warning:\\s-*\\([^:\n]+\\):.*at line \\([0-9]+\\), column \\([0-9]+\\)"
649 1 2 3 1 1))
650 "Value for `compilation-error-regexp-alist' in inferior octave."
651 :version "24.4"
652 :type '(repeat (choice (symbol :tag "Predefined symbol")
653 (sexp :tag "Error specification")))
654 :group 'octave)
656 (defvar inferior-octave-compilation-font-lock-keywords
657 '(("\\_<PASS\\_>" . compilation-info-face)
658 ("\\_<FAIL\\_>" . compilation-error-face)
659 ("\\_<\\(warning\\):" 1 compilation-warning-face)
660 ("\\_<\\(error\\):" 1 compilation-error-face)
661 ("^\\s-*!!!!!.*\\|^.*failed$" . compilation-error-face))
662 "Value for `compilation-mode-font-lock-keywords' in inferior octave.")
664 (defvar inferior-octave-process nil)
666 (defvar inferior-octave-mode-map
667 (let ((map (make-sparse-keymap)))
668 (set-keymap-parent map comint-mode-map)
669 (define-key map "\M-." 'octave-find-definition)
670 (define-key map "\t" 'completion-at-point)
671 (define-key map "\C-hd" 'octave-help)
672 (define-key map "\C-ha" 'octave-lookfor)
673 ;; Same as in `shell-mode'.
674 (define-key map "\M-?" 'comint-dynamic-list-filename-completions)
675 (define-key map "\C-c\C-l" 'inferior-octave-dynamic-list-input-ring)
676 (define-key map [menu-bar inout list-history]
677 '("List Input History" . inferior-octave-dynamic-list-input-ring))
678 map)
679 "Keymap used in Inferior Octave mode.")
681 (defvar inferior-octave-mode-syntax-table
682 (let ((table (make-syntax-table octave-mode-syntax-table)))
683 table)
684 "Syntax table in use in `inferior-octave-mode' buffers.")
686 (defvar inferior-octave-font-lock-keywords
687 (list
688 (cons inferior-octave-prompt 'font-lock-type-face))
689 ;; Could certainly do more font locking in inferior Octave ...
690 "Additional expressions to highlight in Inferior Octave mode.")
692 (defvar inferior-octave-output-list nil)
693 (defvar inferior-octave-output-string nil)
694 (defvar inferior-octave-receive-in-progress nil)
696 (define-obsolete-variable-alias 'inferior-octave-startup-hook
697 'inferior-octave-mode-hook "24.4")
699 (defvar inferior-octave-dynamic-complete-functions
700 '(inferior-octave-completion-at-point comint-filename-completion)
701 "List of functions called to perform completion for inferior Octave.
702 This variable is used to initialize `comint-dynamic-complete-functions'
703 in the Inferior Octave buffer.")
705 (defvar info-lookup-mode)
706 (defvar compilation-error-regexp-alist)
707 (defvar compilation-mode-font-lock-keywords)
709 (declare-function compilation-forget-errors "compile" ())
711 (defun inferior-octave-process-live-p ()
712 (process-live-p inferior-octave-process))
714 (define-derived-mode inferior-octave-mode comint-mode "Inferior Octave"
715 "Major mode for interacting with an inferior Octave process.
717 See Info node `(octave-mode) Running Octave from Within Emacs' for more
718 details.
720 Key bindings:
721 \\{inferior-octave-mode-map}"
722 :abbrev-table octave-abbrev-table
723 :group 'octave
725 (setq comint-prompt-regexp inferior-octave-prompt)
727 (setq-local comment-use-syntax t)
728 (setq-local comment-start octave-comment-start)
729 (setq-local comment-end "")
730 (setq comment-column 32)
731 (setq-local comment-start-skip octave-comment-start-skip)
733 (setq font-lock-defaults '(inferior-octave-font-lock-keywords nil nil))
735 (setq-local info-lookup-mode 'octave-mode)
736 (setq-local eldoc-documentation-function 'octave-eldoc-function)
738 (setq comint-input-ring-file-name
739 (or (getenv "OCTAVE_HISTFILE") "~/.octave_hist")
740 comint-input-ring-size (or (getenv "OCTAVE_HISTSIZE") 1024))
741 (comint-read-input-ring t)
742 (setq-local comint-dynamic-complete-functions
743 inferior-octave-dynamic-complete-functions)
744 (setq-local comint-prompt-read-only inferior-octave-prompt-read-only)
745 (add-hook 'comint-input-filter-functions
746 'inferior-octave-directory-tracker nil t)
747 ;; http://thread.gmane.org/gmane.comp.gnu.octave.general/48572
748 (add-hook 'window-configuration-change-hook
749 'inferior-octave-track-window-width-change nil t)
750 (setq-local compilation-error-regexp-alist inferior-octave-error-regexp-alist)
751 (setq-local compilation-mode-font-lock-keywords
752 inferior-octave-compilation-font-lock-keywords)
753 (compilation-shell-minor-mode 1)
754 (compilation-forget-errors))
756 ;;;###autoload
757 (defun inferior-octave (&optional arg)
758 "Run an inferior Octave process, I/O via `inferior-octave-buffer'.
759 This buffer is put in Inferior Octave mode. See `inferior-octave-mode'.
761 Unless ARG is non-nil, switches to this buffer.
763 The elements of the list `inferior-octave-startup-args' are sent as
764 command line arguments to the inferior Octave process on startup.
766 Additional commands to be executed on startup can be provided either in
767 the file specified by `inferior-octave-startup-file' or by the default
768 startup file, `~/.emacs-octave'."
769 (interactive "P")
770 (let ((buffer (get-buffer-create inferior-octave-buffer)))
771 (unless arg
772 (pop-to-buffer buffer))
773 (unless (comint-check-proc buffer)
774 (with-current-buffer buffer
775 (inferior-octave-startup)
776 (inferior-octave-mode)))
777 buffer))
779 ;;;###autoload
780 (defalias 'run-octave 'inferior-octave)
782 (defun inferior-octave-startup ()
783 "Start an inferior Octave process."
784 (let ((proc (comint-exec-1
785 (substring inferior-octave-buffer 1 -1)
786 inferior-octave-buffer
787 inferior-octave-program
788 (append
789 inferior-octave-startup-args
790 ;; --no-gui is introduced in Octave > 3.7
791 (and (not (member "--no-gui" inferior-octave-startup-args))
792 (zerop (process-file inferior-octave-program
793 nil nil nil "--no-gui" "--help"))
794 '("--no-gui"))))))
795 (set-process-filter proc 'inferior-octave-output-digest)
796 (setq inferior-octave-process proc
797 inferior-octave-output-list nil
798 inferior-octave-output-string nil
799 inferior-octave-receive-in-progress t)
801 ;; This may look complicated ... However, we need to make sure that
802 ;; we additional startup code only AFTER Octave is ready (otherwise,
803 ;; output may be mixed up). Hence, we need to digest the Octave
804 ;; output to see when it issues a prompt.
805 (while inferior-octave-receive-in-progress
806 (unless (inferior-octave-process-live-p)
807 ;; Spit out the error messages.
808 (when inferior-octave-output-list
809 (princ (concat (mapconcat 'identity inferior-octave-output-list "\n")
810 "\n")
811 (process-mark inferior-octave-process)))
812 (error "Process `%s' died" inferior-octave-process))
813 (accept-process-output inferior-octave-process))
814 (goto-char (point-max))
815 (set-marker (process-mark proc) (point))
816 (insert-before-markers
817 (concat
818 (if (not (bobp)) "\f\n")
819 (if inferior-octave-output-list
820 (concat (mapconcat
821 'identity inferior-octave-output-list "\n")
822 "\n"))))
824 ;; An empty secondary prompt, as e.g. obtained by '--braindead',
825 ;; means trouble.
826 (inferior-octave-send-list-and-digest (list "PS2\n"))
827 (when (string-match "\\(PS2\\|ans\\) = *$"
828 (car inferior-octave-output-list))
829 (inferior-octave-send-list-and-digest (list "PS2 ('> ');\n")))
831 (inferior-octave-send-list-and-digest
832 (list "disp (getenv ('OCTAVE_SRCDIR'))\n"))
833 (process-put proc 'octave-srcdir
834 (unless (equal (car inferior-octave-output-list) "")
835 (car inferior-octave-output-list)))
837 ;; O.K., now we are ready for the Inferior Octave startup commands.
838 (inferior-octave-send-list-and-digest
839 (list "more off;\n"
840 (unless (equal inferior-octave-output-string ">> ")
841 ;; See http://hg.savannah.gnu.org/hgweb/octave/rev/708173343c50
842 "PS1 ('octave> ');\n")
843 (when (and inferior-octave-startup-file
844 (file-exists-p inferior-octave-startup-file))
845 (format "source ('%s');\n" inferior-octave-startup-file))))
846 (when inferior-octave-output-list
847 (insert-before-markers
848 (mapconcat 'identity inferior-octave-output-list "\n")))
850 ;; And finally, everything is back to normal.
851 (set-process-filter proc 'comint-output-filter)
852 ;; Just in case, to be sure a cd in the startup file won't have
853 ;; detrimental effects.
854 (with-demoted-errors (inferior-octave-resync-dirs))
855 ;; Generate a proper prompt, which is critical to
856 ;; `comint-history-isearch-backward-regexp'. Bug#14433.
857 (comint-send-string proc "\n")))
859 (defun inferior-octave-completion-table ()
860 (completion-table-with-cache
861 (lambda (command)
862 (inferior-octave-send-list-and-digest
863 (list (format "completion_matches ('%s');\n" command)))
864 (delete-consecutive-dups
865 (sort inferior-octave-output-list 'string-lessp)))))
867 (defun inferior-octave-completion-at-point ()
868 "Return the data to complete the Octave symbol at point."
869 ;; http://debbugs.gnu.org/14300
870 (unless (string-match-p "/" (or (comint--match-partial-filename) ""))
871 (let ((beg (save-excursion
872 (skip-syntax-backward "w_" (comint-line-beginning-position))
873 (point)))
874 (end (point)))
875 (when (and beg (> end beg))
876 (list beg end (completion-table-in-turn
877 (inferior-octave-completion-table)
878 'comint-completion-file-name-table))))))
880 (define-obsolete-function-alias 'inferior-octave-complete
881 'completion-at-point "24.1")
883 (defun inferior-octave-dynamic-list-input-ring ()
884 "List the buffer's input history in a help buffer."
885 ;; We cannot use `comint-dynamic-list-input-ring', because it replaces
886 ;; "completion" by "history reference" ...
887 (interactive)
888 (if (or (not (ring-p comint-input-ring))
889 (ring-empty-p comint-input-ring))
890 (message "No history")
891 (let ((history nil)
892 (history-buffer " *Input History*")
893 (index (1- (ring-length comint-input-ring)))
894 (conf (current-window-configuration)))
895 ;; We have to build up a list ourselves from the ring vector.
896 (while (>= index 0)
897 (setq history (cons (ring-ref comint-input-ring index) history)
898 index (1- index)))
899 ;; Change "completion" to "history reference"
900 ;; to make the display accurate.
901 (with-output-to-temp-buffer history-buffer
902 (display-completion-list history)
903 (set-buffer history-buffer))
904 (message "Hit space to flush")
905 (let ((ch (read-event)))
906 (if (eq ch ?\ )
907 (set-window-configuration conf)
908 (setq unread-command-events (list ch)))))))
910 (defun inferior-octave-output-digest (_proc string)
911 "Special output filter for the inferior Octave process.
912 Save all output between newlines into `inferior-octave-output-list', and
913 the rest to `inferior-octave-output-string'."
914 (setq string (concat inferior-octave-output-string string))
915 (while (string-match "\n" string)
916 (setq inferior-octave-output-list
917 (append inferior-octave-output-list
918 (list (substring string 0 (match-beginning 0))))
919 string (substring string (match-end 0))))
920 (if (string-match inferior-octave-prompt string)
921 (setq inferior-octave-receive-in-progress nil))
922 (setq inferior-octave-output-string string))
924 (defun inferior-octave-check-process ()
925 (or (inferior-octave-process-live-p)
926 (error (substitute-command-keys
927 "No inferior octave process running. Type \\[run-octave]"))))
929 (defun inferior-octave-send-list-and-digest (list)
930 "Send LIST to the inferior Octave process and digest the output.
931 The elements of LIST have to be strings and are sent one by one. All
932 output is passed to the filter `inferior-octave-output-digest'."
933 (inferior-octave-check-process)
934 (let* ((proc inferior-octave-process)
935 (filter (process-filter proc))
936 string)
937 (set-process-filter proc 'inferior-octave-output-digest)
938 (setq inferior-octave-output-list nil)
939 (unwind-protect
940 (while (setq string (car list))
941 (setq inferior-octave-output-string nil
942 inferior-octave-receive-in-progress t)
943 (comint-send-string proc string)
944 (while inferior-octave-receive-in-progress
945 (accept-process-output proc))
946 (setq list (cdr list)))
947 (set-process-filter proc filter))))
949 (defvar inferior-octave-directory-tracker-resync nil)
950 (make-variable-buffer-local 'inferior-octave-directory-tracker-resync)
952 (defun inferior-octave-directory-tracker (string)
953 "Tracks `cd' commands issued to the inferior Octave process.
954 Use \\[inferior-octave-resync-dirs] to resync if Emacs gets confused."
955 (when inferior-octave-directory-tracker-resync
956 (or (inferior-octave-resync-dirs 'noerror)
957 (setq inferior-octave-directory-tracker-resync nil)))
958 (cond
959 ((string-match "^[ \t]*cd[ \t;]*$" string)
960 (cd "~"))
961 ((string-match "^[ \t]*cd[ \t]+\\([^ \t\n;]*\\)[ \t\n;]*" string)
962 (condition-case err
963 (cd (match-string 1 string))
964 (error (setq inferior-octave-directory-tracker-resync t)
965 (message "%s: `%s'"
966 (error-message-string err)
967 (match-string 1 string)))))))
969 (defun inferior-octave-resync-dirs (&optional noerror)
970 "Resync the buffer's idea of the current directory.
971 This command queries the inferior Octave process about its current
972 directory and makes this the current buffer's default directory."
973 (interactive)
974 (inferior-octave-send-list-and-digest '("disp (pwd ())\n"))
975 (condition-case err
976 (progn
977 (cd (car inferior-octave-output-list))
979 (error (unless noerror (signal (car err) (cdr err))))))
981 (defcustom inferior-octave-minimal-columns 80
982 "The minimal column width for the inferior Octave process."
983 :type 'integer
984 :group 'octave
985 :version "24.4")
987 (defvar inferior-octave-last-column-width nil)
989 (defun inferior-octave-track-window-width-change ()
990 ;; http://thread.gmane.org/gmane.comp.gnu.octave.general/48572
991 (let ((width (max inferior-octave-minimal-columns (window-width))))
992 (unless (eq inferior-octave-last-column-width width)
993 (setq-local inferior-octave-last-column-width width)
994 (when (inferior-octave-process-live-p)
995 (inferior-octave-send-list-and-digest
996 (list (format "putenv ('COLUMNS', '%s');\n" width)))))))
999 ;;; Miscellaneous useful functions
1001 (defun octave-in-comment-p ()
1002 "Return non-nil if point is inside an Octave comment."
1003 (nth 4 (syntax-ppss)))
1005 (defun octave-in-string-p ()
1006 "Return non-nil if point is inside an Octave string."
1007 (nth 3 (syntax-ppss)))
1009 (defun octave-in-string-or-comment-p ()
1010 "Return non-nil if point is inside an Octave string or comment."
1011 (nth 8 (syntax-ppss)))
1013 (defun octave-looking-at-kw (regexp)
1014 "Like `looking-at', but sets `case-fold-search' nil."
1015 (let ((case-fold-search nil))
1016 (looking-at regexp)))
1018 (defun octave-maybe-insert-continuation-string ()
1019 (if (or (octave-in-comment-p)
1020 (save-excursion
1021 (beginning-of-line)
1022 (looking-at octave-continuation-regexp)))
1024 (delete-horizontal-space)
1025 (insert (concat " " octave-continuation-string))))
1027 (defun octave-completing-read ()
1028 (let ((def (or (thing-at-point 'symbol)
1029 (save-excursion
1030 (skip-syntax-backward "-(")
1031 (thing-at-point 'symbol)))))
1032 (completing-read
1033 (format (if def "Function (default %s): "
1034 "Function: ") def)
1035 (inferior-octave-completion-table)
1036 nil nil nil nil def)))
1038 (defun octave-goto-function-definition (fn)
1039 "Go to the function definition of FN in current buffer."
1040 (let ((search
1041 (lambda (re sub)
1042 (let ((orig (point)) found)
1043 (goto-char (point-min))
1044 (while (and (not found) (re-search-forward re nil t))
1045 (when (and (equal (match-string sub) fn)
1046 (not (nth 8 (syntax-ppss))))
1047 (setq found t)))
1048 (unless found (goto-char orig))
1049 found))))
1050 (pcase (and buffer-file-name (file-name-extension buffer-file-name))
1051 ("cc" (funcall search
1052 "\\_<DEFUN\\(?:_DLD\\)?\\s-*(\\s-*\\(\\(?:\\sw\\|\\s_\\)+\\)" 1))
1053 (t (funcall search octave-function-header-regexp 3)))))
1055 (defun octave-function-file-p ()
1056 "Return non-nil if the first token is \"function\".
1057 The value is (START END NAME-START NAME-END) of the function."
1058 (save-excursion
1059 (goto-char (point-min))
1060 (when (equal (funcall smie-forward-token-function) "function")
1061 (forward-word -1)
1062 (let* ((start (point))
1063 (end (progn (forward-sexp 1) (point)))
1064 (name (when (progn
1065 (goto-char start)
1066 (re-search-forward octave-function-header-regexp
1067 end t))
1068 (list (match-beginning 3) (match-end 3)))))
1069 (cons start (cons end name))))))
1071 ;; Like forward-comment but stop at non-comment blank
1072 (defun octave-skip-comment-forward (limit)
1073 (let ((ppss (syntax-ppss)))
1074 (if (nth 4 ppss)
1075 (goto-char (nth 8 ppss))
1076 (goto-char (or (comment-search-forward limit t) (point)))))
1077 (while (and (< (point) limit) (looking-at-p "\\s<"))
1078 (forward-comment 1)))
1080 ;;; First non-copyright comment block
1081 (defun octave-function-file-comment ()
1082 "Beginning and end positions of the function file comment."
1083 (save-excursion
1084 (goto-char (point-min))
1085 ;; Copyright block: octave/libinterp/parse-tree/lex.ll around line 1634
1086 (while (save-excursion
1087 (when (comment-search-forward (point-max) t)
1088 (when (eq (char-after) ?\{) ; case of block comment
1089 (forward-char 1))
1090 (skip-syntax-forward "-")
1091 (let ((case-fold-search t))
1092 (looking-at-p "\\(?:copyright\\|author\\)\\_>"))))
1093 (octave-skip-comment-forward (point-max)))
1094 (let ((beg (comment-search-forward (point-max) t)))
1095 (when beg
1096 (goto-char beg)
1097 (octave-skip-comment-forward (point-max))
1098 (list beg (point))))))
1100 (defun octave-sync-function-file-names ()
1101 "Ensure function name agree with function file name.
1102 See Info node `(octave)Function Files'."
1103 (interactive)
1104 (when buffer-file-name
1105 (pcase-let ((`(,start ,_end ,name-start ,name-end)
1106 (octave-function-file-p)))
1107 (when (and start name-start)
1108 (let* ((func (buffer-substring name-start name-end))
1109 (file (file-name-sans-extension
1110 (file-name-nondirectory buffer-file-name)))
1111 (help-form (format "\
1112 a: Use function name `%s'
1113 b: Use file name `%s'
1114 q: Don't fix\n" func file))
1115 (c (unless (equal file func)
1116 (save-window-excursion
1117 (help-form-show)
1118 (read-char-choice
1119 "Which name to use? (a/b/q) " '(?a ?b ?q))))))
1120 (pcase c
1121 (?a (let ((newname (expand-file-name
1122 (concat func (file-name-extension
1123 buffer-file-name t)))))
1124 (when (or (not (file-exists-p newname))
1125 (yes-or-no-p
1126 (format "Target file %s exists; proceed? " newname)))
1127 (when (file-exists-p buffer-file-name)
1128 (rename-file buffer-file-name newname t))
1129 (set-visited-file-name newname))))
1130 (?b (save-excursion
1131 (goto-char name-start)
1132 (delete-region name-start name-end)
1133 (insert file)))))))))
1135 (defun octave-update-function-file-comment (beg end)
1136 "Query replace function names in function file comment."
1137 (interactive
1138 (progn
1139 (barf-if-buffer-read-only)
1140 (if (use-region-p)
1141 (list (region-beginning) (region-end))
1142 (or (octave-function-file-comment)
1143 (error "No function file comment found")))))
1144 (save-excursion
1145 (let* ((bounds (or (octave-function-file-p)
1146 (error "Not in a function file buffer")))
1147 (func (if (cddr bounds)
1148 (apply #'buffer-substring (cddr bounds))
1149 (error "Function name not found")))
1150 (old-func (progn
1151 (goto-char beg)
1152 (when (re-search-forward
1153 "[=}]\\s-*\\(\\(?:\\sw\\|\\s_\\)+\\)\\_>"
1154 (min (line-end-position 4) end)
1156 (match-string 1))))
1157 (old-func (read-string (format (if old-func
1158 "Name to replace (default %s): "
1159 "Name to replace: ")
1160 old-func)
1161 nil nil old-func)))
1162 (if (and func old-func (not (equal func old-func)))
1163 (perform-replace old-func func 'query
1164 nil 'delimited nil nil beg end)
1165 (message "Function names match")))))
1167 (defface octave-function-comment-block
1168 '((t (:inherit font-lock-doc-face)))
1169 "Face used to highlight function comment block."
1170 :group 'octave)
1172 (eval-when-compile (require 'texinfo))
1174 (defun octave-font-lock-texinfo-comment ()
1175 (let ((kws
1176 (eval-when-compile
1177 (delq nil (mapcar
1178 (lambda (kw)
1179 (if (numberp (nth 1 kw))
1180 `(,(nth 0 kw) ,(nth 1 kw) ,(nth 2 kw) prepend)
1181 (message "Ignoring Texinfo highlight: %S" kw)))
1182 texinfo-font-lock-keywords)))))
1183 (font-lock-add-keywords
1185 `((,(lambda (limit)
1186 (while (and (< (point) limit)
1187 (search-forward "-*- texinfo -*-" limit t)
1188 (octave-in-comment-p))
1189 (let ((beg (nth 8 (syntax-ppss)))
1190 (end (progn
1191 (octave-skip-comment-forward (point-max))
1192 (point))))
1193 (put-text-property beg end 'font-lock-multiline t)
1194 (font-lock-prepend-text-property
1195 beg end 'face 'octave-function-comment-block)
1196 (dolist (kw kws)
1197 (goto-char beg)
1198 (while (re-search-forward (car kw) end 'move)
1199 (font-lock-apply-highlight (cdr kw))))))
1200 nil)))
1201 'append)))
1204 ;;; Indentation
1206 (defun octave-indent-new-comment-line (&optional soft)
1207 "Break Octave line at point, continuing comment if within one.
1208 Insert `octave-continuation-string' before breaking the line
1209 unless inside a list. Signal an error if within a single-quoted
1210 string."
1211 (interactive)
1212 (funcall comment-line-break-function soft))
1214 (defun octave--indent-new-comment-line (orig &rest args)
1215 (cond
1216 ((octave-in-comment-p) nil)
1217 ((eq (octave-in-string-p) ?')
1218 (error "Cannot split a single-quoted string"))
1219 ((eq (octave-in-string-p) ?\")
1220 (insert octave-continuation-string))
1222 (delete-horizontal-space)
1223 (unless (and (cadr (syntax-ppss))
1224 (eq (char-after (cadr (syntax-ppss))) ?\())
1225 (insert " " octave-continuation-string))))
1226 (apply orig args)
1227 (indent-according-to-mode))
1229 (define-obsolete-function-alias
1230 'octave-indent-defun 'prog-indent-sexp "24.4")
1233 ;;; Motion
1234 (defun octave-next-code-line (&optional arg)
1235 "Move ARG lines of Octave code forward (backward if ARG is negative).
1236 Skips past all empty and comment lines. Default for ARG is 1.
1238 On success, return 0. Otherwise, go as far as possible and return -1."
1239 (interactive "p")
1240 (or arg (setq arg 1))
1241 (beginning-of-line)
1242 (let ((n 0)
1243 (inc (if (> arg 0) 1 -1)))
1244 (while (and (/= arg 0) (= n 0))
1245 (setq n (forward-line inc))
1246 (while (and (= n 0)
1247 (looking-at "\\s-*\\($\\|\\s<\\)"))
1248 (setq n (forward-line inc)))
1249 (setq arg (- arg inc)))
1252 (defun octave-previous-code-line (&optional arg)
1253 "Move ARG lines of Octave code backward (forward if ARG is negative).
1254 Skips past all empty and comment lines. Default for ARG is 1.
1256 On success, return 0. Otherwise, go as far as possible and return -1."
1257 (interactive "p")
1258 (or arg (setq arg 1))
1259 (octave-next-code-line (- arg)))
1261 (defun octave-beginning-of-line ()
1262 "Move point to beginning of current Octave line.
1263 If on an empty or comment line, go to the beginning of that line.
1264 Otherwise, move backward to the beginning of the first Octave code line
1265 which is not inside a continuation statement, i.e., which does not
1266 follow a code line ending with `...' or is inside an open
1267 parenthesis list."
1268 (interactive)
1269 (beginning-of-line)
1270 (unless (looking-at "\\s-*\\($\\|\\s<\\)")
1271 (while (or (when (cadr (syntax-ppss))
1272 (goto-char (cadr (syntax-ppss)))
1273 (beginning-of-line)
1275 (and (or (looking-at "\\s-*\\($\\|\\s<\\)")
1276 (save-excursion
1277 (if (zerop (octave-previous-code-line))
1278 (looking-at octave-continuation-regexp))))
1279 (zerop (forward-line -1)))))))
1281 (defun octave-end-of-line ()
1282 "Move point to end of current Octave line.
1283 If on an empty or comment line, go to the end of that line.
1284 Otherwise, move forward to the end of the first Octave code line which
1285 does not end with `...' or is inside an open parenthesis list."
1286 (interactive)
1287 (end-of-line)
1288 (unless (save-excursion
1289 (beginning-of-line)
1290 (looking-at "\\s-*\\($\\|\\s<\\)"))
1291 (while (or (when (cadr (syntax-ppss))
1292 (condition-case nil
1293 (progn
1294 (up-list 1)
1295 (end-of-line)
1297 (error nil)))
1298 (and (save-excursion
1299 (beginning-of-line)
1300 (or (looking-at "\\s-*\\($\\|\\s<\\)")
1301 (looking-at octave-continuation-regexp)))
1302 (zerop (forward-line 1)))))
1303 (end-of-line)))
1305 (defun octave-mark-block ()
1306 "Put point at the beginning of this Octave block, mark at the end.
1307 The block marked is the one that contains point or follows point."
1308 (interactive)
1309 (if (and (looking-at "\\sw\\|\\s_")
1310 (looking-back "\\sw\\|\\s_" (1- (point))))
1311 (skip-syntax-forward "w_"))
1312 (unless (or (looking-at "\\s(")
1313 (save-excursion
1314 (let* ((token (funcall smie-forward-token-function))
1315 (level (assoc token smie-grammar)))
1316 (and level (not (numberp (cadr level)))))))
1317 (backward-up-list 1))
1318 (mark-sexp))
1320 (defun octave-beginning-of-defun (&optional arg)
1321 "Octave-specific `beginning-of-defun-function' (which see)."
1322 (or arg (setq arg 1))
1323 ;; Move out of strings or comments.
1324 (when (octave-in-string-or-comment-p)
1325 (goto-char (octave-in-string-or-comment-p)))
1326 (letrec ((orig (point))
1327 (toplevel (lambda (pos)
1328 (condition-case nil
1329 (progn
1330 (backward-up-list 1)
1331 (funcall toplevel (point)))
1332 (scan-error pos)))))
1333 (goto-char (funcall toplevel (point)))
1334 (when (and (> arg 0) (/= orig (point)))
1335 (setq arg (1- arg)))
1336 (forward-sexp (- arg))
1337 (and (< arg 0) (forward-sexp -1))
1338 (/= orig (point))))
1340 (defun octave-fill-paragraph (&optional _arg)
1341 "Fill paragraph of Octave code, handling Octave comments."
1342 ;; FIXME: difference with generic fill-paragraph:
1343 ;; - code lines are only split, never joined.
1344 ;; - \n that end comments are never removed.
1345 ;; - insert continuation marker when splitting code lines.
1346 (interactive "P")
1347 (save-excursion
1348 (let ((end (progn (forward-paragraph) (copy-marker (point) t)))
1349 (beg (progn
1350 (forward-paragraph -1)
1351 (skip-chars-forward " \t\n")
1352 (beginning-of-line)
1353 (point)))
1354 (cfc (current-fill-column))
1355 comment-prefix)
1356 (goto-char beg)
1357 (while (< (point) end)
1358 (condition-case nil
1359 (indent-according-to-mode)
1360 (error nil))
1361 (move-to-column cfc)
1362 ;; First check whether we need to combine non-empty comment lines
1363 (if (and (< (current-column) cfc)
1364 (octave-in-comment-p)
1365 (not (save-excursion
1366 (beginning-of-line)
1367 (looking-at "^\\s-*\\s<+\\s-*$"))))
1368 ;; This is a nonempty comment line which does not extend
1369 ;; past the fill column. If it is followed by a nonempty
1370 ;; comment line with the same comment prefix, try to
1371 ;; combine them, and repeat this until either we reach the
1372 ;; fill-column or there is nothing more to combine.
1373 (progn
1374 ;; Get the comment prefix
1375 (save-excursion
1376 (beginning-of-line)
1377 (while (and (re-search-forward "\\s<+")
1378 (not (octave-in-comment-p))))
1379 (setq comment-prefix (match-string 0)))
1380 ;; And keep combining ...
1381 (while (and (< (current-column) cfc)
1382 (save-excursion
1383 (forward-line 1)
1384 (and (looking-at
1385 (concat "^\\s-*"
1386 comment-prefix
1387 "\\S<"))
1388 (not (looking-at
1389 (concat "^\\s-*"
1390 comment-prefix
1391 "\\s-*$"))))))
1392 (delete-char 1)
1393 (re-search-forward comment-prefix)
1394 (delete-region (match-beginning 0) (match-end 0))
1395 (fixup-whitespace)
1396 (move-to-column cfc))))
1397 ;; We might also try to combine continued code lines> Perhaps
1398 ;; some other time ...
1399 (skip-chars-forward "^ \t\n")
1400 (delete-horizontal-space)
1401 (if (or (< (current-column) cfc)
1402 (and (= (current-column) cfc) (eolp)))
1403 (forward-line 1)
1404 (if (not (eolp)) (insert " "))
1405 (or (funcall normal-auto-fill-function)
1406 (forward-line 1))))
1407 t)))
1409 (defun octave-completion-at-point ()
1410 "Find the text to complete and the corresponding table."
1411 (let* ((beg (save-excursion (skip-syntax-backward "w_") (point)))
1412 (end (point)))
1413 (if (< beg (point))
1414 ;; Extend region past point, if applicable.
1415 (save-excursion (skip-syntax-forward "w_")
1416 (setq end (point))))
1417 (when (> end beg)
1418 (list beg end (or (and (inferior-octave-process-live-p)
1419 (inferior-octave-completion-table))
1420 octave-reserved-words)))))
1422 (define-obsolete-function-alias 'octave-complete-symbol
1423 'completion-at-point "24.1")
1425 (defun octave-add-log-current-defun ()
1426 "A function for `add-log-current-defun-function' (which see)."
1427 (save-excursion
1428 (end-of-line)
1429 (and (beginning-of-defun)
1430 (re-search-forward octave-function-header-regexp
1431 (line-end-position) t)
1432 (match-string 3))))
1435 ;;; Electric characters && friends
1436 (define-skeleton octave-insert-defun
1437 "Insert an Octave function skeleton.
1438 Prompt for the function's name, arguments and return values (to be
1439 entered without parens)."
1440 (let* ((defname (file-name-sans-extension (buffer-name)))
1441 (name (read-string (format "Function name (default %s): " defname)
1442 nil nil defname))
1443 (args (read-string "Arguments: "))
1444 (vals (read-string "Return values: ")))
1445 (format "%s%s (%s)"
1446 (cond
1447 ((string-equal vals "") vals)
1448 ((string-match "[ ,]" vals) (concat "[" vals "] = "))
1449 (t (concat vals " = ")))
1450 name
1451 args))
1452 \n octave-block-comment-start "usage: " str \n
1453 octave-block-comment-start '(delete-horizontal-space) \n
1454 octave-block-comment-start '(delete-horizontal-space) \n
1455 "function " > str \n
1456 _ \n
1457 "endfunction" > \n)
1459 ;;; Communication with the inferior Octave process
1460 (defun octave-kill-process ()
1461 "Kill inferior Octave process and its buffer."
1462 (interactive)
1463 (when (and (buffer-live-p (get-buffer inferior-octave-buffer))
1464 (or (yes-or-no-p (format "Kill %S and its buffer? "
1465 inferior-octave-process))
1466 (user-error "Aborted")))
1467 (when (inferior-octave-process-live-p)
1468 (set-process-query-on-exit-flag inferior-octave-process nil)
1469 (process-send-string inferior-octave-process "quit;\n")
1470 (accept-process-output inferior-octave-process))
1471 (kill-buffer inferior-octave-buffer)))
1473 (defun octave-show-process-buffer ()
1474 "Make sure that `inferior-octave-buffer' is displayed."
1475 (interactive)
1476 (if (get-buffer inferior-octave-buffer)
1477 (display-buffer inferior-octave-buffer)
1478 (message "No buffer named %s" inferior-octave-buffer)))
1480 (defun octave-hide-process-buffer ()
1481 "Delete all windows that display `inferior-octave-buffer'."
1482 (interactive)
1483 (if (get-buffer inferior-octave-buffer)
1484 (delete-windows-on inferior-octave-buffer)
1485 (message "No buffer named %s" inferior-octave-buffer)))
1487 (defun octave-source-file (file)
1488 "Execute FILE in the inferior Octave process.
1489 This is done using Octave's source function. FILE defaults to
1490 current buffer file unless called with a prefix arg \\[universal-argument]."
1491 (interactive (list (or (and (not current-prefix-arg) buffer-file-name)
1492 (read-file-name "File: " nil nil t))))
1493 (or (stringp file)
1494 (signal 'wrong-type-argument (list 'stringp file)))
1495 (inferior-octave t)
1496 (with-current-buffer inferior-octave-buffer
1497 (comint-send-string inferior-octave-process
1498 (format "source '%s'\n" file))))
1500 (defun octave-send-region (beg end)
1501 "Send current region to the inferior Octave process."
1502 (interactive "r")
1503 (inferior-octave t)
1504 (let ((proc inferior-octave-process)
1505 (string (buffer-substring-no-properties beg end))
1506 line)
1507 (with-current-buffer inferior-octave-buffer
1508 ;; http://lists.gnu.org/archive/html/emacs-devel/2013-10/msg00095.html
1509 (compilation-forget-errors)
1510 (setq inferior-octave-output-list nil)
1511 (while (not (string-equal string ""))
1512 (if (string-match "\n" string)
1513 (setq line (substring string 0 (match-beginning 0))
1514 string (substring string (match-end 0)))
1515 (setq line string string ""))
1516 (setq inferior-octave-receive-in-progress t)
1517 (inferior-octave-send-list-and-digest (list (concat line "\n")))
1518 (while inferior-octave-receive-in-progress
1519 (accept-process-output proc))
1520 (insert-before-markers
1521 (mapconcat 'identity
1522 (append
1523 (if octave-send-echo-input (list line) (list ""))
1524 inferior-octave-output-list
1525 (list inferior-octave-output-string))
1526 "\n")))))
1527 (if octave-send-show-buffer
1528 (display-buffer inferior-octave-buffer)))
1530 (defun octave-send-buffer ()
1531 "Send current buffer to the inferior Octave process."
1532 (interactive)
1533 (octave-send-region (point-min) (point-max)))
1535 (defun octave-send-block ()
1536 "Send current Octave block to the inferior Octave process."
1537 (interactive)
1538 (save-excursion
1539 (octave-mark-block)
1540 (octave-send-region (point) (mark))))
1542 (defun octave-send-defun ()
1543 "Send current Octave function to the inferior Octave process."
1544 (interactive)
1545 (save-excursion
1546 (mark-defun)
1547 (octave-send-region (point) (mark))))
1549 (defun octave-send-line (&optional arg)
1550 "Send current Octave code line to the inferior Octave process.
1551 With positive prefix ARG, send that many lines.
1552 If `octave-send-line-auto-forward' is non-nil, go to the next unsent
1553 code line."
1554 (interactive "P")
1555 (or arg (setq arg 1))
1556 (if (> arg 0)
1557 (let (beg end)
1558 (beginning-of-line)
1559 (setq beg (point))
1560 (octave-next-code-line (- arg 1))
1561 (end-of-line)
1562 (setq end (point))
1563 (if octave-send-line-auto-forward
1564 (octave-next-code-line 1))
1565 (octave-send-region beg end))))
1567 (defun octave-eval-print-last-sexp ()
1568 "Evaluate Octave sexp before point and print value into current buffer."
1569 (interactive)
1570 (inferior-octave t)
1571 (let ((standard-output (current-buffer))
1572 (print-escape-newlines nil)
1573 (opoint (point)))
1574 (terpri)
1575 (prin1
1576 (save-excursion
1577 (forward-sexp -1)
1578 (inferior-octave-send-list-and-digest
1579 (list (concat (buffer-substring-no-properties (point) opoint)
1580 "\n")))
1581 (mapconcat 'identity inferior-octave-output-list "\n")))
1582 (terpri)))
1586 (defcustom octave-eldoc-message-style 'auto
1587 "Octave eldoc message style: auto, oneline, multiline."
1588 :type '(choice (const :tag "Automatic" auto)
1589 (const :tag "One Line" oneline)
1590 (const :tag "Multi Line" multiline))
1591 :group 'octave
1592 :version "24.4")
1594 ;; (FN SIGNATURE1 SIGNATURE2 ...)
1595 (defvar octave-eldoc-cache nil)
1597 (defun octave-eldoc-function-signatures (fn)
1598 (unless (equal fn (car octave-eldoc-cache))
1599 (inferior-octave-send-list-and-digest
1600 (list (format "print_usage ('%s');\n" fn)))
1601 (let (result)
1602 (dolist (line inferior-octave-output-list)
1603 (when (string-match
1604 "\\s-*\\(?:--[^:]+\\|usage\\):\\s-*\\(.*\\)$"
1605 line)
1606 (push (match-string 1 line) result)))
1607 (setq octave-eldoc-cache
1608 (cons (substring-no-properties fn)
1609 (nreverse result)))))
1610 (cdr octave-eldoc-cache))
1612 (defun octave-eldoc-function ()
1613 "A function for `eldoc-documentation-function' (which see)."
1614 (when (inferior-octave-process-live-p)
1615 (let* ((ppss (syntax-ppss))
1616 (paren-pos (cadr ppss))
1617 (fn (save-excursion
1618 (if (and paren-pos
1619 ;; PAREN-POS must be after the prompt
1620 (>= paren-pos
1621 (if (eq (get-buffer-process (current-buffer))
1622 inferior-octave-process)
1623 (process-mark inferior-octave-process)
1624 (point-min)))
1625 (or (not (eq (get-buffer-process (current-buffer))
1626 inferior-octave-process))
1627 (< (process-mark inferior-octave-process)
1628 paren-pos))
1629 (eq (char-after paren-pos) ?\())
1630 (goto-char paren-pos)
1631 (setq paren-pos nil))
1632 (when (or (< (skip-syntax-backward "-") 0) paren-pos)
1633 (thing-at-point 'symbol))))
1634 (sigs (and fn (octave-eldoc-function-signatures fn)))
1635 (oneline (mapconcat 'identity sigs
1636 (propertize " | " 'face 'warning)))
1637 (multiline (mapconcat (lambda (s) (concat "-- " s)) sigs "\n")))
1639 ;; Return the value according to style.
1640 (pcase octave-eldoc-message-style
1641 (`auto (if (< (length oneline) (window-width (minibuffer-window)))
1642 oneline
1643 multiline))
1644 (`oneline oneline)
1645 (`multiline multiline)))))
1647 (defcustom octave-help-buffer "*Octave Help*"
1648 "Buffer name for `octave-help'."
1649 :type 'string
1650 :group 'octave
1651 :version "24.4")
1653 ;; Used in a mode derived from help-mode.
1654 (declare-function help-button-action "help-mode" (button))
1656 (define-button-type 'octave-help-file
1657 'follow-link t
1658 'action #'help-button-action
1659 'help-function 'octave-find-definition)
1661 (define-button-type 'octave-help-function
1662 'follow-link t
1663 'action (lambda (b)
1664 (octave-help
1665 (buffer-substring (button-start b) (button-end b)))))
1667 (defvar octave-help-mode-map
1668 (let ((map (make-sparse-keymap)))
1669 (define-key map "\M-." 'octave-find-definition)
1670 (define-key map "\C-hd" 'octave-help)
1671 (define-key map "\C-ha" 'octave-lookfor)
1672 map))
1674 (define-derived-mode octave-help-mode help-mode "OctHelp"
1675 "Major mode for displaying Octave documentation."
1676 :abbrev-table nil
1677 :syntax-table octave-mode-syntax-table
1678 (eval-and-compile (require 'help-mode))
1679 ;; Don't highlight `EXAMPLE' as elisp symbols by using a regexp that
1680 ;; can never match.
1681 (setq-local help-xref-symbol-regexp "x\\`"))
1683 (defun octave-help (fn)
1684 "Display the documentation of FN."
1685 (interactive (list (octave-completing-read)))
1686 (inferior-octave-send-list-and-digest
1687 (list (format "help ('%s');\n" fn)))
1688 (let ((lines inferior-octave-output-list)
1689 (inhibit-read-only t))
1690 (when (string-match "error: \\(.*\\)$" (car lines))
1691 (error "%s" (match-string 1 (car lines))))
1692 (with-help-window octave-help-buffer
1693 (princ (mapconcat 'identity lines "\n"))
1694 (with-current-buffer octave-help-buffer
1695 ;; Bound to t so that `help-buffer' returns current buffer for
1696 ;; `help-setup-xref'.
1697 (let ((help-xref-following t))
1698 (help-setup-xref (list 'octave-help fn)
1699 (called-interactively-p 'interactive)))
1700 ;; Note: can be turned off by suppress_verbose_help_message.
1702 ;; Remove boring trailing text: Additional help for built-in functions
1703 ;; and operators ...
1704 (goto-char (point-max))
1705 (when (search-backward "\n\n\n" nil t)
1706 (goto-char (match-beginning 0))
1707 (delete-region (point) (point-max)))
1708 ;; File name highlight
1709 (goto-char (point-min))
1710 (when (re-search-forward "from the file \\(.*\\)$"
1711 (line-end-position)
1713 (let* ((file (match-string 1))
1714 (dir (file-name-directory
1715 (directory-file-name (file-name-directory file)))))
1716 (replace-match "" nil nil nil 1)
1717 (insert "`")
1718 ;; Include the parent directory which may be regarded as
1719 ;; the category for the FN.
1720 (help-insert-xref-button (file-relative-name file dir)
1721 'octave-help-file fn)
1722 (insert "'")))
1723 ;; Make 'See also' clickable.
1724 (with-syntax-table octave-mode-syntax-table
1725 (when (re-search-forward "^\\s-*See also:" nil t)
1726 (let ((end (save-excursion (re-search-forward "^\\s-*$" nil t))))
1727 (while (re-search-forward
1728 "\\s-*\\([^,\n]+?\\)\\s-*\\(?:[,]\\|[.]?$\\)" end t)
1729 (make-text-button (match-beginning 1) (match-end 1)
1730 :type 'octave-help-function)))))
1731 (octave-help-mode)))))
1733 (defun octave-lookfor (str &optional all)
1734 "Search for the string STR in all function help strings.
1735 If ALL is non-nil search the entire help string else only search the first
1736 sentence."
1737 (interactive "sSearch for: \nP")
1738 (inferior-octave-send-list-and-digest
1739 (list (format "lookfor (%s'%s');\n"
1740 (if all "'-all', " "")
1741 str)))
1742 (let ((lines inferior-octave-output-list))
1743 (when (and (stringp (car lines))
1744 (string-match "error: \\(.*\\)$" (car lines)))
1745 (error "%s" (match-string 1 (car lines))))
1746 (with-help-window octave-help-buffer
1747 (with-current-buffer octave-help-buffer
1748 (if lines
1749 (insert (mapconcat 'identity lines "\n"))
1750 (insert (format "Nothing found for \"%s\".\n" str)))
1751 ;; Bound to t so that `help-buffer' returns current buffer for
1752 ;; `help-setup-xref'.
1753 (let ((help-xref-following t))
1754 (help-setup-xref (list 'octave-lookfor str all)
1755 (called-interactively-p 'interactive)))
1756 (goto-char (point-min))
1757 (when lines
1758 (while (re-search-forward "^\\([^[:blank:]]+\\) " nil 'noerror)
1759 (make-text-button (match-beginning 1) (match-end 1)
1760 :type 'octave-help-function)))
1761 (unless all
1762 (goto-char (point-max))
1763 (insert "\nRetry with ")
1764 (insert-text-button "'-all'"
1765 'follow-link t
1766 'action #'(lambda (_b)
1767 (octave-lookfor str '-all)))
1768 (insert ".\n"))
1769 (octave-help-mode)))))
1771 (defcustom octave-source-directories nil
1772 "A list of directories for Octave sources.
1773 If the environment variable OCTAVE_SRCDIR is set, it is searched first."
1774 :type '(repeat directory)
1775 :group 'octave
1776 :version "24.4")
1778 (defun octave-source-directories ()
1779 (let ((srcdir (or (and inferior-octave-process
1780 (process-get inferior-octave-process 'octave-srcdir))
1781 (getenv "OCTAVE_SRCDIR"))))
1782 (if srcdir
1783 (cons srcdir octave-source-directories)
1784 octave-source-directories)))
1786 (defvar octave-find-definition-filename-function
1787 #'octave-find-definition-default-filename)
1789 (defun octave-find-definition-default-filename (name)
1790 "Default value for `octave-find-definition-filename-function'."
1791 (pcase (file-name-extension name)
1792 ("oct"
1793 (octave-find-definition-default-filename
1794 (concat "libinterp/dldfcn/"
1795 (file-name-sans-extension (file-name-nondirectory name))
1796 ".cc")))
1797 ("cc"
1798 (let ((file (or (locate-file name (octave-source-directories))
1799 (locate-file (file-name-nondirectory name)
1800 (octave-source-directories)))))
1801 (or (and file (file-exists-p file))
1802 (error "File `%s' not found" name))
1803 file))
1804 ("mex"
1805 (if (yes-or-no-p (format "File `%s' may be binary; open? "
1806 (file-name-nondirectory name)))
1807 name
1808 (user-error "Aborted")))
1809 (t name)))
1811 (defvar find-tag-marker-ring)
1813 (defun octave-find-definition (fn)
1814 "Find the definition of FN.
1815 Functions implemented in C++ can be found if
1816 variable `octave-source-directories' is set correctly."
1817 (interactive (list (octave-completing-read)))
1818 (require 'etags)
1819 (let ((orig (point)))
1820 (if (and (derived-mode-p 'octave-mode)
1821 (octave-goto-function-definition fn))
1822 (ring-insert find-tag-marker-ring (copy-marker orig))
1823 (inferior-octave-send-list-and-digest
1824 ;; help NAME is more verbose
1825 (list (format "\
1826 if iskeyword('%s') disp('`%s'' is a keyword') else which('%s') endif\n"
1827 fn fn fn)))
1828 (let (line file)
1829 ;; Skip garbage lines such as
1830 ;; warning: fmincg.m: possible Matlab-style ....
1831 (while (and (not file) (consp inferior-octave-output-list))
1832 (setq line (pop inferior-octave-output-list))
1833 (when (string-match "from the file \\(.*\\)$" line)
1834 (setq file (match-string 1 line))))
1835 (if (not file)
1836 (user-error "%s" (or line (format "`%s' not found" fn)))
1837 (ring-insert find-tag-marker-ring (point-marker))
1838 (setq file (funcall octave-find-definition-filename-function file))
1839 (when file
1840 (find-file file)
1841 (octave-goto-function-definition fn)))))))
1843 (provide 'octave)
1844 ;;; octave.el ends here