Don't break emacs <= 24.3 just yet
[bpt/emacs.git] / lisp / progmodes / octave.el
CommitLineData
4d2e94d1 1;;; octave.el --- editing octave source files under emacs -*- lexical-binding: t; -*-
f2727dfb 2
ba318903 3;; Copyright (C) 1997, 2001-2014 Free Software Foundation, Inc.
f2727dfb 4
f7fba1a8 5;; Author: Kurt Hornik <Kurt.Hornik@wu-wien.ac.at>
daf3dc79 6;; John Eaton <jwe@octave.org>
34dc21db 7;; Maintainer: emacs-devel@gnu.org
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)
2e611da6
LL
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)))))
2640d52e
LL
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
28d16ed3 62(defgroup octave nil
be64c05d 63 "Editing Octave code."
51d971b4
RS
64 :link '(custom-manual "(octave-mode)Top")
65 :link '(url-link "http://www.gnu.org/s/octave")
8ec3bce0 66 :link '(custom-group-link :tag "Font Lock Faces group" font-lock-faces)
28d16ed3
AS
67 :group 'languages)
68
070ccca4
LL
69(define-obsolete-function-alias 'octave-submit-bug-report
70 'report-emacs-bug "24.4")
e7017ef9 71
9b92c13b 72(define-abbrev-table 'octave-abbrev-table nil
e7017ef9 73 "Abbrev table for Octave's reserved words.
9b92c13b 74Used in `octave-mode' and `inferior-octave-mode' buffers.")
e7017ef9
RS
75
76(defvar octave-comment-char ?#
77 "Character to start an Octave comment.")
9b92c13b 78
42caeb89
LL
79(defvar octave-comment-start (char-to-string octave-comment-char)
80 "Octave-specific `comment-start' (which see).")
9b92c13b 81
42caeb89
LL
82(defvar octave-comment-start-skip "\\(^\\|\\S<\\)\\(?:%!\\|\\s<+\\)\\s-*"
83 "Octave-specific `comment-start-skip' (which see).")
e7017ef9
RS
84
85(defvar octave-begin-keywords
6980b0ca
LL
86 '("classdef" "do" "enumeration" "events" "for" "function" "if" "methods"
87 "parfor" "properties" "switch" "try" "unwind_protect" "while"))
9b92c13b 88
e7017ef9 89(defvar octave-else-keywords
6e6d2764 90 '("case" "catch" "else" "elseif" "otherwise" "unwind_protect_cleanup"))
9b92c13b 91
e7017ef9 92(defvar octave-end-keywords
6980b0ca
LL
93 '("endclassdef" "endenumeration" "endevents" "endfor" "endfunction" "endif"
94 "endmethods" "endparfor" "endproperties" "endswitch" "end_try_catch"
b2ad70b6 95 "end_unwind_protect" "endwhile" "until" "end"))
e7017ef9
RS
96
97(defvar octave-reserved-words
6e6d2764
KH
98 (append octave-begin-keywords
99 octave-else-keywords
100 octave-end-keywords
6980b0ca 101 '("break" "continue" "global" "persistent" "return"))
e7017ef9
RS
102 "Reserved words in Octave.")
103
e7017ef9 104(defvar octave-function-header-regexp
e92f3bd3 105 (concat "^\\s-*\\_<\\(function\\)\\_>"
ce8209d4 106 "\\([^=;(\n]*=[ \t]*\\|[ \t]*\\)\\(\\(?:\\w\\|\\s_\\)+\\)\\_>")
e7017ef9
RS
107 "Regexp to match an Octave function header.
108The string `function' and its name are given by the first and third
109parenthetical grouping.")
110
be64c05d 111\f
e22bbd48 112(defvar octave-mode-map
f2727dfb 113 (let ((map (make-sparse-keymap)))
f5a9432f
LL
114 (define-key map "\M-." 'octave-find-definition)
115 (define-key map "\M-\C-j" 'octave-indent-new-comment-line)
f2727dfb
RS
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)
a1506d29 119 (define-key map "\C-c\C-e" 'octave-end-of-line)
ec5d3ff7 120 (define-key map [remap down-list] 'smie-down-list)
f2727dfb 121 (define-key map "\C-c\M-\C-h" 'octave-mark-block)
e17b68ed
SM
122 (define-key map "\C-c]" 'smie-close-block)
123 (define-key map "\C-c/" 'smie-close-block)
b7260dd4 124 (define-key map "\C-c;" 'octave-update-function-file-comment)
d4d0f9b3 125 (define-key map "\C-hd" 'octave-help)
5af5ed08 126 (define-key map "\C-ha" 'octave-lookfor)
06e752b4 127 (define-key map "\C-c\C-l" 'octave-source-file)
34a463f1 128 (define-key map "\C-c\C-f" 'octave-insert-defun)
34a463f1
RS
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)
a1506d29 132 (define-key map "\C-c\C-ir" 'octave-send-region)
7e138a62 133 (define-key map "\C-c\C-ia" 'octave-send-buffer)
34a463f1 134 (define-key map "\C-c\C-is" 'octave-show-process-buffer)
ad64b83d 135 (define-key map "\C-c\C-iq" 'octave-hide-process-buffer)
34a463f1
RS
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)
a1506d29 140 (define-key map "\C-c\C-i\C-r" 'octave-send-region)
7e138a62 141 (define-key map "\C-c\C-i\C-a" 'octave-send-buffer)
34a463f1 142 (define-key map "\C-c\C-i\C-s" 'octave-show-process-buffer)
7a1beb6c 143 (define-key map "\C-c\C-i\C-q" 'octave-hide-process-buffer)
34a463f1 144 (define-key map "\C-c\C-i\C-k" 'octave-kill-process)
e22bbd48
SM
145 map)
146 "Keymap used in Octave mode.")
147
f2727dfb 148
ff80a446
SM
149
150(easy-menu-define octave-mode-menu octave-mode-map
151 "Menu for Octave mode."
e22bbd48 152 '("Octave"
ee44b62a
LL
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]
3ac7cff4 162 ["Documentation Lookup" info-lookup-symbol t]
ee44b62a 163 ["Help on Function" octave-help t]
5af5ed08 164 ["Search help" octave-lookfor t]
ee44b62a
LL
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 "---"
9b335362
LL
169 ["Function Syntax Hints" (eldoc-mode 'toggle)
170 :style toggle :selected (bound-and-true-p eldoc-mode)
ee44b62a 171 :help "Display function signatures after typing `SPC' or `('"]
976cb066
LL
172 ["Delimiter Matching" show-paren-mode
173 :style toggle :selected show-paren-mode
ee44b62a 174 :help "Highlight matched pairs such as `if ... end'"
976cb066 175 :visible (fboundp 'smie--matching-block-data)]
ee44b62a
LL
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 "---"
67885e8c 183 ("Debug"
ee44b62a
LL
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]
7e138a62 188 ["Send Buffer" octave-send-buffer t]
06e752b4 189 ["Source Current File" octave-source-file t]
ee44b62a
LL
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 "---"
51d971b4 194 ["Octave Mode Manual" (info "(octave-mode)Top") t]
ee44b62a
LL
195 ["Customize Octave" (customize-group 'octave) t]
196 ["Submit Bug Report" report-emacs-bug t]))
f2727dfb 197
cb3d3ec1 198(defvar octave-mode-syntax-table
f2727dfb
RS
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)
27135018 211 (modify-syntax-entry ?\\ "." table)
f2727dfb 212 (modify-syntax-entry ?\' "." table)
7210c33f 213 (modify-syntax-entry ?\` "." table)
c75c93c7 214 (modify-syntax-entry ?. "." table)
f2727dfb 215 (modify-syntax-entry ?\" "\"" table)
e92f3bd3 216 (modify-syntax-entry ?_ "_" table)
c5683ceb 217 ;; The "b" flag only applies to the second letter of the comstart
7e82caa7
SM
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.
c5683ceb 222 ;; So we need the new "c" comment style.
c82d5b11
SM
223 (modify-syntax-entry ?\% "< 13" table)
224 (modify-syntax-entry ?\# "< 13" table)
c5683ceb
SM
225 (modify-syntax-entry ?\{ "(} 2c" table)
226 (modify-syntax-entry ?\} "){ 4c" table)
f2727dfb 227 (modify-syntax-entry ?\n ">" table)
cb3d3ec1
SM
228 table)
229 "Syntax table in use in `octave-mode' buffers.")
f2727dfb 230
5b78d7fc
LL
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
28d16ed3 237(defcustom octave-blink-matching-block t
e22bbd48 238 "Control the blinking of matching Octave block keywords.
f2727dfb 239Non-nil means show matching begin of block when inserting a space,
28d16ed3
AS
240newline or semicolon after an else or end keyword."
241 :type 'boolean
242 :group 'octave)
ff80a446 243
28d16ed3 244(defcustom octave-block-offset 2
e22bbd48 245 "Extra indentation applied to statements in Octave block structures."
28d16ed3
AS
246 :type 'integer
247 :group 'octave)
f2727dfb 248
f2727dfb
RS
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
28d16ed3 253(defcustom octave-continuation-offset 4
e22bbd48 254 "Extra indentation applied to Octave continuation lines."
28d16ed3
AS
255 :type 'integer
256 :group 'octave)
38d8527b 257
e17b68ed
SM
258(eval-and-compile
259 (defconst octave-continuation-marker-regexp "\\\\\\|\\.\\.\\."))
38d8527b 260
f2727dfb 261(defvar octave-continuation-regexp
e17b68ed
SM
262 (concat "[^#%\n]*\\(" octave-continuation-marker-regexp
263 "\\)\\s-*\\(\\s<.*\\)?$"))
38d8527b
LL
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.")
f2727dfb 268
f2727dfb
RS
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
28d16ed3 275(defcustom octave-mode-hook nil
e22bbd48 276 "Hook to be run when Octave mode is started."
28d16ed3
AS
277 :type 'hook
278 :group 'octave)
279
280(defcustom octave-send-show-buffer t
e22bbd48 281 "Non-nil means display `inferior-octave-buffer' after sending to it."
28d16ed3
AS
282 :type 'boolean
283 :group 'octave)
9b92c13b 284
28d16ed3 285(defcustom octave-send-line-auto-forward t
e22bbd48 286 "Control auto-forward after sending to the inferior Octave process.
28d16ed3
AS
287Non-nil means always go to the next Octave code line after sending."
288 :type 'boolean
289 :group 'octave)
9b92c13b 290
28d16ed3 291(defcustom octave-send-echo-input t
e22bbd48 292 "Non-nil means echo input sent to the inferior Octave process."
28d16ed3
AS
293 :type 'boolean
294 :group 'octave)
f2727dfb
RS
295
296\f
e17b68ed
SM
297;;; SMIE indentation
298
299(require 'smie)
300
203a5572 301;; Use '__operators__' in Octave REPL to get a full list.
e17b68ed
SM
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
89acf735
SM
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")
6980b0ca
LL
336 ("parfor" exp "endparfor")
337 ("parfor" exp "end")
89acf735
SM
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")
6980b0ca
LL
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"))
89acf735
SM
362 ;; (fundesc (atom "=" atom))
363 ))
364
674728d4
SM
365(defconst octave-smie-grammar
366 (smie-prec2->grammar
e17b68ed 367 (smie-merge-prec2s
674728d4
SM
368 (smie-bnf->prec2 octave-smie-bnf-table
369 '((assoc "\n" ";")))
e17b68ed 370
674728d4 371 (smie-precs->prec2 octave-operator-table))))
e17b68ed
SM
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
7a7567d2
LL
378 (regexp-opt (remove "\n" (apply 'append
379 (mapcar 'cdr octave-operator-table)))))
e17b68ed
SM
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
ceb57e59
SM
416 ((and (looking-at "[%#\n]")
417 (not (or (save-excursion (skip-chars-backward " \t")
418 ;; Only add implicit ; when needed.
150194c3 419 (or (bolp) (eq (char-before) ?\;)))
ceb57e59
SM
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))
e17b68ed
SM
425 ;; Why bother distinguishing \n and ;?
426 ";") ;;"\n"
ceb57e59 427 ((progn (forward-comment (point-max)) nil))
e17b68ed
SM
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
c4d17d50
SM
441(defun octave-smie-rules (kind token)
442 (pcase (cons kind token)
674728d4
SM
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.
c4d17d50 447 (`(:elem . basic) octave-block-offset)
674728d4
SM
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))
c4d17d50 451 (`(:after . ";")
6980b0ca
LL
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"
674728d4
SM
456 "unwind_protect_cleanup")
457 (smie-rule-parent octave-block-offset)
c4d17d50 458 ;; For (invalid) code between switch and case.
b2856a6f 459 ;; (if (smie-rule-parent-p "switch") 4)
650cff3d 460 nil))))
e17b68ed 461
9dbdb67e
LL
462(defun octave-indent-comment ()
463 "A function for `smie-indent-functions' (which see)."
464 (save-excursion
465 (back-to-indentation)
2aeb3a1d
LL
466 (cond
467 ((octave-in-string-or-comment-p) nil)
f236dd84 468 ((looking-at-p "\\(\\s<\\)\\1\\{2,\\}")
2aeb3a1d 469 0)
b0e069c2
LL
470 ;; Exclude %{, %} and %!.
471 ((and (looking-at-p "\\s<\\(?:[^{}!]\\|$\\)")
f236dd84 472 (not (looking-at-p "\\(\\s<\\)\\1")))
2aeb3a1d 473 (comment-choose-indent)))))
9dbdb67e 474
203a5572
LL
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)
4d25fd7e 490 (condition-case nil
203a5572
LL
491 (progn
492 (goto-char beg)
493 (backward-up-list)
494 (when (memq (char-after) '(?\( ?\[ ?\{))
4d25fd7e
LL
495 (put-text-property beg end 'face nil))
496 (goto-char end))
497 (error (goto-char end))))))
203a5572
LL
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
03f70355 534(defvar electric-layout-rules)
b073dc4b 535
f2727dfb 536;;;###autoload
c82d5b11 537(define-derived-mode octave-mode prog-mode "Octave"
f2727dfb
RS
538 "Major mode for editing Octave code.
539
b7260dd4
LL
540Octave is a high-level language, primarily intended for numerical
541computations. It provides a convenient command line interface
542for solving linear and nonlinear problems numerically. Function
ed4bc201
RS
543definitions can also be stored in files and used in batch mode.
544
545See Info node `(octave-mode) Using Octave Mode' for more details.
546
547Key bindings:
548\\{octave-mode-map}"
9b92c13b 549 :abbrev-table octave-abbrev-table
ed4bc201 550 :group 'octave
c82d5b11 551
674728d4 552 (smie-setup octave-smie-grammar #'octave-smie-rules
c4d17d50
SM
553 :forward-token #'octave-smie-forward-token
554 :backward-token #'octave-smie-backward-token)
070ccca4 555 (setq-local smie-indent-basic 'octave-block-offset)
9dbdb67e 556 (add-hook 'smie-indent-functions #'octave-indent-comment nil t)
c4d17d50 557
070ccca4
LL
558 (setq-local smie-blink-matching-triggers
559 (cons ?\; smie-blink-matching-triggers))
c4d17d50
SM
560 (unless octave-blink-matching-block
561 (remove-hook 'post-self-insert-hook #'smie-blink-matching-open 'local))
89acf735 562
070ccca4
LL
563 (setq-local electric-indent-chars
564 (cons ?\; electric-indent-chars))
03f70355
SM
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).
070ccca4 567 (setq-local electric-layout-rules '((?\; . after)))
c82d5b11 568
38637cca 569 (setq-local comment-use-syntax t)
070ccca4
LL
570 (setq-local comment-start octave-comment-start)
571 (setq-local comment-end "")
b0e069c2 572 (setq-local comment-start-skip octave-comment-start-skip)
070ccca4
LL
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)
9cc3e83f 580
ee44b62a
LL
581 (setq-local fill-nobreak-predicate
582 (lambda () (eq (octave-in-string-p) ?')))
62efb35e
LL
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))))
c82d5b11 590
070ccca4 591 (setq font-lock-defaults '(octave-font-lock-keywords))
cf38dd42 592
070ccca4 593 (setq-local syntax-propertize-function #'octave-syntax-propertize-function)
c82d5b11 594
02502a5f
LL
595 (setq-local imenu-generic-expression octave-mode-imenu-generic-expression)
596 (setq-local imenu-case-fold-search nil)
c82d5b11 597
fda74125
LL
598 (setq-local add-log-current-defun-function #'octave-add-log-current-defun)
599
203a5572 600 (add-hook 'completion-at-point-functions 'octave-completion-at-point nil t)
e55d3b04 601 (add-hook 'before-save-hook 'octave-sync-function-file-names nil t)
070ccca4 602 (setq-local beginning-of-defun-function 'octave-beginning-of-defun)
5b78d7fc 603 (and octave-font-lock-texinfo-comment (octave-font-lock-texinfo-comment))
c8730c3a 604 (setq-local eldoc-documentation-function 'octave-eldoc-function)
f2727dfb 605
584ea277 606 (easy-menu-add octave-mode-menu))
be64c05d
LL
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
b2856a6f
LL
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\\|^\\)>+ "
be64c05d
LL
623 "Regexp to match prompts for the inferior Octave process."
624 :type 'regexp
625 :group 'octave)
626
b12d33d7 627(defcustom inferior-octave-prompt-read-only comint-prompt-read-only
5147fc17 628 "If non-nil, the Octave prompt is read only.
b12d33d7 629See `comint-prompt-read-only' for details."
5147fc17
RS
630 :type 'boolean
631 :group 'octave
632 :version "24.4")
633
0d634d3a 634(defcustom inferior-octave-startup-file
481a8e0f
RS
635 (let ((n (file-name-nondirectory inferior-octave-program)))
636 (locate-user-emacs-file (format "init_%s.m" n) (format ".emacs-%s" n)))
be64c05d
LL
637 "Name of the inferior Octave startup file.
638The contents of this file are sent to the inferior Octave process on
639startup."
0d634d3a
LL
640 :type '(choice (const :tag "None" nil) file)
641 :group 'octave
642 :version "24.4")
be64c05d 643
daabf15a 644(defcustom inferior-octave-startup-args '("-i" "--no-line-editing")
be64c05d
LL
645 "List of command line arguments for the inferior Octave process.
646For example, for suppressing the startup message and using `traditional'
daabf15a 647mode, include \"-q\" and \"--traditional\"."
be64c05d 648 :type '(repeat string)
daabf15a
LL
649 :group 'octave
650 :version "24.4")
be64c05d
LL
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
1dab32a3
LL
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."
bb098075 663 :version "24.4"
1dab32a3
LL
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
be64c05d
LL
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)
d4d0f9b3 681 (define-key map "\M-." 'octave-find-definition)
c129b51f 682 (define-key map "\t" 'completion-at-point)
d4d0f9b3 683 (define-key map "\C-hd" 'octave-help)
5af5ed08 684 (define-key map "\C-ha" 'octave-lookfor)
c129b51f 685 ;; Same as in `shell-mode'.
be64c05d
LL
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)
7e138a62 696 "Syntax table in use in `inferior-octave-mode' buffers.")
be64c05d
LL
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
be64c05d
LL
704(defvar inferior-octave-output-list nil)
705(defvar inferior-octave-output-string nil)
706(defvar inferior-octave-receive-in-progress nil)
707
2ec12cb0
LL
708(define-obsolete-variable-alias 'inferior-octave-startup-hook
709 'inferior-octave-mode-hook "24.4")
be64c05d 710
be64c05d
LL
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.
714This variable is used to initialize `comint-dynamic-complete-functions'
715in the Inferior Octave buffer.")
716
717(defvar info-lookup-mode)
1dab32a3
LL
718(defvar compilation-error-regexp-alist)
719(defvar compilation-mode-font-lock-keywords)
be64c05d 720
939fb29c
LL
721(declare-function compilation-forget-errors "compile" ())
722
724bc265 723(defun inferior-octave-process-live-p ()
0518b057 724 (process-live-p inferior-octave-process))
724bc265 725
be64c05d 726(define-derived-mode inferior-octave-mode comint-mode "Inferior Octave"
ed4bc201
RS
727 "Major mode for interacting with an inferior Octave process.
728
729See Info node `(octave-mode) Running Octave from Within Emacs' for more
730details.
731
732Key bindings:
733\\{inferior-octave-mode-map}"
9b92c13b 734 :abbrev-table octave-abbrev-table
ed4bc201
RS
735 :group 'octave
736
9b92c13b 737 (setq comint-prompt-regexp inferior-octave-prompt)
be64c05d 738
38637cca 739 (setq-local comment-use-syntax t)
070ccca4
LL
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)
be64c05d 744
070ccca4 745 (setq font-lock-defaults '(inferior-octave-font-lock-keywords nil nil))
be64c05d 746
02502a5f 747 (setq-local info-lookup-mode 'octave-mode)
c8730c3a 748 (setq-local eldoc-documentation-function 'octave-eldoc-function)
be64c05d
LL
749
750 (setq comint-input-ring-file-name
c75c93c7
LL
751 (or (getenv "OCTAVE_HISTFILE") "~/.octave_hist")
752 comint-input-ring-size (or (getenv "OCTAVE_HISTSIZE") 1024))
939fb29c 753 (comint-read-input-ring t)
070ccca4
LL
754 (setq-local comint-dynamic-complete-functions
755 inferior-octave-dynamic-complete-functions)
5147fc17 756 (setq-local comint-prompt-read-only inferior-octave-prompt-read-only)
be64c05d 757 (add-hook 'comint-input-filter-functions
203a5572 758 'inferior-octave-directory-tracker nil t)
c75c93c7
LL
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)
1dab32a3
LL
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)
939fb29c
LL
765 (compilation-shell-minor-mode 1)
766 (compilation-forget-errors))
be64c05d
LL
767
768;;;###autoload
769(defun inferior-octave (&optional arg)
770 "Run an inferior Octave process, I/O via `inferior-octave-buffer'.
771This buffer is put in Inferior Octave mode. See `inferior-octave-mode'.
772
773Unless ARG is non-nil, switches to this buffer.
774
775The elements of the list `inferior-octave-startup-args' are sent as
776command line arguments to the inferior Octave process on startup.
777
778Additional commands to be executed on startup can be provided either in
779the file specified by `inferior-octave-startup-file' or by the default
780startup file, `~/.emacs-octave'."
781 (interactive "P")
0d634d3a 782 (let ((buffer (get-buffer-create inferior-octave-buffer)))
ee44b62a
LL
783 (unless arg
784 (pop-to-buffer buffer))
0d634d3a 785 (unless (comint-check-proc buffer)
be64c05d 786 (with-current-buffer buffer
0d634d3a
LL
787 (inferior-octave-startup)
788 (inferior-octave-mode)))
0d634d3a 789 buffer))
be64c05d
LL
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
0d634d3a
LL
797 (substring inferior-octave-buffer 1 -1)
798 inferior-octave-buffer
799 inferior-octave-program
daabf15a
LL
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"))))))
be64c05d 807 (set-process-filter proc 'inferior-octave-output-digest)
0d634d3a
LL
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)
be64c05d
LL
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
965bb23a
LL
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))
be64c05d
LL
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
0d634d3a
LL
832 (concat (mapconcat
833 'identity inferior-octave-output-list "\n")
834 "\n"))))
be64c05d 835
be64c05d
LL
836 ;; An empty secondary prompt, as e.g. obtained by '--braindead',
837 ;; means trouble.
838 (inferior-octave-send-list-and-digest (list "PS2\n"))
0d634d3a
LL
839 (when (string-match "\\(PS2\\|ans\\) = *$"
840 (car inferior-octave-output-list))
daabf15a 841 (inferior-octave-send-list-and-digest (list "PS2 ('> ');\n")))
0d634d3a 842
30ea8374 843 (inferior-octave-send-list-and-digest
daabf15a 844 (list "disp (getenv ('OCTAVE_SRCDIR'))\n"))
5e80b74f
LL
845 (process-put proc 'octave-srcdir
846 (unless (equal (car inferior-octave-output-list) "")
847 (car inferior-octave-output-list)))
30ea8374 848
0d634d3a
LL
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 ">> ")
b2856a6f
LL
853 ;; See http://hg.savannah.gnu.org/hgweb/octave/rev/708173343c50
854 "PS1 ('octave> ');\n")
0d634d3a
LL
855 (when (and inferior-octave-startup-file
856 (file-exists-p inferior-octave-startup-file))
daabf15a 857 (format "source ('%s');\n" inferior-octave-startup-file))))
85d090a9
LL
858 (when inferior-octave-output-list
859 (insert-before-markers
860 (mapconcat 'identity inferior-octave-output-list "\n")))
be64c05d
LL
861
862 ;; And finally, everything is back to normal.
c129b51f 863 (set-process-filter proc 'comint-output-filter)
daabf15a
LL
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))
85d090a9
LL
867 ;; Generate a proper prompt, which is critical to
868 ;; `comint-history-isearch-backward-regexp'. Bug#14433.
455851dd 869 (comint-send-string proc "\n")))
be64c05d 870
16588fad
DG
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)))))
584ea277 878
be64c05d
LL
879(defun inferior-octave-completion-at-point ()
880 "Return the data to complete the Octave symbol at point."
455851dd 881 ;; http://debbugs.gnu.org/14300
4d2e94d1
LL
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
16588fad 889 (inferior-octave-completion-table)
4d2e94d1 890 'comint-completion-file-name-table))))))
be64c05d
LL
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
be64c05d
LL
922(defun inferior-octave-output-digest (_proc string)
923 "Special output filter for the inferior Octave process.
924Save all output between newlines into `inferior-octave-output-list', and
925the 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
30ea8374 936(defun inferior-octave-check-process ()
724bc265 937 (or (inferior-octave-process-live-p)
30ea8374
LL
938 (error (substitute-command-keys
939 "No inferior octave process running. Type \\[run-octave]"))))
940
be64c05d
LL
941(defun inferior-octave-send-list-and-digest (list)
942 "Send LIST to the inferior Octave process and digest the output.
943The elements of LIST have to be strings and are sent one by one. All
944output is passed to the filter `inferior-octave-output-digest'."
30ea8374 945 (inferior-octave-check-process)
be64c05d
LL
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
837fd9af
LL
961(defvar inferior-octave-directory-tracker-resync nil)
962(make-variable-buffer-local 'inferior-octave-directory-tracker-resync)
963
be64c05d
LL
964(defun inferior-octave-directory-tracker (string)
965 "Tracks `cd' commands issued to the inferior Octave process.
966Use \\[inferior-octave-resync-dirs] to resync if Emacs gets confused."
837fd9af 967 (when inferior-octave-directory-tracker-resync
daabf15a
LL
968 (or (inferior-octave-resync-dirs 'noerror)
969 (setq inferior-octave-directory-tracker-resync nil)))
be64c05d
LL
970 (cond
971 ((string-match "^[ \t]*cd[ \t;]*$" string)
972 (cd "~"))
973 ((string-match "^[ \t]*cd[ \t]+\\([^ \t\n;]*\\)[ \t\n;]*" string)
837fd9af
LL
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)))))))
be64c05d 980
daabf15a 981(defun inferior-octave-resync-dirs (&optional noerror)
be64c05d
LL
982 "Resync the buffer's idea of the current directory.
983This command queries the inferior Octave process about its current
984directory and makes this the current buffer's default directory."
985 (interactive)
986 (inferior-octave-send-list-and-digest '("disp (pwd ())\n"))
daabf15a
LL
987 (condition-case err
988 (progn
989 (cd (car inferior-octave-output-list))
990 t)
991 (error (unless noerror (signal (car err) (cdr err))))))
be64c05d 992
c75c93c7
LL
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)
724bc265 1006 (when (inferior-octave-process-live-p)
c75c93c7 1007 (inferior-octave-send-list-and-digest
daabf15a 1008 (list (format "putenv ('COLUMNS', '%s');\n" width)))))))
c75c93c7 1009
f2727dfb
RS
1010\f
1011;;; Miscellaneous useful functions
f2727dfb 1012
070ccca4
LL
1013(defun octave-in-comment-p ()
1014 "Return non-nil if point is inside an Octave comment."
602ea69d 1015 (nth 4 (syntax-ppss)))
f2727dfb 1016
070ccca4
LL
1017(defun octave-in-string-p ()
1018 "Return non-nil if point is inside an Octave string."
602ea69d 1019 (nth 3 (syntax-ppss)))
f2727dfb 1020
070ccca4
LL
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)))
f2727dfb 1024
a584f30f 1025(defun octave-looking-at-kw (regexp)
050a4b35 1026 "Like `looking-at', but sets `case-fold-search' nil."
a584f30f
GM
1027 (let ((case-fold-search nil))
1028 (looking-at regexp)))
1029
d83ee578
KH
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))))
e55d3b04 1038
d4d0f9b3
LL
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)
16588fad 1047 (inferior-octave-completion-table)
d4d0f9b3
LL
1048 nil nil nil nil def)))
1049
e3772e98
LL
1050(defun octave-goto-function-definition (fn)
1051 "Go to the function definition of FN in current buffer."
e3772e98
LL
1052 (let ((search
1053 (lambda (re sub)
fda74125
LL
1054 (let ((orig (point)) found)
1055 (goto-char (point-min))
1056 (while (and (not found) (re-search-forward re nil t))
e3772e98
LL
1057 (when (and (equal (match-string sub) fn)
1058 (not (nth 8 (syntax-ppss))))
fda74125
LL
1059 (setq found t)))
1060 (unless found (goto-char orig))
1061 found))))
daabf15a 1062 (pcase (and buffer-file-name (file-name-extension buffer-file-name))
2e611da6
LL
1063 (`"cc" (funcall search
1064 "\\_<DEFUN\\(?:_DLD\\)?\\s-*(\\s-*\\(\\(?:\\sw\\|\\s_\\)+\\)" 1))
e3772e98 1065 (t (funcall search octave-function-header-regexp 3)))))
d4d0f9b3 1066
b7260dd4
LL
1067(defun octave-function-file-p ()
1068 "Return non-nil if the first token is \"function\".
1069The 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 ()
2ec12cb0 1094 "Beginning and end positions of the function file comment."
b7260dd4
LL
1095 (save-excursion
1096 (goto-char (point-min))
38d8527b
LL
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))))))
b7260dd4 1111
e55d3b04
LL
1112(defun octave-sync-function-file-names ()
1113 "Ensure function name agree with function file name.
1114See Info node `(octave)Function Files'."
1115 (interactive)
b7260dd4
LL
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)
2ec12cb0
LL
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 "\
1124a: Use function name `%s'
1125b: Use file name `%s'
1126q: 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
2e611da6
LL
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)))))))))
b7260dd4
LL
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")))))
e55d3b04 1156 (save-excursion
b7260dd4
LL
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)
38d8527b
LL
1164 (when (re-search-forward
1165 "[=}]\\s-*\\(\\(?:\\sw\\|\\s_\\)+\\)\\_>"
1166 (min (line-end-position 4) end)
1167 t)
b7260dd4
LL
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")))))
e55d3b04 1178
5b78d7fc
LL
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
1e2c18df
SM
1184(eval-when-compile (require 'texinfo))
1185
5b78d7fc 1186(defun octave-font-lock-texinfo-comment ()
1e2c18df
SM
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)
6073d8f4
LL
1198 (while (and (< (point) limit)
1199 (search-forward "-*- texinfo -*-" limit t)
1e2c18df
SM
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)))
5b78d7fc 1214
f2727dfb
RS
1215\f
1216;;; Indentation
f2727dfb 1217
9cc3e83f 1218(defun octave-indent-new-comment-line (&optional soft)
f2727dfb 1219 "Break Octave line at point, continuing comment if within one.
9cc3e83f
LL
1220Insert `octave-continuation-string' before breaking the line
1221unless inside a list. Signal an error if within a single-quoted
1222string."
f2727dfb 1223 (interactive)
650cff3d
SM
1224 (funcall comment-line-break-function soft))
1225
1226(defun octave--indent-new-comment-line (orig &rest args)
f2727dfb 1227 (cond
9cc3e83f
LL
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))
f2727dfb 1233 (t
9cc3e83f
LL
1234 (delete-horizontal-space)
1235 (unless (and (cadr (syntax-ppss))
1236 (eq (char-after (cadr (syntax-ppss))) ?\())
1237 (insert " " octave-continuation-string))))
650cff3d 1238 (apply orig args)
9cc3e83f 1239 (indent-according-to-mode))
f2727dfb 1240
2d4bf34b
LL
1241(define-obsolete-function-alias
1242 'octave-indent-defun 'prog-indent-sexp "24.4")
f2727dfb
RS
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).
1248Skips past all empty and comment lines. Default for ARG is 1.
1249
1250On 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))
a1506d29 1263
f2727dfb
RS
1264(defun octave-previous-code-line (&optional arg)
1265 "Move ARG lines of Octave code backward (forward if ARG is negative).
1266Skips past all empty and comment lines. Default for ARG is 1.
1267
1268On 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.
1275If on an empty or comment line, go to the beginning of that line.
1276Otherwise, move backward to the beginning of the first Octave code line
1277which is not inside a continuation statement, i.e., which does not
083fe0d7 1278follow a code line ending with `...' or is inside an open
f2727dfb
RS
1279parenthesis list."
1280 (interactive)
1281 (beginning-of-line)
083fe0d7
LL
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)))))))
f2727dfb
RS
1292
1293(defun octave-end-of-line ()
1294 "Move point to end of current Octave line.
1295If on an empty or comment line, go to the end of that line.
1296Otherwise, move forward to the end of the first Octave code line which
083fe0d7 1297does not end with `...' or is inside an open parenthesis list."
f2727dfb
RS
1298 (interactive)
1299 (end-of-line)
083fe0d7
LL
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)))))
f2727dfb 1315 (end-of-line)))
a1506d29 1316
f2727dfb
RS
1317(defun octave-mark-block ()
1318 "Put point at the beginning of this Octave block, mark at the end.
1319The block marked is the one that contains point or follows point."
1320 (interactive)
ef54d315
SM
1321 (if (and (looking-at "\\sw\\|\\s_")
1322 (looking-back "\\sw\\|\\s_" (1- (point))))
1323 (skip-syntax-forward "w_"))
ec5d3ff7
SM
1324 (unless (or (looking-at "\\s(")
1325 (save-excursion
1326 (let* ((token (funcall smie-forward-token-function))
6d2a1e35 1327 (level (assoc token smie-grammar)))
ef54d315 1328 (and level (not (numberp (cadr level)))))))
ec5d3ff7
SM
1329 (backward-up-list 1))
1330 (mark-sexp))
f2727dfb 1331
f2727dfb 1332(defun octave-beginning-of-defun (&optional arg)
f71c50d0
LL
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))
9cc3e83f 1349 (and (< arg 0) (forward-sexp -1))
f71c50d0 1350 (/= orig (point))))
f2727dfb 1351
e02f48d7 1352(defun octave-fill-paragraph (&optional _arg)
ec5d3ff7
SM
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 " "))
ee44b62a 1417 (or (funcall normal-auto-fill-function)
ec5d3ff7
SM
1418 (forward-line 1))))
1419 t)))
f2727dfb 1420
203a5572 1421(defun octave-completion-at-point ()
c82d5b11 1422 "Find the text to complete and the corresponding table."
e92f3bd3 1423 (let* ((beg (save-excursion (skip-syntax-backward "w_") (point)))
ff80a446
SM
1424 (end (point)))
1425 (if (< beg (point))
1426 ;; Extend region past point, if applicable.
e92f3bd3
SM
1427 (save-excursion (skip-syntax-forward "w_")
1428 (setq end (point))))
203a5572 1429 (when (> end beg)
724bc265 1430 (list beg end (or (and (inferior-octave-process-live-p)
16588fad 1431 (inferior-octave-completion-table))
203a5572 1432 octave-reserved-words)))))
f2727dfb 1433
bcd70d97
SM
1434(define-obsolete-function-alias 'octave-complete-symbol
1435 'completion-at-point "24.1")
fda74125
LL
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
f2727dfb
RS
1446\f
1447;;; Electric characters && friends
c82d5b11 1448(define-skeleton octave-insert-defun
f2727dfb
RS
1449 "Insert an Octave function skeleton.
1450Prompt for the function's name, arguments and return values (to be
1451entered without parens)."
070ccca4 1452 (let* ((defname (file-name-sans-extension (buffer-name)))
c82d5b11
SM
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))
b7260dd4
LL
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
c82d5b11 1469 "endfunction" > \n)
fda74125 1470
f2727dfb
RS
1471;;; Communication with the inferior Octave process
1472(defun octave-kill-process ()
1473 "Kill inferior Octave process and its buffer."
1474 (interactive)
2cc18f93
LL
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))
724bc265 1483 (kill-buffer inferior-octave-buffer)))
f2727dfb
RS
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
06e752b4
RS
1499(defun octave-source-file (file)
1500 "Execute FILE in the inferior Octave process.
1501This is done using Octave's source function. FILE defaults to
1502current 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
f2727dfb
RS
1512(defun octave-send-region (beg end)
1513 "Send current region to the inferior Octave process."
1514 (interactive "r")
a1506d29 1515 (inferior-octave t)
f2727dfb 1516 (let ((proc inferior-octave-process)
c129b51f
LL
1517 (string (buffer-substring-no-properties beg end))
1518 line)
5d8137ab 1519 (with-current-buffer inferior-octave-buffer
6f6ab820
LL
1520 ;; http://lists.gnu.org/archive/html/emacs-devel/2013-10/msg00095.html
1521 (compilation-forget-errors)
f2727dfb
RS
1522 (setq inferior-octave-output-list nil)
1523 (while (not (string-equal string ""))
c129b51f
LL
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")))))
f2727dfb
RS
1539 (if octave-send-show-buffer
1540 (display-buffer inferior-octave-buffer)))
1541
7e138a62
RS
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
f2727dfb 1547(defun octave-send-block ()
a1506d29 1548 "Send current Octave block to the inferior Octave process."
f2727dfb
RS
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
ff80a446 1558 (mark-defun)
f2727dfb
RS
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.
1563With positive prefix ARG, send that many lines.
1564If `octave-send-line-auto-forward' is non-nil, go to the next unsent
1565code 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)
a1506d29 1587 (prin1
f2727dfb
RS
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)))
070ccca4 1595
d4d0f9b3
LL
1596\f
1597
c8730c3a
LL
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
daabf15a 1612 (list (format "print_usage ('%s');\n" fn)))
c8730c3a
LL
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)."
724bc265 1626 (when (inferior-octave-process-live-p)
c8730c3a
LL
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
d4d0f9b3
LL
1659(defcustom octave-help-buffer "*Octave Help*"
1660 "Buffer name for `octave-help'."
1661 :type 'string
1662 :group 'octave
1663 :version "24.4")
1664
30b626e9
GM
1665;; Used in a mode derived from help-mode.
1666(declare-function help-button-action "help-mode" (button))
1667
d4d0f9b3
LL
1668(define-button-type 'octave-help-file
1669 'follow-link t
1670 'action #'help-button-action
c129b51f 1671 'help-function 'octave-find-definition)
d4d0f9b3
LL
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
b4da2cbb
LL
1679(defvar octave-help-mode-map
1680 (let ((map (make-sparse-keymap)))
8c09f64b 1681 (define-key map "\M-." 'octave-find-definition)
b4da2cbb 1682 (define-key map "\C-hd" 'octave-help)
5af5ed08 1683 (define-key map "\C-ha" 'octave-lookfor)
b4da2cbb
LL
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))
8c09f64b
LL
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\\`"))
b4da2cbb 1694
d4d0f9b3
LL
1695(defun octave-help (fn)
1696 "Display the documentation of FN."
1697 (interactive (list (octave-completing-read)))
1698 (inferior-octave-send-list-and-digest
daabf15a 1699 (list (format "help ('%s');\n" fn)))
b4da2cbb
LL
1700 (let ((lines inferior-octave-output-list)
1701 (inhibit-read-only t))
d4d0f9b3
LL
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)
9cc3e83f
LL
1725 (let* ((file (match-string 1))
1726 (dir (file-name-directory
1727 (directory-file-name (file-name-directory file)))))
d4d0f9b3
LL
1728 (replace-match "" nil nil nil 1)
1729 (insert "`")
9cc3e83f
LL
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)
c129b51f 1733 'octave-help-file fn)
d4d0f9b3 1734 (insert "'")))
daabf15a 1735 ;; Make 'See also' clickable.
d4d0f9b3
LL
1736 (with-syntax-table octave-mode-syntax-table
1737 (when (re-search-forward "^\\s-*See also:" nil t)
f236dd84 1738 (let ((end (save-excursion (re-search-forward "^\\s-*$" nil t))))
daabf15a 1739 (while (re-search-forward
ad528125 1740 "\\s-*\\([^,\n]+?\\)\\s-*\\(?:[,]\\|[.]?$\\)" end t)
daabf15a 1741 (make-text-button (match-beginning 1) (match-end 1)
837fd9af 1742 :type 'octave-help-function)))))
b4da2cbb 1743 (octave-help-mode)))))
d4d0f9b3 1744
5af5ed08
RS
1745(defun octave-lookfor (str &optional all)
1746 "Search for the string STR in all function help strings.
1747If ALL is non-nil search the entire help string else only search the first
1748sentence."
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))
6408a65d
RS
1755 (when (and (stringp (car lines))
1756 (string-match "error: \\(.*\\)$" (car lines)))
5af5ed08
RS
1757 (error "%s" (match-string 1 (car lines))))
1758 (with-help-window octave-help-buffer
5af5ed08 1759 (with-current-buffer octave-help-buffer
6408a65d
RS
1760 (if lines
1761 (insert (mapconcat 'identity lines "\n"))
1762 (insert (format "Nothing found for \"%s\".\n" str)))
5af5ed08
RS
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))
6408a65d
RS
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
3eb91f7b 1778 'action #'(lambda (_b)
6408a65d
RS
1779 (octave-lookfor str '-all)))
1780 (insert ".\n"))
5af5ed08
RS
1781 (octave-help-mode)))))
1782
30ea8374 1783(defcustom octave-source-directories nil
5e80b74f
LL
1784 "A list of directories for Octave sources.
1785If the environment variable OCTAVE_SRCDIR is set, it is searched first."
30ea8374 1786 :type '(repeat directory)
c129b51f
LL
1787 :group 'octave
1788 :version "24.4")
1789
30ea8374 1790(defun octave-source-directories ()
5e80b74f
LL
1791 (let ((srcdir (or (and inferior-octave-process
1792 (process-get inferior-octave-process 'octave-srcdir))
1793 (getenv "OCTAVE_SRCDIR"))))
30ea8374
LL
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)
2e611da6 1804 (`"oct"
30ea8374
LL
1805 (octave-find-definition-default-filename
1806 (concat "libinterp/dldfcn/"
1807 (file-name-sans-extension (file-name-nondirectory name))
1808 ".cc")))
2e611da6 1809 (`"cc"
30ea8374
LL
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))
2e611da6 1816 (`"mex"
30ea8374
LL
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
d4d0f9b3
LL
1823(defvar find-tag-marker-ring)
1824
1825(defun octave-find-definition (fn)
30ea8374 1826 "Find the definition of FN.
5e80b74f 1827Functions implemented in C++ can be found if
7e138a62 1828variable `octave-source-directories' is set correctly."
d4d0f9b3 1829 (interactive (list (octave-completing-read)))
fda74125
LL
1830 (require 'etags)
1831 (let ((orig (point)))
daabf15a
LL
1832 (if (and (derived-mode-p 'octave-mode)
1833 (octave-goto-function-definition fn))
fda74125
LL
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 "\
daabf15a 1838if iskeyword('%s') disp('`%s'' is a keyword') else which('%s') endif\n"
fda74125
LL
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)))))))
d4d0f9b3 1854
be64c05d
LL
1855(provide 'octave)
1856;;; octave.el ends here