Quoting fixes in lisp/progmodes
[emacs.git] / lisp / progmodes / octave.el
blob70a2b1ab5ad48fa885fa8a5cf8c19839b55897a5
1 ;;; octave.el --- editing octave source files under emacs -*- lexical-binding: t; -*-
3 ;; Copyright (C) 1997, 2001-2015 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 (add-function :before-until (local 'eldoc-documentation-function)
605 'octave-eldoc-function)
607 (easy-menu-add octave-mode-menu))
610 (defcustom inferior-octave-program "octave"
611 "Program invoked by `inferior-octave'."
612 :type 'string
613 :group 'octave)
615 (defcustom inferior-octave-buffer "*Inferior Octave*"
616 "Name of buffer for running an inferior Octave process."
617 :type 'string
618 :group 'octave)
620 (defcustom inferior-octave-prompt
621 ;; For Octave >= 3.8, default is always 'octave', see
622 ;; http://hg.savannah.gnu.org/hgweb/octave/rev/708173343c50
623 "\\(?:^octave\\(?:.bin\\|.exe\\)?\\(?:-[.0-9]+\\)?\\(?::[0-9]+\\)?\\|^debug\\|^\\)>+ "
624 "Regexp to match prompts for the inferior Octave process."
625 :type 'regexp
626 :group 'octave)
628 (defcustom inferior-octave-prompt-read-only comint-prompt-read-only
629 "If non-nil, the Octave prompt is read only.
630 See `comint-prompt-read-only' for details."
631 :type 'boolean
632 :group 'octave
633 :version "24.4")
635 (defcustom inferior-octave-startup-file
636 (let ((n (file-name-nondirectory inferior-octave-program)))
637 (locate-user-emacs-file (format "init_%s.m" n) (format ".emacs-%s" n)))
638 "Name of the inferior Octave startup file.
639 The contents of this file are sent to the inferior Octave process on
640 startup."
641 :type '(choice (const :tag "None" nil) file)
642 :group 'octave
643 :version "24.4")
645 (defcustom inferior-octave-startup-args '("-i" "--no-line-editing")
646 "List of command line arguments for the inferior Octave process.
647 For example, for suppressing the startup message and using `traditional'
648 mode, include \"-q\" and \"--traditional\"."
649 :type '(repeat string)
650 :group 'octave
651 :version "24.4")
653 (defcustom inferior-octave-mode-hook nil
654 "Hook to be run when Inferior Octave mode is started."
655 :type 'hook
656 :group 'octave)
658 (defcustom inferior-octave-error-regexp-alist
659 '(("error:\\s-*\\(.*?\\) at line \\([0-9]+\\), column \\([0-9]+\\)"
660 1 2 3 2 1)
661 ("warning:\\s-*\\([^:\n]+\\):.*at line \\([0-9]+\\), column \\([0-9]+\\)"
662 1 2 3 1 1))
663 "Value for `compilation-error-regexp-alist' in inferior octave."
664 :version "24.4"
665 :type '(repeat (choice (symbol :tag "Predefined symbol")
666 (sexp :tag "Error specification")))
667 :group 'octave)
669 (defvar inferior-octave-compilation-font-lock-keywords
670 '(("\\_<PASS\\_>" . compilation-info-face)
671 ("\\_<FAIL\\_>" . compilation-error-face)
672 ("\\_<\\(warning\\):" 1 compilation-warning-face)
673 ("\\_<\\(error\\):" 1 compilation-error-face)
674 ("^\\s-*!!!!!.*\\|^.*failed$" . compilation-error-face))
675 "Value for `compilation-mode-font-lock-keywords' in inferior octave.")
677 (defvar inferior-octave-process nil)
679 (defvar inferior-octave-mode-map
680 (let ((map (make-sparse-keymap)))
681 (set-keymap-parent map comint-mode-map)
682 (define-key map "\M-." 'octave-find-definition)
683 (define-key map "\t" 'completion-at-point)
684 (define-key map "\C-hd" 'octave-help)
685 (define-key map "\C-ha" 'octave-lookfor)
686 ;; Same as in `shell-mode'.
687 (define-key map "\M-?" 'comint-dynamic-list-filename-completions)
688 (define-key map "\C-c\C-l" 'inferior-octave-dynamic-list-input-ring)
689 (define-key map [menu-bar inout list-history]
690 '("List Input History" . inferior-octave-dynamic-list-input-ring))
691 map)
692 "Keymap used in Inferior Octave mode.")
694 (defvar inferior-octave-mode-syntax-table
695 (let ((table (make-syntax-table octave-mode-syntax-table)))
696 table)
697 "Syntax table in use in `inferior-octave-mode' buffers.")
699 (defvar inferior-octave-font-lock-keywords
700 (list
701 (cons inferior-octave-prompt 'font-lock-type-face))
702 ;; Could certainly do more font locking in inferior Octave ...
703 "Additional expressions to highlight in Inferior Octave mode.")
705 (defvar inferior-octave-output-list nil)
706 (defvar inferior-octave-output-string nil)
707 (defvar inferior-octave-receive-in-progress nil)
709 (define-obsolete-variable-alias 'inferior-octave-startup-hook
710 'inferior-octave-mode-hook "24.4")
712 (defvar inferior-octave-dynamic-complete-functions
713 '(inferior-octave-completion-at-point comint-filename-completion)
714 "List of functions called to perform completion for inferior Octave.
715 This variable is used to initialize `comint-dynamic-complete-functions'
716 in the Inferior Octave buffer.")
718 (defvar info-lookup-mode)
719 (defvar compilation-error-regexp-alist)
720 (defvar compilation-mode-font-lock-keywords)
722 (declare-function compilation-forget-errors "compile" ())
724 (defun inferior-octave-process-live-p ()
725 (process-live-p inferior-octave-process))
727 (define-derived-mode inferior-octave-mode comint-mode "Inferior Octave"
728 "Major mode for interacting with an inferior Octave process.
730 See Info node `(octave-mode) Running Octave from Within Emacs' for more
731 details.
733 Key bindings:
734 \\{inferior-octave-mode-map}"
735 :abbrev-table octave-abbrev-table
736 :group 'octave
738 (setq comint-prompt-regexp inferior-octave-prompt)
740 (setq-local comment-use-syntax t)
741 (setq-local comment-start octave-comment-start)
742 (setq-local comment-end "")
743 (setq comment-column 32)
744 (setq-local comment-start-skip octave-comment-start-skip)
746 (setq font-lock-defaults '(inferior-octave-font-lock-keywords nil nil))
748 (setq-local info-lookup-mode 'octave-mode)
749 (setq-local eldoc-documentation-function 'octave-eldoc-function)
751 (setq-local comint-input-ring-file-name
752 (or (getenv "OCTAVE_HISTFILE") "~/.octave_hist"))
753 (setq-local comint-input-ring-size
754 (string-to-number (or (getenv "OCTAVE_HISTSIZE") "1024")))
755 (comint-read-input-ring t)
756 (setq-local comint-dynamic-complete-functions
757 inferior-octave-dynamic-complete-functions)
758 (setq-local comint-prompt-read-only inferior-octave-prompt-read-only)
759 (add-hook 'comint-input-filter-functions
760 'inferior-octave-directory-tracker nil t)
761 ;; http://thread.gmane.org/gmane.comp.gnu.octave.general/48572
762 (add-hook 'window-configuration-change-hook
763 'inferior-octave-track-window-width-change nil t)
764 (setq-local compilation-error-regexp-alist inferior-octave-error-regexp-alist)
765 (setq-local compilation-mode-font-lock-keywords
766 inferior-octave-compilation-font-lock-keywords)
767 (compilation-shell-minor-mode 1)
768 (compilation-forget-errors))
770 ;;;###autoload
771 (defun inferior-octave (&optional arg)
772 "Run an inferior Octave process, I/O via `inferior-octave-buffer'.
773 This buffer is put in Inferior Octave mode. See `inferior-octave-mode'.
775 Unless ARG is non-nil, switches to this buffer.
777 The elements of the list `inferior-octave-startup-args' are sent as
778 command line arguments to the inferior Octave process on startup.
780 Additional commands to be executed on startup can be provided either in
781 the file specified by `inferior-octave-startup-file' or by the default
782 startup file, `~/.emacs-octave'."
783 (interactive "P")
784 (let ((buffer (get-buffer-create inferior-octave-buffer)))
785 (unless arg
786 (pop-to-buffer buffer))
787 (unless (comint-check-proc buffer)
788 (with-current-buffer buffer
789 (inferior-octave-startup)
790 (inferior-octave-mode)))
791 buffer))
793 ;;;###autoload
794 (defalias 'run-octave 'inferior-octave)
796 (defun inferior-octave-startup ()
797 "Start an inferior Octave process."
798 (let ((proc (comint-exec-1
799 (substring inferior-octave-buffer 1 -1)
800 inferior-octave-buffer
801 inferior-octave-program
802 (append
803 inferior-octave-startup-args
804 ;; --no-gui is introduced in Octave > 3.7
805 (and (not (member "--no-gui" inferior-octave-startup-args))
806 (zerop (process-file inferior-octave-program
807 nil nil nil "--no-gui" "--help"))
808 '("--no-gui"))))))
809 (set-process-filter proc 'inferior-octave-output-digest)
810 (setq inferior-octave-process proc
811 inferior-octave-output-list nil
812 inferior-octave-output-string nil
813 inferior-octave-receive-in-progress t)
815 ;; This may look complicated ... However, we need to make sure that
816 ;; we additional startup code only AFTER Octave is ready (otherwise,
817 ;; output may be mixed up). Hence, we need to digest the Octave
818 ;; output to see when it issues a prompt.
819 (while inferior-octave-receive-in-progress
820 (unless (inferior-octave-process-live-p)
821 ;; Spit out the error messages.
822 (when inferior-octave-output-list
823 (princ (concat (mapconcat 'identity inferior-octave-output-list "\n")
824 "\n")
825 (process-mark inferior-octave-process)))
826 (error "Process `%s' died" inferior-octave-process))
827 (accept-process-output inferior-octave-process))
828 (goto-char (point-max))
829 (set-marker (process-mark proc) (point))
830 (insert-before-markers
831 (concat
832 (if (not (bobp)) "\f\n")
833 (if inferior-octave-output-list
834 (concat (mapconcat
835 'identity inferior-octave-output-list "\n")
836 "\n"))))
838 ;; An empty secondary prompt, as e.g. obtained by '--braindead',
839 ;; means trouble.
840 (inferior-octave-send-list-and-digest (list "PS2\n"))
841 (when (string-match "\\(PS2\\|ans\\) = *$"
842 (car inferior-octave-output-list))
843 (inferior-octave-send-list-and-digest (list "PS2 ('> ');\n")))
845 (inferior-octave-send-list-and-digest
846 (list "disp (getenv ('OCTAVE_SRCDIR'))\n"))
847 (process-put proc 'octave-srcdir
848 (unless (equal (car inferior-octave-output-list) "")
849 (car inferior-octave-output-list)))
851 ;; O.K., now we are ready for the Inferior Octave startup commands.
852 (inferior-octave-send-list-and-digest
853 (list "more off;\n"
854 (unless (equal inferior-octave-output-string ">> ")
855 ;; See http://hg.savannah.gnu.org/hgweb/octave/rev/708173343c50
856 "PS1 ('octave> ');\n")
857 (when (and inferior-octave-startup-file
858 (file-exists-p inferior-octave-startup-file))
859 (format "source ('%s');\n" inferior-octave-startup-file))))
860 (when inferior-octave-output-list
861 (insert-before-markers
862 (mapconcat 'identity inferior-octave-output-list "\n")))
864 ;; And finally, everything is back to normal.
865 (set-process-filter proc 'comint-output-filter)
866 ;; Just in case, to be sure a cd in the startup file won't have
867 ;; detrimental effects.
868 (with-demoted-errors (inferior-octave-resync-dirs))
869 ;; Generate a proper prompt, which is critical to
870 ;; `comint-history-isearch-backward-regexp'. Bug#14433.
871 (comint-send-string proc "\n")))
873 (defun inferior-octave-completion-table ()
874 (completion-table-with-cache
875 (lambda (command)
876 (inferior-octave-send-list-and-digest
877 (list (format "completion_matches ('%s');\n" command)))
878 (delete-consecutive-dups
879 (sort inferior-octave-output-list 'string-lessp)))))
881 (defun inferior-octave-completion-at-point ()
882 "Return the data to complete the Octave symbol at point."
883 ;; http://debbugs.gnu.org/14300
884 (unless (string-match-p "/" (or (comint--match-partial-filename) ""))
885 (let ((beg (save-excursion
886 (skip-syntax-backward "w_" (comint-line-beginning-position))
887 (point)))
888 (end (point)))
889 (when (and beg (> end beg))
890 (list beg end (completion-table-in-turn
891 (inferior-octave-completion-table)
892 'comint-completion-file-name-table))))))
894 (define-obsolete-function-alias 'inferior-octave-complete
895 'completion-at-point "24.1")
897 (defun inferior-octave-dynamic-list-input-ring ()
898 "List the buffer's input history in a help buffer."
899 ;; We cannot use `comint-dynamic-list-input-ring', because it replaces
900 ;; "completion" by "history reference" ...
901 (interactive)
902 (if (or (not (ring-p comint-input-ring))
903 (ring-empty-p comint-input-ring))
904 (message "No history")
905 (let ((history nil)
906 (history-buffer " *Input History*")
907 (index (1- (ring-length comint-input-ring)))
908 (conf (current-window-configuration)))
909 ;; We have to build up a list ourselves from the ring vector.
910 (while (>= index 0)
911 (setq history (cons (ring-ref comint-input-ring index) history)
912 index (1- index)))
913 ;; Change "completion" to "history reference"
914 ;; to make the display accurate.
915 (with-output-to-temp-buffer history-buffer
916 (display-completion-list history)
917 (set-buffer history-buffer))
918 (message "Hit space to flush")
919 (let ((ch (read-event)))
920 (if (eq ch ?\ )
921 (set-window-configuration conf)
922 (push ch unread-command-events))))))
924 (defun inferior-octave-output-digest (_proc string)
925 "Special output filter for the inferior Octave process.
926 Save all output between newlines into `inferior-octave-output-list', and
927 the rest to `inferior-octave-output-string'."
928 (setq string (concat inferior-octave-output-string string))
929 (while (string-match "\n" string)
930 (setq inferior-octave-output-list
931 (append inferior-octave-output-list
932 (list (substring string 0 (match-beginning 0))))
933 string (substring string (match-end 0))))
934 (if (string-match inferior-octave-prompt string)
935 (setq inferior-octave-receive-in-progress nil))
936 (setq inferior-octave-output-string string))
938 (defun inferior-octave-check-process ()
939 (or (inferior-octave-process-live-p)
940 (error (substitute-command-keys
941 "No inferior octave process running. Type \\[run-octave]"))))
943 (defun inferior-octave-send-list-and-digest (list)
944 "Send LIST to the inferior Octave process and digest the output.
945 The elements of LIST have to be strings and are sent one by one. All
946 output is passed to the filter `inferior-octave-output-digest'."
947 (inferior-octave-check-process)
948 (let* ((proc inferior-octave-process)
949 (filter (process-filter proc))
950 string)
951 (set-process-filter proc 'inferior-octave-output-digest)
952 (setq inferior-octave-output-list nil)
953 (unwind-protect
954 (while (setq string (car list))
955 (setq inferior-octave-output-string nil
956 inferior-octave-receive-in-progress t)
957 (comint-send-string proc string)
958 (while inferior-octave-receive-in-progress
959 (accept-process-output proc))
960 (setq list (cdr list)))
961 (set-process-filter proc filter))))
963 (defvar inferior-octave-directory-tracker-resync nil)
964 (make-variable-buffer-local 'inferior-octave-directory-tracker-resync)
966 (defun inferior-octave-directory-tracker (string)
967 "Tracks `cd' commands issued to the inferior Octave process.
968 Use \\[inferior-octave-resync-dirs] to resync if Emacs gets confused."
969 (when inferior-octave-directory-tracker-resync
970 (or (inferior-octave-resync-dirs 'noerror)
971 (setq inferior-octave-directory-tracker-resync nil)))
972 (cond
973 ((string-match "^[ \t]*cd[ \t;]*$" string)
974 (cd "~"))
975 ((string-match "^[ \t]*cd[ \t]+\\([^ \t\n;]*\\)[ \t\n;]*" string)
976 (condition-case err
977 (cd (match-string 1 string))
978 (error (setq inferior-octave-directory-tracker-resync t)
979 (message "%s: `%s'"
980 (error-message-string err)
981 (match-string 1 string)))))))
983 (defun inferior-octave-resync-dirs (&optional noerror)
984 "Resync the buffer's idea of the current directory.
985 This command queries the inferior Octave process about its current
986 directory and makes this the current buffer's default directory."
987 (interactive)
988 (inferior-octave-send-list-and-digest '("disp (pwd ())\n"))
989 (condition-case err
990 (progn
991 (cd (car inferior-octave-output-list))
993 (error (unless noerror (signal (car err) (cdr err))))))
995 (defcustom inferior-octave-minimal-columns 80
996 "The minimal column width for the inferior Octave process."
997 :type 'integer
998 :group 'octave
999 :version "24.4")
1001 (defvar inferior-octave-last-column-width nil)
1003 (defun inferior-octave-track-window-width-change ()
1004 ;; http://thread.gmane.org/gmane.comp.gnu.octave.general/48572
1005 (let ((width (max inferior-octave-minimal-columns (window-width))))
1006 (unless (eq inferior-octave-last-column-width width)
1007 (setq-local inferior-octave-last-column-width width)
1008 (when (inferior-octave-process-live-p)
1009 (inferior-octave-send-list-and-digest
1010 (list (format "putenv ('COLUMNS', '%s');\n" width)))))))
1013 ;;; Miscellaneous useful functions
1015 (defun octave-in-comment-p ()
1016 "Return non-nil if point is inside an Octave comment."
1017 (nth 4 (syntax-ppss)))
1019 (defun octave-in-string-p ()
1020 "Return non-nil if point is inside an Octave string."
1021 (nth 3 (syntax-ppss)))
1023 (defun octave-in-string-or-comment-p ()
1024 "Return non-nil if point is inside an Octave string or comment."
1025 (nth 8 (syntax-ppss)))
1027 (defun octave-looking-at-kw (regexp)
1028 "Like `looking-at', but sets `case-fold-search' nil."
1029 (let ((case-fold-search nil))
1030 (looking-at regexp)))
1032 (defun octave-maybe-insert-continuation-string ()
1033 (if (or (octave-in-comment-p)
1034 (save-excursion
1035 (beginning-of-line)
1036 (looking-at octave-continuation-regexp)))
1038 (delete-horizontal-space)
1039 (insert (concat " " octave-continuation-string))))
1041 (defun octave-completing-read ()
1042 (let ((def (or (thing-at-point 'symbol)
1043 (save-excursion
1044 (skip-syntax-backward "-(")
1045 (thing-at-point 'symbol)))))
1046 (completing-read
1047 (format (if def "Function (default %s): "
1048 "Function: ") def)
1049 (inferior-octave-completion-table)
1050 nil nil nil nil def)))
1052 (defun octave-goto-function-definition (fn)
1053 "Go to the function definition of FN in current buffer."
1054 (let ((search
1055 (lambda (re sub)
1056 (let ((orig (point)) found)
1057 (goto-char (point-min))
1058 (while (and (not found) (re-search-forward re nil t))
1059 (when (and (equal (match-string sub) fn)
1060 (not (nth 8 (syntax-ppss))))
1061 (setq found t)))
1062 (unless found (goto-char orig))
1063 found))))
1064 (pcase (and buffer-file-name (file-name-extension buffer-file-name))
1065 (`"cc" (funcall search
1066 "\\_<DEFUN\\(?:_DLD\\)?\\s-*(\\s-*\\(\\(?:\\sw\\|\\s_\\)+\\)" 1))
1067 (_ (funcall search octave-function-header-regexp 3)))))
1069 (defun octave-function-file-p ()
1070 "Return non-nil if the first token is \"function\".
1071 The value is (START END NAME-START NAME-END) of the function."
1072 (save-excursion
1073 (goto-char (point-min))
1074 (when (equal (funcall smie-forward-token-function) "function")
1075 (forward-word -1)
1076 (let* ((start (point))
1077 (end (progn (forward-sexp 1) (point)))
1078 (name (when (progn
1079 (goto-char start)
1080 (re-search-forward octave-function-header-regexp
1081 end t))
1082 (list (match-beginning 3) (match-end 3)))))
1083 (cons start (cons end name))))))
1085 ;; Like forward-comment but stop at non-comment blank
1086 (defun octave-skip-comment-forward (limit)
1087 (let ((ppss (syntax-ppss)))
1088 (if (nth 4 ppss)
1089 (goto-char (nth 8 ppss))
1090 (goto-char (or (comment-search-forward limit t) (point)))))
1091 (while (and (< (point) limit) (looking-at-p "\\s<"))
1092 (forward-comment 1)))
1094 ;;; First non-copyright comment block
1095 (defun octave-function-file-comment ()
1096 "Beginning and end positions of the function file comment."
1097 (save-excursion
1098 (goto-char (point-min))
1099 ;; Copyright block: octave/libinterp/parse-tree/lex.ll around line 1634
1100 (while (save-excursion
1101 (when (comment-search-forward (point-max) t)
1102 (when (eq (char-after) ?\{) ; case of block comment
1103 (forward-char 1))
1104 (skip-syntax-forward "-")
1105 (let ((case-fold-search t))
1106 (looking-at-p "\\(?:copyright\\|author\\)\\_>"))))
1107 (octave-skip-comment-forward (point-max)))
1108 (let ((beg (comment-search-forward (point-max) t)))
1109 (when beg
1110 (goto-char beg)
1111 (octave-skip-comment-forward (point-max))
1112 (list beg (point))))))
1114 (defun octave-sync-function-file-names ()
1115 "Ensure function name agree with function file name.
1116 See Info node `(octave)Function Files'."
1117 (interactive)
1118 (when buffer-file-name
1119 (pcase-let ((`(,start ,_end ,name-start ,name-end)
1120 (octave-function-file-p)))
1121 (when (and start name-start)
1122 (let* ((func (buffer-substring name-start name-end))
1123 (file (file-name-sans-extension
1124 (file-name-nondirectory buffer-file-name)))
1125 (help-form (format-message "\
1126 a: Use function name `%s'
1127 b: Use file name `%s'
1128 q: Don't fix\n" func file))
1129 (c (unless (equal file func)
1130 (save-window-excursion
1131 (help-form-show)
1132 (read-char-choice
1133 "Which name to use? (a/b/q) " '(?a ?b ?q))))))
1134 (pcase c
1135 (`?a (let ((newname (expand-file-name
1136 (concat func (file-name-extension
1137 buffer-file-name t)))))
1138 (when (or (not (file-exists-p newname))
1139 (yes-or-no-p
1140 (format "Target file %s exists; proceed? " newname)))
1141 (when (file-exists-p buffer-file-name)
1142 (rename-file buffer-file-name newname t))
1143 (set-visited-file-name newname))))
1144 (`?b (save-excursion
1145 (goto-char name-start)
1146 (delete-region name-start name-end)
1147 (insert file)))))))))
1149 (defun octave-update-function-file-comment (beg end)
1150 "Query replace function names in function file comment."
1151 (interactive
1152 (progn
1153 (barf-if-buffer-read-only)
1154 (if (use-region-p)
1155 (list (region-beginning) (region-end))
1156 (or (octave-function-file-comment)
1157 (error "No function file comment found")))))
1158 (save-excursion
1159 (let* ((bounds (or (octave-function-file-p)
1160 (error "Not in a function file buffer")))
1161 (func (if (cddr bounds)
1162 (apply #'buffer-substring (cddr bounds))
1163 (error "Function name not found")))
1164 (old-func (progn
1165 (goto-char beg)
1166 (when (re-search-forward
1167 "[=}]\\s-*\\(\\(?:\\sw\\|\\s_\\)+\\)\\_>"
1168 (min (line-end-position 4) end)
1170 (match-string 1))))
1171 (old-func (read-string (format (if old-func
1172 "Name to replace (default %s): "
1173 "Name to replace: ")
1174 old-func)
1175 nil nil old-func)))
1176 (if (and func old-func (not (equal func old-func)))
1177 (perform-replace old-func func 'query
1178 nil 'delimited nil nil beg end)
1179 (message "Function names match")))))
1181 (defface octave-function-comment-block
1182 '((t (:inherit font-lock-doc-face)))
1183 "Face used to highlight function comment block."
1184 :group 'octave)
1186 (eval-when-compile (require 'texinfo))
1188 (defun octave-font-lock-texinfo-comment ()
1189 (let ((kws
1190 (eval-when-compile
1191 (delq nil (mapcar
1192 (lambda (kw)
1193 (if (numberp (nth 1 kw))
1194 `(,(nth 0 kw) ,(nth 1 kw) ,(nth 2 kw) prepend)
1195 (message "Ignoring Texinfo highlight: %S" kw)))
1196 texinfo-font-lock-keywords)))))
1197 (font-lock-add-keywords
1199 `((,(lambda (limit)
1200 (while (and (< (point) limit)
1201 (search-forward "-*- texinfo -*-" limit t)
1202 (octave-in-comment-p))
1203 (let ((beg (nth 8 (syntax-ppss)))
1204 (end (progn
1205 (octave-skip-comment-forward (point-max))
1206 (point))))
1207 (put-text-property beg end 'font-lock-multiline t)
1208 (font-lock-prepend-text-property
1209 beg end 'face 'octave-function-comment-block)
1210 (dolist (kw kws)
1211 (goto-char beg)
1212 (while (re-search-forward (car kw) end 'move)
1213 (font-lock-apply-highlight (cdr kw))))))
1214 nil)))
1215 'append)))
1218 ;;; Indentation
1220 (defun octave-indent-new-comment-line (&optional soft)
1221 "Break Octave line at point, continuing comment if within one.
1222 Insert `octave-continuation-string' before breaking the line
1223 unless inside a list. Signal an error if within a single-quoted
1224 string."
1225 (interactive)
1226 (funcall comment-line-break-function soft))
1228 (defun octave--indent-new-comment-line (orig &rest args)
1229 (cond
1230 ((octave-in-comment-p) nil)
1231 ((eq (octave-in-string-p) ?')
1232 (error "Cannot split a single-quoted string"))
1233 ((eq (octave-in-string-p) ?\")
1234 (insert octave-continuation-string))
1236 (delete-horizontal-space)
1237 (unless (and (cadr (syntax-ppss))
1238 (eq (char-after (cadr (syntax-ppss))) ?\())
1239 (insert " " octave-continuation-string))))
1240 (apply orig args)
1241 (indent-according-to-mode))
1243 (define-obsolete-function-alias
1244 'octave-indent-defun 'prog-indent-sexp "24.4")
1247 ;;; Motion
1248 (defun octave-next-code-line (&optional arg)
1249 "Move ARG lines of Octave code forward (backward if ARG is negative).
1250 Skips past all empty and comment lines. Default for ARG is 1.
1252 On success, return 0. Otherwise, go as far as possible and return -1."
1253 (interactive "p")
1254 (or arg (setq arg 1))
1255 (beginning-of-line)
1256 (let ((n 0)
1257 (inc (if (> arg 0) 1 -1)))
1258 (while (and (/= arg 0) (= n 0))
1259 (setq n (forward-line inc))
1260 (while (and (= n 0)
1261 (looking-at "\\s-*\\($\\|\\s<\\)"))
1262 (setq n (forward-line inc)))
1263 (setq arg (- arg inc)))
1266 (defun octave-previous-code-line (&optional arg)
1267 "Move ARG lines of Octave code backward (forward if ARG is negative).
1268 Skips past all empty and comment lines. Default for ARG is 1.
1270 On success, return 0. Otherwise, go as far as possible and return -1."
1271 (interactive "p")
1272 (or arg (setq arg 1))
1273 (octave-next-code-line (- arg)))
1275 (defun octave-beginning-of-line ()
1276 "Move point to beginning of current Octave line.
1277 If on an empty or comment line, go to the beginning of that line.
1278 Otherwise, move backward to the beginning of the first Octave code line
1279 which is not inside a continuation statement, i.e., which does not
1280 follow a code line ending with `...' or is inside an open
1281 parenthesis list."
1282 (interactive)
1283 (beginning-of-line)
1284 (unless (looking-at "\\s-*\\($\\|\\s<\\)")
1285 (while (or (when (cadr (syntax-ppss))
1286 (goto-char (cadr (syntax-ppss)))
1287 (beginning-of-line)
1289 (and (or (looking-at "\\s-*\\($\\|\\s<\\)")
1290 (save-excursion
1291 (if (zerop (octave-previous-code-line))
1292 (looking-at octave-continuation-regexp))))
1293 (zerop (forward-line -1)))))))
1295 (defun octave-end-of-line ()
1296 "Move point to end of current Octave line.
1297 If on an empty or comment line, go to the end of that line.
1298 Otherwise, move forward to the end of the first Octave code line which
1299 does not end with `...' or is inside an open parenthesis list."
1300 (interactive)
1301 (end-of-line)
1302 (unless (save-excursion
1303 (beginning-of-line)
1304 (looking-at "\\s-*\\($\\|\\s<\\)"))
1305 (while (or (when (cadr (syntax-ppss))
1306 (condition-case nil
1307 (progn
1308 (up-list 1)
1309 (end-of-line)
1311 (error nil)))
1312 (and (save-excursion
1313 (beginning-of-line)
1314 (or (looking-at "\\s-*\\($\\|\\s<\\)")
1315 (looking-at octave-continuation-regexp)))
1316 (zerop (forward-line 1)))))
1317 (end-of-line)))
1319 (defun octave-mark-block ()
1320 "Put point at the beginning of this Octave block, mark at the end.
1321 The block marked is the one that contains point or follows point."
1322 (interactive)
1323 (if (and (looking-at "\\sw\\|\\s_")
1324 (looking-back "\\sw\\|\\s_" (1- (point))))
1325 (skip-syntax-forward "w_"))
1326 (unless (or (looking-at "\\s(")
1327 (save-excursion
1328 (let* ((token (funcall smie-forward-token-function))
1329 (level (assoc token smie-grammar)))
1330 (and level (not (numberp (cadr level)))))))
1331 (backward-up-list 1))
1332 (mark-sexp))
1334 (defun octave-beginning-of-defun (&optional arg)
1335 "Octave-specific `beginning-of-defun-function' (which see)."
1336 (or arg (setq arg 1))
1337 ;; Move out of strings or comments.
1338 (when (octave-in-string-or-comment-p)
1339 (goto-char (octave-in-string-or-comment-p)))
1340 (letrec ((orig (point))
1341 (toplevel (lambda (pos)
1342 (condition-case nil
1343 (progn
1344 (backward-up-list 1)
1345 (funcall toplevel (point)))
1346 (scan-error pos)))))
1347 (goto-char (funcall toplevel (point)))
1348 (when (and (> arg 0) (/= orig (point)))
1349 (setq arg (1- arg)))
1350 (forward-sexp (- arg))
1351 (and (< arg 0) (forward-sexp -1))
1352 (/= orig (point))))
1354 (defun octave-fill-paragraph (&optional _arg)
1355 "Fill paragraph of Octave code, handling Octave comments."
1356 ;; FIXME: difference with generic fill-paragraph:
1357 ;; - code lines are only split, never joined.
1358 ;; - \n that end comments are never removed.
1359 ;; - insert continuation marker when splitting code lines.
1360 (interactive "P")
1361 (save-excursion
1362 (let ((end (progn (forward-paragraph) (copy-marker (point) t)))
1363 (beg (progn
1364 (forward-paragraph -1)
1365 (skip-chars-forward " \t\n")
1366 (beginning-of-line)
1367 (point)))
1368 (cfc (current-fill-column))
1369 comment-prefix)
1370 (goto-char beg)
1371 (while (< (point) end)
1372 (condition-case nil
1373 (indent-according-to-mode)
1374 (error nil))
1375 (move-to-column cfc)
1376 ;; First check whether we need to combine non-empty comment lines
1377 (if (and (< (current-column) cfc)
1378 (octave-in-comment-p)
1379 (not (save-excursion
1380 (beginning-of-line)
1381 (looking-at "^\\s-*\\s<+\\s-*$"))))
1382 ;; This is a nonempty comment line which does not extend
1383 ;; past the fill column. If it is followed by a nonempty
1384 ;; comment line with the same comment prefix, try to
1385 ;; combine them, and repeat this until either we reach the
1386 ;; fill-column or there is nothing more to combine.
1387 (progn
1388 ;; Get the comment prefix
1389 (save-excursion
1390 (beginning-of-line)
1391 (while (and (re-search-forward "\\s<+")
1392 (not (octave-in-comment-p))))
1393 (setq comment-prefix (match-string 0)))
1394 ;; And keep combining ...
1395 (while (and (< (current-column) cfc)
1396 (save-excursion
1397 (forward-line 1)
1398 (and (looking-at
1399 (concat "^\\s-*"
1400 comment-prefix
1401 "\\S<"))
1402 (not (looking-at
1403 (concat "^\\s-*"
1404 comment-prefix
1405 "\\s-*$"))))))
1406 (delete-char 1)
1407 (re-search-forward comment-prefix)
1408 (delete-region (match-beginning 0) (match-end 0))
1409 (fixup-whitespace)
1410 (move-to-column cfc))))
1411 ;; We might also try to combine continued code lines> Perhaps
1412 ;; some other time ...
1413 (skip-chars-forward "^ \t\n")
1414 (delete-horizontal-space)
1415 (if (or (< (current-column) cfc)
1416 (and (= (current-column) cfc) (eolp)))
1417 (forward-line 1)
1418 (if (not (eolp)) (insert " "))
1419 (or (funcall normal-auto-fill-function)
1420 (forward-line 1))))
1421 t)))
1423 (defun octave-completion-at-point ()
1424 "Find the text to complete and the corresponding table."
1425 (let* ((beg (save-excursion (skip-syntax-backward "w_") (point)))
1426 (end (point)))
1427 (if (< beg (point))
1428 ;; Extend region past point, if applicable.
1429 (save-excursion (skip-syntax-forward "w_")
1430 (setq end (point))))
1431 (when (> end beg)
1432 (list beg end (or (and (inferior-octave-process-live-p)
1433 (inferior-octave-completion-table))
1434 octave-reserved-words)))))
1436 (define-obsolete-function-alias 'octave-complete-symbol
1437 'completion-at-point "24.1")
1439 (defun octave-add-log-current-defun ()
1440 "A function for `add-log-current-defun-function' (which see)."
1441 (save-excursion
1442 (end-of-line)
1443 (and (beginning-of-defun)
1444 (re-search-forward octave-function-header-regexp
1445 (line-end-position) t)
1446 (match-string 3))))
1449 ;;; Electric characters && friends
1450 (define-skeleton octave-insert-defun
1451 "Insert an Octave function skeleton.
1452 Prompt for the function's name, arguments and return values (to be
1453 entered without parens)."
1454 (let* ((defname (file-name-sans-extension (buffer-name)))
1455 (name (read-string (format "Function name (default %s): " defname)
1456 nil nil defname))
1457 (args (read-string "Arguments: "))
1458 (vals (read-string "Return values: ")))
1459 (format "%s%s (%s)"
1460 (cond
1461 ((string-equal vals "") vals)
1462 ((string-match "[ ,]" vals) (concat "[" vals "] = "))
1463 (t (concat vals " = ")))
1464 name
1465 args))
1466 \n octave-block-comment-start "usage: " str \n
1467 octave-block-comment-start '(delete-horizontal-space) \n
1468 octave-block-comment-start '(delete-horizontal-space) \n
1469 "function " > str \n
1470 _ \n
1471 "endfunction" > \n)
1473 ;;; Communication with the inferior Octave process
1474 (defun octave-kill-process ()
1475 "Kill inferior Octave process and its buffer."
1476 (interactive)
1477 (when (and (buffer-live-p (get-buffer inferior-octave-buffer))
1478 (or (yes-or-no-p (format "Kill %S and its buffer? "
1479 inferior-octave-process))
1480 (user-error "Aborted")))
1481 (when (inferior-octave-process-live-p)
1482 (set-process-query-on-exit-flag inferior-octave-process nil)
1483 (process-send-string inferior-octave-process "quit;\n")
1484 (accept-process-output inferior-octave-process))
1485 (kill-buffer inferior-octave-buffer)))
1487 (defun octave-show-process-buffer ()
1488 "Make sure that `inferior-octave-buffer' is displayed."
1489 (interactive)
1490 (if (get-buffer inferior-octave-buffer)
1491 (display-buffer inferior-octave-buffer)
1492 (message "No buffer named %s" inferior-octave-buffer)))
1494 (defun octave-hide-process-buffer ()
1495 "Delete all windows that display `inferior-octave-buffer'."
1496 (interactive)
1497 (if (get-buffer inferior-octave-buffer)
1498 (delete-windows-on inferior-octave-buffer)
1499 (message "No buffer named %s" inferior-octave-buffer)))
1501 (defun octave-source-file (file)
1502 "Execute FILE in the inferior Octave process.
1503 This is done using Octave's source function. FILE defaults to
1504 current buffer file unless called with a prefix arg \\[universal-argument]."
1505 (interactive (list (or (and (not current-prefix-arg) buffer-file-name)
1506 (read-file-name "File: " nil nil t))))
1507 (or (stringp file)
1508 (signal 'wrong-type-argument (list 'stringp file)))
1509 (inferior-octave t)
1510 (with-current-buffer inferior-octave-buffer
1511 (comint-send-string inferior-octave-process
1512 (format "source '%s'\n" file))))
1514 (defun octave-send-region (beg end)
1515 "Send current region to the inferior Octave process."
1516 (interactive "r")
1517 (inferior-octave t)
1518 (let ((proc inferior-octave-process)
1519 (string (buffer-substring-no-properties beg end))
1520 line)
1521 (with-current-buffer inferior-octave-buffer
1522 ;; http://lists.gnu.org/archive/html/emacs-devel/2013-10/msg00095.html
1523 (compilation-forget-errors)
1524 (setq inferior-octave-output-list nil)
1525 (while (not (string-equal string ""))
1526 (if (string-match "\n" string)
1527 (setq line (substring string 0 (match-beginning 0))
1528 string (substring string (match-end 0)))
1529 (setq line string string ""))
1530 (setq inferior-octave-receive-in-progress t)
1531 (inferior-octave-send-list-and-digest (list (concat line "\n")))
1532 (while inferior-octave-receive-in-progress
1533 (accept-process-output proc))
1534 (insert-before-markers
1535 (mapconcat 'identity
1536 (append
1537 (if octave-send-echo-input (list line) (list ""))
1538 inferior-octave-output-list
1539 (list inferior-octave-output-string))
1540 "\n")))))
1541 (if octave-send-show-buffer
1542 (display-buffer inferior-octave-buffer)))
1544 (defun octave-send-buffer ()
1545 "Send current buffer to the inferior Octave process."
1546 (interactive)
1547 (octave-send-region (point-min) (point-max)))
1549 (defun octave-send-block ()
1550 "Send current Octave block to the inferior Octave process."
1551 (interactive)
1552 (save-excursion
1553 (octave-mark-block)
1554 (octave-send-region (point) (mark))))
1556 (defun octave-send-defun ()
1557 "Send current Octave function to the inferior Octave process."
1558 (interactive)
1559 (save-excursion
1560 (mark-defun)
1561 (octave-send-region (point) (mark))))
1563 (defun octave-send-line (&optional arg)
1564 "Send current Octave code line to the inferior Octave process.
1565 With positive prefix ARG, send that many lines.
1566 If `octave-send-line-auto-forward' is non-nil, go to the next unsent
1567 code line."
1568 (interactive "P")
1569 (or arg (setq arg 1))
1570 (if (> arg 0)
1571 (let (beg end)
1572 (beginning-of-line)
1573 (setq beg (point))
1574 (octave-next-code-line (- arg 1))
1575 (end-of-line)
1576 (setq end (point))
1577 (if octave-send-line-auto-forward
1578 (octave-next-code-line 1))
1579 (octave-send-region beg end))))
1581 (defun octave-eval-print-last-sexp ()
1582 "Evaluate Octave sexp before point and print value into current buffer."
1583 (interactive)
1584 (inferior-octave t)
1585 (let ((standard-output (current-buffer))
1586 (print-escape-newlines nil)
1587 (opoint (point)))
1588 (terpri)
1589 (prin1
1590 (save-excursion
1591 (forward-sexp -1)
1592 (inferior-octave-send-list-and-digest
1593 (list (concat (buffer-substring-no-properties (point) opoint)
1594 "\n")))
1595 (mapconcat 'identity inferior-octave-output-list "\n")))
1596 (terpri)))
1600 (defcustom octave-eldoc-message-style 'auto
1601 "Octave eldoc message style: auto, oneline, multiline."
1602 :type '(choice (const :tag "Automatic" auto)
1603 (const :tag "One Line" oneline)
1604 (const :tag "Multi Line" multiline))
1605 :group 'octave
1606 :version "24.4")
1608 ;; (FN SIGNATURE1 SIGNATURE2 ...)
1609 (defvar octave-eldoc-cache nil)
1611 (defun octave-eldoc-function-signatures (fn)
1612 (unless (equal fn (car octave-eldoc-cache))
1613 (inferior-octave-send-list-and-digest
1614 (list (format "print_usage ('%s');\n" fn)))
1615 (let (result)
1616 (dolist (line inferior-octave-output-list)
1617 (when (string-match
1618 "\\s-*\\(?:--[^:]+\\|usage\\):\\s-*\\(.*\\)$"
1619 line)
1620 (push (match-string 1 line) result)))
1621 (setq octave-eldoc-cache
1622 (cons (substring-no-properties fn)
1623 (nreverse result)))))
1624 (cdr octave-eldoc-cache))
1626 (defun octave-eldoc-function ()
1627 "A function for `eldoc-documentation-function' (which see)."
1628 (when (inferior-octave-process-live-p)
1629 (let* ((ppss (syntax-ppss))
1630 (paren-pos (cadr ppss))
1631 (fn (save-excursion
1632 (if (and paren-pos
1633 ;; PAREN-POS must be after the prompt
1634 (>= paren-pos
1635 (if (eq (get-buffer-process (current-buffer))
1636 inferior-octave-process)
1637 (process-mark inferior-octave-process)
1638 (point-min)))
1639 (or (not (eq (get-buffer-process (current-buffer))
1640 inferior-octave-process))
1641 (< (process-mark inferior-octave-process)
1642 paren-pos))
1643 (eq (char-after paren-pos) ?\())
1644 (goto-char paren-pos)
1645 (setq paren-pos nil))
1646 (when (or (< (skip-syntax-backward "-") 0) paren-pos)
1647 (thing-at-point 'symbol))))
1648 (sigs (and fn (octave-eldoc-function-signatures fn)))
1649 (oneline (mapconcat 'identity sigs
1650 (propertize " | " 'face 'warning)))
1651 (multiline (mapconcat (lambda (s) (concat "-- " s)) sigs "\n")))
1653 ;; Return the value according to style.
1654 (pcase octave-eldoc-message-style
1655 (`auto (if (< (length oneline) (window-width (minibuffer-window)))
1656 oneline
1657 multiline))
1658 (`oneline oneline)
1659 (`multiline multiline)))))
1661 (defcustom octave-help-buffer "*Octave Help*"
1662 "Buffer name for `octave-help'."
1663 :type 'string
1664 :group 'octave
1665 :version "24.4")
1667 ;; Used in a mode derived from help-mode.
1668 (declare-function help-button-action "help-mode" (button))
1670 (define-button-type 'octave-help-file
1671 'follow-link t
1672 'action #'help-button-action
1673 'help-function 'octave-find-definition)
1675 (define-button-type 'octave-help-function
1676 'follow-link t
1677 'action (lambda (b)
1678 (octave-help
1679 (buffer-substring (button-start b) (button-end b)))))
1681 (defvar octave-help-mode-map
1682 (let ((map (make-sparse-keymap)))
1683 (define-key map "\M-." 'octave-find-definition)
1684 (define-key map "\C-hd" 'octave-help)
1685 (define-key map "\C-ha" 'octave-lookfor)
1686 map))
1688 (define-derived-mode octave-help-mode help-mode "OctHelp"
1689 "Major mode for displaying Octave documentation."
1690 :abbrev-table nil
1691 :syntax-table octave-mode-syntax-table
1692 (eval-and-compile (require 'help-mode))
1693 ;; Don't highlight `EXAMPLE' as elisp symbols by using a regexp that
1694 ;; can never match.
1695 (setq-local help-xref-symbol-regexp "x\\`"))
1697 (defun octave-help (fn)
1698 "Display the documentation of FN."
1699 (interactive (list (octave-completing-read)))
1700 (inferior-octave-send-list-and-digest
1701 (list (format "help ('%s');\n" fn)))
1702 (let ((lines inferior-octave-output-list)
1703 (inhibit-read-only t))
1704 (when (string-match "error: \\(.*\\)$" (car lines))
1705 (error "%s" (match-string 1 (car lines))))
1706 (with-help-window octave-help-buffer
1707 (princ (mapconcat 'identity lines "\n"))
1708 (with-current-buffer octave-help-buffer
1709 ;; Bound to t so that `help-buffer' returns current buffer for
1710 ;; `help-setup-xref'.
1711 (let ((help-xref-following t))
1712 (help-setup-xref (list 'octave-help fn)
1713 (called-interactively-p 'interactive)))
1714 ;; Note: can be turned off by suppress_verbose_help_message.
1716 ;; Remove boring trailing text: Additional help for built-in functions
1717 ;; and operators ...
1718 (goto-char (point-max))
1719 (when (search-backward "\n\n\n" nil t)
1720 (goto-char (match-beginning 0))
1721 (delete-region (point) (point-max)))
1722 ;; File name highlight
1723 (goto-char (point-min))
1724 (when (re-search-forward "from the file \\(.*\\)$"
1725 (line-end-position)
1727 (let* ((file (match-string 1))
1728 (dir (file-name-directory
1729 (directory-file-name (file-name-directory file)))))
1730 (replace-match "" nil nil nil 1)
1731 (insert (substitute-command-keys "`"))
1732 ;; Include the parent directory which may be regarded as
1733 ;; the category for the FN.
1734 (help-insert-xref-button (file-relative-name file dir)
1735 'octave-help-file fn)
1736 (insert (substitute-command-keys "'"))))
1737 ;; Make 'See also' clickable.
1738 (with-syntax-table octave-mode-syntax-table
1739 (when (re-search-forward "^\\s-*See also:" nil t)
1740 (let ((end (save-excursion (re-search-forward "^\\s-*$" nil t))))
1741 (while (re-search-forward
1742 "\\s-*\\([^,\n]+?\\)\\s-*\\(?:[,]\\|[.]?$\\)" end t)
1743 (make-text-button (match-beginning 1) (match-end 1)
1744 :type 'octave-help-function)))))
1745 (octave-help-mode)))))
1747 (defun octave-lookfor (str &optional all)
1748 "Search for the string STR in all function help strings.
1749 If ALL is non-nil search the entire help string else only search the first
1750 sentence."
1751 (interactive "sSearch for: \nP")
1752 (inferior-octave-send-list-and-digest
1753 (list (format "lookfor (%s'%s');\n"
1754 (if all "'-all', " "")
1755 str)))
1756 (let ((lines inferior-octave-output-list))
1757 (when (and (stringp (car lines))
1758 (string-match "error: \\(.*\\)$" (car lines)))
1759 (error "%s" (match-string 1 (car lines))))
1760 (with-help-window octave-help-buffer
1761 (with-current-buffer octave-help-buffer
1762 (if lines
1763 (insert (mapconcat 'identity lines "\n"))
1764 (insert (format "Nothing found for \"%s\".\n" str)))
1765 ;; Bound to t so that `help-buffer' returns current buffer for
1766 ;; `help-setup-xref'.
1767 (let ((help-xref-following t))
1768 (help-setup-xref (list 'octave-lookfor str all)
1769 (called-interactively-p 'interactive)))
1770 (goto-char (point-min))
1771 (when lines
1772 (while (re-search-forward "^\\([^[:blank:]]+\\) " nil 'noerror)
1773 (make-text-button (match-beginning 1) (match-end 1)
1774 :type 'octave-help-function)))
1775 (unless all
1776 (goto-char (point-max))
1777 (insert "\nRetry with ")
1778 (insert-text-button "'-all'"
1779 'follow-link t
1780 'action #'(lambda (_b)
1781 (octave-lookfor str '-all)))
1782 (insert ".\n"))
1783 (octave-help-mode)))))
1785 (defcustom octave-source-directories nil
1786 "A list of directories for Octave sources.
1787 If the environment variable OCTAVE_SRCDIR is set, it is searched first."
1788 :type '(repeat directory)
1789 :group 'octave
1790 :version "24.4")
1792 (defun octave-source-directories ()
1793 (let ((srcdir (or (and inferior-octave-process
1794 (process-get inferior-octave-process 'octave-srcdir))
1795 (getenv "OCTAVE_SRCDIR"))))
1796 (if srcdir
1797 (cons srcdir octave-source-directories)
1798 octave-source-directories)))
1800 (defvar octave-find-definition-filename-function
1801 #'octave-find-definition-default-filename)
1803 (defun octave-find-definition-default-filename (name)
1804 "Default value for `octave-find-definition-filename-function'."
1805 (pcase (file-name-extension name)
1806 (`"oct"
1807 (octave-find-definition-default-filename
1808 (concat "libinterp/dldfcn/"
1809 (file-name-sans-extension (file-name-nondirectory name))
1810 ".cc")))
1811 (`"cc"
1812 (let ((file (or (locate-file name (octave-source-directories))
1813 (locate-file (file-name-nondirectory name)
1814 (octave-source-directories)))))
1815 (or (and file (file-exists-p file))
1816 (error "File `%s' not found" name))
1817 file))
1818 (`"mex"
1819 (if (yes-or-no-p (format-message "File `%s' may be binary; open? "
1820 (file-name-nondirectory name)))
1821 name
1822 (user-error "Aborted")))
1823 (_ name)))
1825 (defvar find-tag-marker-ring)
1827 (defun octave-find-definition (fn)
1828 "Find the definition of FN.
1829 Functions implemented in C++ can be found if
1830 variable `octave-source-directories' is set correctly."
1831 (interactive (list (octave-completing-read)))
1832 (require 'etags)
1833 (let ((orig (point)))
1834 (if (and (derived-mode-p 'octave-mode)
1835 (octave-goto-function-definition fn))
1836 (ring-insert find-tag-marker-ring (copy-marker orig))
1837 (inferior-octave-send-list-and-digest
1838 ;; help NAME is more verbose
1839 (list (format "\
1840 if iskeyword('%s') disp('`%s'' is a keyword') else which('%s') endif\n"
1841 fn fn fn)))
1842 (let (line file)
1843 ;; Skip garbage lines such as
1844 ;; warning: fmincg.m: possible Matlab-style ....
1845 (while (and (not file) (consp inferior-octave-output-list))
1846 (setq line (pop inferior-octave-output-list))
1847 (when (string-match "from the file \\(.*\\)$" line)
1848 (setq file (match-string 1 line))))
1849 (if (not file)
1850 (user-error "%s" (or line (format-message "`%s' not found" fn)))
1851 (ring-insert find-tag-marker-ring (point-marker))
1852 (setq file (funcall octave-find-definition-filename-function file))
1853 (when file
1854 (find-file file)
1855 (octave-goto-function-definition fn)))))))
1857 (provide 'octave)
1858 ;;; octave.el ends here