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