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