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