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