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