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