* progmodes/octave.el (octave-completing-read)
[bpt/emacs.git] / lisp / progmodes / octave.el
CommitLineData
070ccca4 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
be64c05d
LL
27;; This package provides emacs support for octave. It defines a major
28;; mode for editing octave code and contains code for interacting with
29;; an inferior octave process using comint.
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)
39(eval-when-compile
40 (unless (fboundp 'setq-local)
41 (defmacro setq-local (var val)
42 "Set variable VAR to value VAL in current buffer."
43 (list 'set (list 'make-local-variable (list 'quote var)) val))))
44
28d16ed3 45(defgroup octave nil
be64c05d 46 "Editing Octave code."
8ec3bce0 47 :link '(custom-group-link :tag "Font Lock Faces group" font-lock-faces)
28d16ed3
AS
48 :group 'languages)
49
070ccca4
LL
50(define-obsolete-function-alias 'octave-submit-bug-report
51 'report-emacs-bug "24.4")
e7017ef9 52
9b92c13b 53(define-abbrev-table 'octave-abbrev-table nil
e7017ef9 54 "Abbrev table for Octave's reserved words.
9b92c13b 55Used in `octave-mode' and `inferior-octave-mode' buffers.")
e7017ef9
RS
56
57(defvar octave-comment-char ?#
58 "Character to start an Octave comment.")
9b92c13b 59
e7017ef9 60(defvar octave-comment-start
c82d5b11 61 (string octave-comment-char ?\s)
e7017ef9 62 "String to insert to start a new Octave in-line comment.")
9b92c13b 63
e7017ef9
RS
64(defvar octave-comment-start-skip "\\s<+\\s-*"
65 "Regexp to match the start of an Octave comment up to its body.")
66
67(defvar octave-begin-keywords
490a8abe 68 '("do" "for" "function" "if" "switch" "try" "unwind_protect" "while"))
9b92c13b 69
e7017ef9 70(defvar octave-else-keywords
6e6d2764 71 '("case" "catch" "else" "elseif" "otherwise" "unwind_protect_cleanup"))
9b92c13b 72
e7017ef9 73(defvar octave-end-keywords
490a8abe 74 '("endfor" "endfunction" "endif" "endswitch" "end_try_catch"
b2ad70b6 75 "end_unwind_protect" "endwhile" "until" "end"))
e7017ef9
RS
76
77(defvar octave-reserved-words
6e6d2764
KH
78 (append octave-begin-keywords
79 octave-else-keywords
80 octave-end-keywords
490a8abe 81 '("break" "continue" "end" "global" "persistent" "return"))
e7017ef9
RS
82 "Reserved words in Octave.")
83
84(defvar octave-text-functions
85 '("casesen" "cd" "chdir" "clear" "diary" "dir" "document" "echo"
490a8abe
GM
86 "edit_history" "format" "help" "history" "hold"
87 "load" "ls" "more" "run_history" "save" "type"
e7017ef9 88 "which" "who" "whos")
490a8abe 89 "Text functions in Octave.")
e7017ef9 90
e7017ef9 91(defvar octave-function-header-regexp
e92f3bd3
SM
92 (concat "^\\s-*\\_<\\(function\\)\\_>"
93 "\\([^=;\n]*=[ \t]*\\|[ \t]*\\)\\(\\(?:\\w\\|\\s_\\)+\\)\\_>")
e7017ef9
RS
94 "Regexp to match an Octave function header.
95The string `function' and its name are given by the first and third
96parenthetical grouping.")
97
be64c05d 98\f
e7017ef9
RS
99(defvar octave-font-lock-keywords
100 (list
101 ;; Fontify all builtin keywords.
e92f3bd3 102 (cons (concat "\\_<\\("
b54f978b 103 (regexp-opt (append octave-reserved-words
e17b68ed 104 octave-text-functions))
b54f978b
LL
105 "\\)\\_>")
106 'font-lock-keyword-face)
38d8527b
LL
107 ;; Note: 'end' also serves as the last index in an indexing expression.
108 ;; Ref: http://www.mathworks.com/help/matlab/ref/end.html
b54f978b
LL
109 '((lambda (limit)
110 (while (re-search-forward "\\_<end\\_>" limit 'move)
111 (let ((beg (match-beginning 0))
112 (end (match-end 0)))
113 (unless (octave-in-string-or-comment-p)
114 (unwind-protect
115 (progn
116 (goto-char beg)
117 (backward-up-list)
118 (when (memq (char-after) '(?\( ?\[ ?\{))
119 (put-text-property beg end 'face nil)))
120 (goto-char end)))))
121 nil))
e7017ef9
RS
122 ;; Fontify all builtin operators.
123 (cons "\\(&\\||\\|<=\\|>=\\|==\\|<\\|>\\|!=\\|!\\)"
b54f978b
LL
124 (if (boundp 'font-lock-builtin-face)
125 'font-lock-builtin-face
126 'font-lock-preprocessor-face))
e7017ef9
RS
127 ;; Fontify all function declarations.
128 (list octave-function-header-regexp
b54f978b
LL
129 '(1 font-lock-keyword-face)
130 '(3 font-lock-function-name-face nil t)))
e7017ef9
RS
131 "Additional Octave expressions to highlight.")
132
cf38dd42
SM
133(defun octave-syntax-propertize-function (start end)
134 (goto-char start)
135 (octave-syntax-propertize-sqs end)
136 (funcall (syntax-propertize-rules
602ea69d 137 ;; Try to distinguish the string-quotes from the transpose-quotes.
b4c8295e 138 ("\\(?:^\\|[[({,; ]\\)\\('\\)"
cf38dd42
SM
139 (1 (prog1 "\"'" (octave-syntax-propertize-sqs end)))))
140 (point) end))
141
142(defun octave-syntax-propertize-sqs (end)
143 "Propertize the content/end of single-quote strings."
144 (when (eq (nth 3 (syntax-ppss)) ?\')
602ea69d 145 ;; A '..' string.
cf38dd42
SM
146 (when (re-search-forward
147 "\\(?:\\=\\|[^']\\)\\(?:''\\)*\\('\\)\\($\\|[^']\\)" end 'move)
148 (goto-char (match-beginning 2))
602ea69d
SM
149 (when (eq (char-before (match-beginning 1)) ?\\)
150 ;; Backslash cannot escape a single quote.
151 (put-text-property (1- (match-beginning 1)) (match-beginning 1)
152 'syntax-table (string-to-syntax ".")))
153 (put-text-property (match-beginning 1) (match-end 1)
cf38dd42 154 'syntax-table (string-to-syntax "\"'")))))
ff80a446 155
e7017ef9 156\f
e22bbd48 157(defvar octave-mode-map
f2727dfb 158 (let ((map (make-sparse-keymap)))
d4d0f9b3 159 (define-key map "\M-." 'octave-find-definition)
a1506d29 160 (define-key map "\e\n" 'octave-indent-new-comment-line)
a1506d29 161 (define-key map "\M-\C-q" 'octave-indent-defun)
f2727dfb
RS
162 (define-key map "\C-c\C-p" 'octave-previous-code-line)
163 (define-key map "\C-c\C-n" 'octave-next-code-line)
164 (define-key map "\C-c\C-a" 'octave-beginning-of-line)
a1506d29 165 (define-key map "\C-c\C-e" 'octave-end-of-line)
ec5d3ff7 166 (define-key map [remap down-list] 'smie-down-list)
f2727dfb 167 (define-key map "\C-c\M-\C-h" 'octave-mark-block)
e17b68ed
SM
168 (define-key map "\C-c]" 'smie-close-block)
169 (define-key map "\C-c/" 'smie-close-block)
b7260dd4 170 (define-key map "\C-c;" 'octave-update-function-file-comment)
d4d0f9b3 171 (define-key map "\C-hd" 'octave-help)
34a463f1 172 (define-key map "\C-c\C-f" 'octave-insert-defun)
34a463f1
RS
173 (define-key map "\C-c\C-il" 'octave-send-line)
174 (define-key map "\C-c\C-ib" 'octave-send-block)
175 (define-key map "\C-c\C-if" 'octave-send-defun)
a1506d29 176 (define-key map "\C-c\C-ir" 'octave-send-region)
34a463f1 177 (define-key map "\C-c\C-is" 'octave-show-process-buffer)
ad64b83d 178 (define-key map "\C-c\C-iq" 'octave-hide-process-buffer)
34a463f1
RS
179 (define-key map "\C-c\C-ik" 'octave-kill-process)
180 (define-key map "\C-c\C-i\C-l" 'octave-send-line)
181 (define-key map "\C-c\C-i\C-b" 'octave-send-block)
182 (define-key map "\C-c\C-i\C-f" 'octave-send-defun)
a1506d29 183 (define-key map "\C-c\C-i\C-r" 'octave-send-region)
34a463f1 184 (define-key map "\C-c\C-i\C-s" 'octave-show-process-buffer)
7a1beb6c 185 (define-key map "\C-c\C-i\C-q" 'octave-hide-process-buffer)
34a463f1 186 (define-key map "\C-c\C-i\C-k" 'octave-kill-process)
e22bbd48
SM
187 map)
188 "Keymap used in Octave mode.")
189
f2727dfb 190
ff80a446
SM
191
192(easy-menu-define octave-mode-menu octave-mode-map
193 "Menu for Octave mode."
e22bbd48 194 '("Octave"
67885e8c 195 ("Lines"
e22bbd48
SM
196 ["Previous Code Line" octave-previous-code-line t]
197 ["Next Code Line" octave-next-code-line t]
198 ["Begin of Continuation" octave-beginning-of-line t]
199 ["End of Continuation" octave-end-of-line t]
200 ["Split Line at Point" octave-indent-new-comment-line t])
67885e8c 201 ("Blocks"
e22bbd48 202 ["Mark Block" octave-mark-block t]
e17b68ed 203 ["Close Block" smie-close-block t])
67885e8c 204 ("Functions"
e22bbd48 205 ["Indent Function" octave-indent-defun t]
b7260dd4
LL
206 ["Insert Function" octave-insert-defun t]
207 ["Update function file comment" octave-update-function-file-comment t])
e22bbd48 208 "-"
67885e8c 209 ("Debug"
e22bbd48
SM
210 ["Send Current Line" octave-send-line t]
211 ["Send Current Block" octave-send-block t]
212 ["Send Current Function" octave-send-defun t]
213 ["Send Region" octave-send-region t]
214 ["Show Process Buffer" octave-show-process-buffer t]
215 ["Hide Process Buffer" octave-hide-process-buffer t]
216 ["Kill Process" octave-kill-process t])
217 "-"
218 ["Indent Line" indent-according-to-mode t]
c82d5b11 219 ["Complete Symbol" completion-at-point t]
b5ba2d6f
SM
220 ["Toggle Auto-Fill Mode" auto-fill-mode
221 :style toggle :selected auto-fill-function]
e22bbd48 222 "-"
c82d5b11 223 ["Describe Octave Mode" describe-mode t]
b7260dd4
LL
224 ["Lookup Octave Index" info-lookup-symbol t]
225 ["Customize Octave" (customize-group 'octave) t]
226 "-"
227 ["Submit Bug Report" report-emacs-bug t]))
f2727dfb 228
cb3d3ec1 229(defvar octave-mode-syntax-table
f2727dfb
RS
230 (let ((table (make-syntax-table)))
231 (modify-syntax-entry ?\r " " table)
232 (modify-syntax-entry ?+ "." table)
233 (modify-syntax-entry ?- "." table)
234 (modify-syntax-entry ?= "." table)
235 (modify-syntax-entry ?* "." table)
236 (modify-syntax-entry ?/ "." table)
237 (modify-syntax-entry ?> "." table)
238 (modify-syntax-entry ?< "." table)
239 (modify-syntax-entry ?& "." table)
240 (modify-syntax-entry ?| "." table)
241 (modify-syntax-entry ?! "." table)
27135018 242 (modify-syntax-entry ?\\ "." table)
f2727dfb 243 (modify-syntax-entry ?\' "." table)
7210c33f
SM
244 ;; Was "w" for abbrevs, but now that it's not necessary any more,
245 (modify-syntax-entry ?\` "." table)
f2727dfb 246 (modify-syntax-entry ?\" "\"" table)
e92f3bd3
SM
247 (modify-syntax-entry ?. "_" table)
248 (modify-syntax-entry ?_ "_" table)
c5683ceb 249 ;; The "b" flag only applies to the second letter of the comstart
7e82caa7
SM
250 ;; and the first letter of the comend, i.e. the "4b" below is ineffective.
251 ;; If we try to put `b' on the single-line comments, we get a similar
252 ;; problem where the % and # chars appear as first chars of the 2-char
253 ;; comend, so the multi-line ender is also turned into style-b.
c5683ceb 254 ;; So we need the new "c" comment style.
c82d5b11
SM
255 (modify-syntax-entry ?\% "< 13" table)
256 (modify-syntax-entry ?\# "< 13" table)
c5683ceb
SM
257 (modify-syntax-entry ?\{ "(} 2c" table)
258 (modify-syntax-entry ?\} "){ 4c" table)
f2727dfb 259 (modify-syntax-entry ?\n ">" table)
cb3d3ec1
SM
260 table)
261 "Syntax table in use in `octave-mode' buffers.")
f2727dfb 262
5b78d7fc
LL
263(defcustom octave-font-lock-texinfo-comment t
264 "Control whether to highlight the texinfo comment block."
265 :type 'boolean
266 :group 'octave
267 :version "24.4")
268
28d16ed3 269(defcustom octave-blink-matching-block t
e22bbd48 270 "Control the blinking of matching Octave block keywords.
f2727dfb 271Non-nil means show matching begin of block when inserting a space,
28d16ed3
AS
272newline or semicolon after an else or end keyword."
273 :type 'boolean
274 :group 'octave)
ff80a446 275
28d16ed3 276(defcustom octave-block-offset 2
e22bbd48 277 "Extra indentation applied to statements in Octave block structures."
28d16ed3
AS
278 :type 'integer
279 :group 'octave)
f2727dfb 280
f2727dfb
RS
281(defvar octave-block-comment-start
282 (concat (make-string 2 octave-comment-char) " ")
283 "String to insert to start a new Octave comment on an empty line.")
284
28d16ed3 285(defcustom octave-continuation-offset 4
e22bbd48 286 "Extra indentation applied to Octave continuation lines."
28d16ed3
AS
287 :type 'integer
288 :group 'octave)
38d8527b 289
e17b68ed
SM
290(eval-and-compile
291 (defconst octave-continuation-marker-regexp "\\\\\\|\\.\\.\\."))
38d8527b 292
f2727dfb 293(defvar octave-continuation-regexp
e17b68ed
SM
294 (concat "[^#%\n]*\\(" octave-continuation-marker-regexp
295 "\\)\\s-*\\(\\s<.*\\)?$"))
38d8527b
LL
296
297;; Char \ is considered a bad decision for continuing a line.
298(defconst octave-continuation-string "..."
299 "Character string used for Octave continuation lines.")
f2727dfb 300
f2727dfb
RS
301(defvar octave-mode-imenu-generic-expression
302 (list
303 ;; Functions
304 (list nil octave-function-header-regexp 3))
305 "Imenu expression for Octave mode. See `imenu-generic-expression'.")
306
28d16ed3 307(defcustom octave-mode-hook nil
e22bbd48 308 "Hook to be run when Octave mode is started."
28d16ed3
AS
309 :type 'hook
310 :group 'octave)
311
312(defcustom octave-send-show-buffer t
e22bbd48 313 "Non-nil means display `inferior-octave-buffer' after sending to it."
28d16ed3
AS
314 :type 'boolean
315 :group 'octave)
9b92c13b 316
28d16ed3 317(defcustom octave-send-line-auto-forward t
e22bbd48 318 "Control auto-forward after sending to the inferior Octave process.
28d16ed3
AS
319Non-nil means always go to the next Octave code line after sending."
320 :type 'boolean
321 :group 'octave)
9b92c13b 322
28d16ed3 323(defcustom octave-send-echo-input t
e22bbd48 324 "Non-nil means echo input sent to the inferior Octave process."
28d16ed3
AS
325 :type 'boolean
326 :group 'octave)
f2727dfb
RS
327
328\f
e17b68ed
SM
329;;; SMIE indentation
330
331(require 'smie)
332
333(defconst octave-operator-table
334 '((assoc ";" "\n") (assoc ",") ; The doc claims they have equal precedence!?
335 (right "=" "+=" "-=" "*=" "/=")
336 (assoc "&&") (assoc "||") ; The doc claims they have equal precedence!?
337 (assoc "&") (assoc "|") ; The doc claims they have equal precedence!?
338 (nonassoc "<" "<=" "==" ">=" ">" "!=" "~=")
339 (nonassoc ":") ;No idea what this is.
340 (assoc "+" "-")
341 (assoc "*" "/" "\\" ".\\" ".*" "./")
342 (nonassoc "'" ".'")
343 (nonassoc "++" "--" "!" "~") ;And unary "+" and "-".
344 (right "^" "**" ".^" ".**")
345 ;; It's not really an operator, but for indentation purposes it
346 ;; could be convenient to treat it as one.
347 (assoc "...")))
348
89acf735
SM
349(defconst octave-smie-bnf-table
350 '((atom)
351 ;; We can't distinguish the first element in a sequence with
352 ;; precedence grammars, so we can't distinguish the condition
353 ;; if the `if' from the subsequent body, for example.
354 ;; This has to be done later in the indentation rules.
355 (exp (exp "\n" exp)
356 ;; We need to mention at least one of the operators in this part
357 ;; of the grammar: if the BNF and the operator table have
358 ;; no overlap, SMIE can't know how they relate.
359 (exp ";" exp)
360 ("try" exp "catch" exp "end_try_catch")
361 ("try" exp "catch" exp "end")
362 ("unwind_protect" exp
363 "unwind_protect_cleanup" exp "end_unwind_protect")
364 ("unwind_protect" exp "unwind_protect_cleanup" exp "end")
365 ("for" exp "endfor")
366 ("for" exp "end")
367 ("do" exp "until" atom)
368 ("while" exp "endwhile")
369 ("while" exp "end")
370 ("if" exp "endif")
371 ("if" exp "else" exp "endif")
372 ("if" exp "elseif" exp "else" exp "endif")
373 ("if" exp "elseif" exp "elseif" exp "else" exp "endif")
374 ("if" exp "elseif" exp "elseif" exp "else" exp "end")
375 ("switch" exp "case" exp "endswitch")
376 ("switch" exp "case" exp "otherwise" exp "endswitch")
377 ("switch" exp "case" exp "case" exp "otherwise" exp "endswitch")
378 ("switch" exp "case" exp "case" exp "otherwise" exp "end")
379 ("function" exp "endfunction")
380 ("function" exp "end"))
381 ;; (fundesc (atom "=" atom))
382 ))
383
674728d4
SM
384(defconst octave-smie-grammar
385 (smie-prec2->grammar
e17b68ed 386 (smie-merge-prec2s
674728d4
SM
387 (smie-bnf->prec2 octave-smie-bnf-table
388 '((assoc "\n" ";")))
e17b68ed 389
674728d4 390 (smie-precs->prec2 octave-operator-table))))
e17b68ed
SM
391
392;; Tokenizing needs to be refined so that ";;" is treated as two
393;; tokens and also so as to recognize the \n separator (and
394;; corresponding continuation lines).
395
396(defconst octave-operator-regexp
397 (regexp-opt (apply 'append (mapcar 'cdr octave-operator-table))))
398
399(defun octave-smie-backward-token ()
400 (let ((pos (point)))
401 (forward-comment (- (point)))
402 (cond
403 ((and (not (eq (char-before) ?\;)) ;Coalesce ";" and "\n".
404 (> pos (line-end-position))
405 (if (looking-back octave-continuation-marker-regexp (- (point) 3))
406 (progn
407 (goto-char (match-beginning 0))
408 (forward-comment (- (point)))
409 nil)
410 t)
411 ;; Ignore it if it's within parentheses.
412 (let ((ppss (syntax-ppss)))
413 (not (and (nth 1 ppss)
414 (eq ?\( (char-after (nth 1 ppss)))))))
415 (skip-chars-forward " \t")
416 ;; Why bother distinguishing \n and ;?
417 ";") ;;"\n"
418 ((and (looking-back octave-operator-regexp (- (point) 3) 'greedy)
419 ;; Don't mistake a string quote for a transpose.
420 (not (looking-back "\\s\"" (1- (point)))))
421 (goto-char (match-beginning 0))
422 (match-string-no-properties 0))
423 (t
424 (smie-default-backward-token)))))
425
426(defun octave-smie-forward-token ()
427 (skip-chars-forward " \t")
428 (when (looking-at (eval-when-compile
429 (concat "\\(" octave-continuation-marker-regexp
430 "\\)[ \t]*\\($\\|[%#]\\)")))
431 (goto-char (match-end 1))
432 (forward-comment 1))
433 (cond
434 ((and (looking-at "$\\|[%#]")
e53052d3
SM
435 ;; Ignore it if it's within parentheses or if the newline does not end
436 ;; some preceding text.
437 (prog1 (and (not (smie-rule-bolp))
438 (let ((ppss (syntax-ppss)))
439 (not (and (nth 1 ppss)
440 (eq ?\( (char-after (nth 1 ppss)))))))
e17b68ed
SM
441 (forward-comment (point-max))))
442 ;; Why bother distinguishing \n and ;?
443 ";") ;;"\n"
444 ((looking-at ";[ \t]*\\($\\|[%#]\\)")
445 ;; Combine the ; with the subsequent \n.
446 (goto-char (match-beginning 1))
447 (forward-comment 1)
448 ";")
449 ((and (looking-at octave-operator-regexp)
450 ;; Don't mistake a string quote for a transpose.
451 (not (looking-at "\\s\"")))
452 (goto-char (match-end 0))
453 (match-string-no-properties 0))
454 (t
455 (smie-default-forward-token))))
456
c4d17d50
SM
457(defun octave-smie-rules (kind token)
458 (pcase (cons kind token)
674728d4
SM
459 ;; We could set smie-indent-basic instead, but that would have two
460 ;; disadvantages:
461 ;; - changes to octave-block-offset wouldn't take effect immediately.
462 ;; - edebug wouldn't show the use of this variable.
c4d17d50 463 (`(:elem . basic) octave-block-offset)
674728d4
SM
464 ;; Since "case" is in the same BNF rules as switch..end, SMIE by default
465 ;; aligns it with "switch".
466 (`(:before . "case") (if (not (smie-rule-sibling-p)) octave-block-offset))
c4d17d50 467 (`(:after . ";")
674728d4
SM
468 (if (smie-rule-parent-p "function" "if" "while" "else" "elseif" "for"
469 "otherwise" "case" "try" "catch" "unwind_protect"
470 "unwind_protect_cleanup")
471 (smie-rule-parent octave-block-offset)
c4d17d50
SM
472 ;; For (invalid) code between switch and case.
473 ;; (if (smie-parent-p "switch") 4)
474 0))))
e17b68ed 475
03f70355 476(defvar electric-layout-rules)
b073dc4b 477
f2727dfb 478;;;###autoload
c82d5b11 479(define-derived-mode octave-mode prog-mode "Octave"
f2727dfb
RS
480 "Major mode for editing Octave code.
481
b7260dd4
LL
482Octave is a high-level language, primarily intended for numerical
483computations. It provides a convenient command line interface
484for solving linear and nonlinear problems numerically. Function
485definitions can also be stored in files and used in batch mode."
9b92c13b 486 :abbrev-table octave-abbrev-table
c82d5b11 487
674728d4 488 (smie-setup octave-smie-grammar #'octave-smie-rules
c4d17d50
SM
489 :forward-token #'octave-smie-forward-token
490 :backward-token #'octave-smie-backward-token)
070ccca4 491 (setq-local smie-indent-basic 'octave-block-offset)
c4d17d50 492
070ccca4
LL
493 (setq-local smie-blink-matching-triggers
494 (cons ?\; smie-blink-matching-triggers))
c4d17d50
SM
495 (unless octave-blink-matching-block
496 (remove-hook 'post-self-insert-hook #'smie-blink-matching-open 'local))
89acf735 497
070ccca4
LL
498 (setq-local electric-indent-chars
499 (cons ?\; electric-indent-chars))
03f70355
SM
500 ;; IIUC matlab-mode takes the opposite approach: it makes RET insert
501 ;; a ";" at those places where it's correct (i.e. outside of parens).
070ccca4 502 (setq-local electric-layout-rules '((?\; . after)))
c82d5b11 503
070ccca4
LL
504 (setq-local comment-start octave-comment-start)
505 (setq-local comment-end "")
c82d5b11
SM
506 ;; Don't set it here: it's not really a property of the language,
507 ;; just a personal preference of the author.
070ccca4
LL
508 ;; (setq-local comment-column 32)
509 (setq-local comment-start-skip "\\s<+\\s-*")
510 (setq-local comment-add 1)
511
512 (setq-local parse-sexp-ignore-comments t)
513 (setq-local paragraph-start (concat "\\s-*$\\|" page-delimiter))
514 (setq-local paragraph-separate paragraph-start)
515 (setq-local paragraph-ignore-fill-prefix t)
516 (setq-local fill-paragraph-function 'octave-fill-paragraph)
c82d5b11 517 ;; FIXME: Why disable it?
070ccca4 518 ;; (setq-local adaptive-fill-regexp nil)
c82d5b11 519 ;; Again, this is not a property of the language, don't set it here.
070ccca4
LL
520 ;; (setq fill-column 72)
521 (setq-local normal-auto-fill-function 'octave-auto-fill)
c82d5b11 522
070ccca4 523 (setq font-lock-defaults '(octave-font-lock-keywords))
cf38dd42 524
070ccca4 525 (setq-local syntax-propertize-function #'octave-syntax-propertize-function)
c82d5b11 526
070ccca4
LL
527 (setq imenu-generic-expression octave-mode-imenu-generic-expression)
528 (setq imenu-case-fold-search nil)
c82d5b11
SM
529
530 (add-hook 'completion-at-point-functions
531 'octave-completion-at-point-function nil t)
e55d3b04 532 (add-hook 'before-save-hook 'octave-sync-function-file-names nil t)
070ccca4 533 (setq-local beginning-of-defun-function 'octave-beginning-of-defun)
5b78d7fc 534 (and octave-font-lock-texinfo-comment (octave-font-lock-texinfo-comment))
f2727dfb 535
584ea277 536 (easy-menu-add octave-mode-menu))
be64c05d
LL
537
538\f
539(defcustom inferior-octave-program "octave"
540 "Program invoked by `inferior-octave'."
541 :type 'string
542 :group 'octave)
543
544(defcustom inferior-octave-buffer "*Inferior Octave*"
545 "Name of buffer for running an inferior Octave process."
546 :type 'string
547 :group 'octave)
548
549(defcustom inferior-octave-prompt
550 "\\(^octave\\(\\|.bin\\|.exe\\)\\(-[.0-9]+\\)?\\(:[0-9]+\\)?\\|^debug\\|^\\)>+ "
551 "Regexp to match prompts for the inferior Octave process."
552 :type 'regexp
553 :group 'octave)
554
b12d33d7 555(defcustom inferior-octave-prompt-read-only comint-prompt-read-only
5147fc17 556 "If non-nil, the Octave prompt is read only.
b12d33d7 557See `comint-prompt-read-only' for details."
5147fc17
RS
558 :type 'boolean
559 :group 'octave
560 :version "24.4")
561
0d634d3a
LL
562(defcustom inferior-octave-startup-file
563 (convert-standard-filename
564 (concat "~/.emacs-" (file-name-nondirectory inferior-octave-program)))
be64c05d
LL
565 "Name of the inferior Octave startup file.
566The contents of this file are sent to the inferior Octave process on
567startup."
0d634d3a
LL
568 :type '(choice (const :tag "None" nil) file)
569 :group 'octave
570 :version "24.4")
be64c05d
LL
571
572(defcustom inferior-octave-startup-args nil
573 "List of command line arguments for the inferior Octave process.
574For example, for suppressing the startup message and using `traditional'
575mode, set this to (\"-q\" \"--traditional\")."
576 :type '(repeat string)
577 :group 'octave)
578
579(defcustom inferior-octave-mode-hook nil
580 "Hook to be run when Inferior Octave mode is started."
581 :type 'hook
582 :group 'octave)
583
584(defvar inferior-octave-process nil)
585
586(defvar inferior-octave-mode-map
587 (let ((map (make-sparse-keymap)))
588 (set-keymap-parent map comint-mode-map)
d4d0f9b3 589 (define-key map "\M-." 'octave-find-definition)
be64c05d 590 (define-key map "\t" 'comint-dynamic-complete)
d4d0f9b3 591 (define-key map "\C-hd" 'octave-help)
be64c05d
LL
592 (define-key map "\M-?" 'comint-dynamic-list-filename-completions)
593 (define-key map "\C-c\C-l" 'inferior-octave-dynamic-list-input-ring)
594 (define-key map [menu-bar inout list-history]
595 '("List Input History" . inferior-octave-dynamic-list-input-ring))
596 map)
597 "Keymap used in Inferior Octave mode.")
598
599(defvar inferior-octave-mode-syntax-table
600 (let ((table (make-syntax-table octave-mode-syntax-table)))
601 table)
602 "Syntax table in use in inferior-octave-mode buffers.")
603
604(defvar inferior-octave-font-lock-keywords
605 (list
606 (cons inferior-octave-prompt 'font-lock-type-face))
607 ;; Could certainly do more font locking in inferior Octave ...
608 "Additional expressions to highlight in Inferior Octave mode.")
609
be64c05d
LL
610(defvar inferior-octave-output-list nil)
611(defvar inferior-octave-output-string nil)
612(defvar inferior-octave-receive-in-progress nil)
613
2ec12cb0
LL
614(define-obsolete-variable-alias 'inferior-octave-startup-hook
615 'inferior-octave-mode-hook "24.4")
be64c05d 616
be64c05d
LL
617(defvar inferior-octave-dynamic-complete-functions
618 '(inferior-octave-completion-at-point comint-filename-completion)
619 "List of functions called to perform completion for inferior Octave.
620This variable is used to initialize `comint-dynamic-complete-functions'
621in the Inferior Octave buffer.")
622
623(defvar info-lookup-mode)
624
625(define-derived-mode inferior-octave-mode comint-mode "Inferior Octave"
b7260dd4 626 "Major mode for interacting with an inferior Octave process."
9b92c13b
LL
627 :abbrev-table octave-abbrev-table
628 (setq comint-prompt-regexp inferior-octave-prompt)
be64c05d 629
070ccca4
LL
630 (setq-local comment-start octave-comment-start)
631 (setq-local comment-end "")
632 (setq comment-column 32)
633 (setq-local comment-start-skip octave-comment-start-skip)
be64c05d 634
070ccca4 635 (setq font-lock-defaults '(inferior-octave-font-lock-keywords nil nil))
be64c05d 636
070ccca4 637 (setq info-lookup-mode 'octave-mode)
be64c05d
LL
638
639 (setq comint-input-ring-file-name
640 (or (getenv "OCTAVE_HISTFILE") "~/.octave_hist")
641 comint-input-ring-size (or (getenv "OCTAVE_HISTSIZE") 1024))
070ccca4
LL
642 (setq-local comint-dynamic-complete-functions
643 inferior-octave-dynamic-complete-functions)
5147fc17 644 (setq-local comint-prompt-read-only inferior-octave-prompt-read-only)
be64c05d
LL
645 (add-hook 'comint-input-filter-functions
646 'inferior-octave-directory-tracker nil t)
647 (comint-read-input-ring t))
648
649;;;###autoload
650(defun inferior-octave (&optional arg)
651 "Run an inferior Octave process, I/O via `inferior-octave-buffer'.
652This buffer is put in Inferior Octave mode. See `inferior-octave-mode'.
653
654Unless ARG is non-nil, switches to this buffer.
655
656The elements of the list `inferior-octave-startup-args' are sent as
657command line arguments to the inferior Octave process on startup.
658
659Additional commands to be executed on startup can be provided either in
660the file specified by `inferior-octave-startup-file' or by the default
661startup file, `~/.emacs-octave'."
662 (interactive "P")
0d634d3a
LL
663 (let ((buffer (get-buffer-create inferior-octave-buffer)))
664 (unless (comint-check-proc buffer)
be64c05d 665 (with-current-buffer buffer
0d634d3a
LL
666 (inferior-octave-startup)
667 (inferior-octave-mode)))
668 (unless arg
669 (pop-to-buffer buffer))
670 buffer))
be64c05d
LL
671
672;;;###autoload
673(defalias 'run-octave 'inferior-octave)
674
675(defun inferior-octave-startup ()
676 "Start an inferior Octave process."
677 (let ((proc (comint-exec-1
0d634d3a
LL
678 (substring inferior-octave-buffer 1 -1)
679 inferior-octave-buffer
680 inferior-octave-program
681 (append (list "-i" "--no-line-editing")
682 inferior-octave-startup-args))))
be64c05d 683 (set-process-filter proc 'inferior-octave-output-digest)
0d634d3a
LL
684 (setq inferior-octave-process proc
685 inferior-octave-output-list nil
686 inferior-octave-output-string nil
687 inferior-octave-receive-in-progress t)
be64c05d
LL
688
689 ;; This may look complicated ... However, we need to make sure that
690 ;; we additional startup code only AFTER Octave is ready (otherwise,
691 ;; output may be mixed up). Hence, we need to digest the Octave
692 ;; output to see when it issues a prompt.
693 (while inferior-octave-receive-in-progress
694 (accept-process-output inferior-octave-process))
695 (goto-char (point-max))
696 (set-marker (process-mark proc) (point))
697 (insert-before-markers
698 (concat
699 (if (not (bobp)) "\f\n")
700 (if inferior-octave-output-list
0d634d3a
LL
701 (concat (mapconcat
702 'identity inferior-octave-output-list "\n")
703 "\n"))))
be64c05d 704
be64c05d
LL
705 ;; An empty secondary prompt, as e.g. obtained by '--braindead',
706 ;; means trouble.
707 (inferior-octave-send-list-and-digest (list "PS2\n"))
0d634d3a
LL
708 (when (string-match "\\(PS2\\|ans\\) = *$"
709 (car inferior-octave-output-list))
710 (inferior-octave-send-list-and-digest (list "PS2 (\"> \");\n")))
711
712 ;; O.K., now we are ready for the Inferior Octave startup commands.
713 (inferior-octave-send-list-and-digest
714 (list "more off;\n"
715 (unless (equal inferior-octave-output-string ">> ")
716 "PS1 (\"\\\\s> \");\n")
717 (when (and inferior-octave-startup-file
718 (file-exists-p inferior-octave-startup-file))
719 (format "source (\"%s\");\n" inferior-octave-startup-file))))
720 ;; XXX: the first prompt is incorrectly highlighted
be64c05d
LL
721 (insert-before-markers
722 (concat
723 (if inferior-octave-output-list
0d634d3a
LL
724 (concat (mapconcat
725 'identity inferior-octave-output-list "\n")
726 "\n"))
be64c05d 727 inferior-octave-output-string))
be64c05d
LL
728
729 ;; And finally, everything is back to normal.
730 (set-process-filter proc 'inferior-octave-output-filter)
be64c05d
LL
731 ;; Just in case, to be sure a cd in the startup file
732 ;; won't have detrimental effects.
733 (inferior-octave-resync-dirs)))
734
584ea277 735(defun inferior-octave-completion-table ()
38d8527b
LL
736 (completion-table-dynamic
737 (lambda (command)
738 (inferior-octave-send-list-and-digest
739 (list (concat "completion_matches (\"" command "\");\n")))
740 (sort (delete-dups inferior-octave-output-list)
741 'string-lessp))))
584ea277 742
be64c05d
LL
743(defun inferior-octave-completion-at-point ()
744 "Return the data to complete the Octave symbol at point."
745 (let* ((end (point))
746 (start
747 (save-excursion
748 (skip-syntax-backward "w_" (comint-line-beginning-position))
749 (point))))
38d8527b
LL
750 (when (> end start)
751 (list start end (inferior-octave-completion-table)))))
be64c05d
LL
752
753(define-obsolete-function-alias 'inferior-octave-complete
754 'completion-at-point "24.1")
755
756(defun inferior-octave-dynamic-list-input-ring ()
757 "List the buffer's input history in a help buffer."
758 ;; We cannot use `comint-dynamic-list-input-ring', because it replaces
759 ;; "completion" by "history reference" ...
760 (interactive)
761 (if (or (not (ring-p comint-input-ring))
762 (ring-empty-p comint-input-ring))
763 (message "No history")
764 (let ((history nil)
765 (history-buffer " *Input History*")
766 (index (1- (ring-length comint-input-ring)))
767 (conf (current-window-configuration)))
768 ;; We have to build up a list ourselves from the ring vector.
769 (while (>= index 0)
770 (setq history (cons (ring-ref comint-input-ring index) history)
771 index (1- index)))
772 ;; Change "completion" to "history reference"
773 ;; to make the display accurate.
774 (with-output-to-temp-buffer history-buffer
775 (display-completion-list history)
776 (set-buffer history-buffer))
777 (message "Hit space to flush")
778 (let ((ch (read-event)))
779 (if (eq ch ?\ )
780 (set-window-configuration conf)
781 (setq unread-command-events (list ch)))))))
782
783(defun inferior-octave-strip-ctrl-g (string)
784 "Strip leading `^G' character.
785If STRING starts with a `^G', ring the bell and strip it."
786 (if (string-match "^\a" string)
787 (progn
788 (ding)
789 (setq string (substring string 1))))
790 string)
791
792(defun inferior-octave-output-filter (proc string)
793 "Standard output filter for the inferior Octave process.
794Ring Emacs bell if process output starts with an ASCII bell, and pass
795the rest to `comint-output-filter'."
796 (comint-output-filter proc (inferior-octave-strip-ctrl-g string)))
797
798(defun inferior-octave-output-digest (_proc string)
799 "Special output filter for the inferior Octave process.
800Save all output between newlines into `inferior-octave-output-list', and
801the rest to `inferior-octave-output-string'."
802 (setq string (concat inferior-octave-output-string string))
803 (while (string-match "\n" string)
804 (setq inferior-octave-output-list
805 (append inferior-octave-output-list
806 (list (substring string 0 (match-beginning 0))))
807 string (substring string (match-end 0))))
808 (if (string-match inferior-octave-prompt string)
809 (setq inferior-octave-receive-in-progress nil))
810 (setq inferior-octave-output-string string))
811
812(defun inferior-octave-send-list-and-digest (list)
813 "Send LIST to the inferior Octave process and digest the output.
814The elements of LIST have to be strings and are sent one by one. All
815output is passed to the filter `inferior-octave-output-digest'."
816 (let* ((proc inferior-octave-process)
817 (filter (process-filter proc))
818 string)
819 (set-process-filter proc 'inferior-octave-output-digest)
820 (setq inferior-octave-output-list nil)
821 (unwind-protect
822 (while (setq string (car list))
823 (setq inferior-octave-output-string nil
824 inferior-octave-receive-in-progress t)
825 (comint-send-string proc string)
826 (while inferior-octave-receive-in-progress
827 (accept-process-output proc))
828 (setq list (cdr list)))
829 (set-process-filter proc filter))))
830
831(defun inferior-octave-directory-tracker (string)
832 "Tracks `cd' commands issued to the inferior Octave process.
833Use \\[inferior-octave-resync-dirs] to resync if Emacs gets confused."
834 (cond
835 ((string-match "^[ \t]*cd[ \t;]*$" string)
836 (cd "~"))
837 ((string-match "^[ \t]*cd[ \t]+\\([^ \t\n;]*\\)[ \t\n;]*" string)
838 (cd (substring string (match-beginning 1) (match-end 1))))))
839
840(defun inferior-octave-resync-dirs ()
841 "Resync the buffer's idea of the current directory.
842This command queries the inferior Octave process about its current
843directory and makes this the current buffer's default directory."
844 (interactive)
845 (inferior-octave-send-list-and-digest '("disp (pwd ())\n"))
846 (cd (car inferior-octave-output-list)))
847
f2727dfb
RS
848\f
849;;; Miscellaneous useful functions
f2727dfb 850
070ccca4
LL
851(defun octave-in-comment-p ()
852 "Return non-nil if point is inside an Octave comment."
602ea69d 853 (nth 4 (syntax-ppss)))
f2727dfb 854
070ccca4
LL
855(defun octave-in-string-p ()
856 "Return non-nil if point is inside an Octave string."
602ea69d 857 (nth 3 (syntax-ppss)))
f2727dfb 858
070ccca4
LL
859(defun octave-in-string-or-comment-p ()
860 "Return non-nil if point is inside an Octave string or comment."
861 (nth 8 (syntax-ppss)))
f2727dfb 862
a584f30f 863(defun octave-looking-at-kw (regexp)
050a4b35 864 "Like `looking-at', but sets `case-fold-search' nil."
a584f30f
GM
865 (let ((case-fold-search nil))
866 (looking-at regexp)))
867
d83ee578
KH
868(defun octave-maybe-insert-continuation-string ()
869 (if (or (octave-in-comment-p)
870 (save-excursion
871 (beginning-of-line)
872 (looking-at octave-continuation-regexp)))
873 nil
874 (delete-horizontal-space)
875 (insert (concat " " octave-continuation-string))))
e55d3b04 876
d4d0f9b3
LL
877(defun octave-completing-read ()
878 (let ((def (or (thing-at-point 'symbol)
879 (save-excursion
880 (skip-syntax-backward "-(")
881 (thing-at-point 'symbol)))))
882 (completing-read
883 (format (if def "Function (default %s): "
884 "Function: ") def)
885 (inferior-octave-completion-table)
886 nil nil nil nil def)))
887
888(defun octave-goto-function-definition ()
889 "Go to the first function definition."
890 (when (save-excursion
891 (goto-char (point-min))
892 (re-search-forward octave-function-header-regexp nil t))
893 (goto-char (match-beginning 3))
894 (match-string 3)))
895
b7260dd4
LL
896(defun octave-function-file-p ()
897 "Return non-nil if the first token is \"function\".
898The value is (START END NAME-START NAME-END) of the function."
899 (save-excursion
900 (goto-char (point-min))
901 (when (equal (funcall smie-forward-token-function) "function")
902 (forward-word -1)
903 (let* ((start (point))
904 (end (progn (forward-sexp 1) (point)))
905 (name (when (progn
906 (goto-char start)
907 (re-search-forward octave-function-header-regexp
908 end t))
909 (list (match-beginning 3) (match-end 3)))))
910 (cons start (cons end name))))))
911
912;; Like forward-comment but stop at non-comment blank
913(defun octave-skip-comment-forward (limit)
914 (let ((ppss (syntax-ppss)))
915 (if (nth 4 ppss)
916 (goto-char (nth 8 ppss))
917 (goto-char (or (comment-search-forward limit t) (point)))))
918 (while (and (< (point) limit) (looking-at-p "\\s<"))
919 (forward-comment 1)))
920
921;;; First non-copyright comment block
922(defun octave-function-file-comment ()
2ec12cb0 923 "Beginning and end positions of the function file comment."
b7260dd4
LL
924 (save-excursion
925 (goto-char (point-min))
38d8527b
LL
926 ;; Copyright block: octave/libinterp/parse-tree/lex.ll around line 1634
927 (while (save-excursion
928 (when (comment-search-forward (point-max) t)
929 (when (eq (char-after) ?\{) ; case of block comment
930 (forward-char 1))
931 (skip-syntax-forward "-")
932 (let ((case-fold-search t))
933 (looking-at-p "\\(?:copyright\\|author\\)\\_>"))))
934 (octave-skip-comment-forward (point-max)))
935 (let ((beg (comment-search-forward (point-max) t)))
936 (when beg
937 (goto-char beg)
938 (octave-skip-comment-forward (point-max))
939 (list beg (point))))))
b7260dd4 940
e55d3b04
LL
941(defun octave-sync-function-file-names ()
942 "Ensure function name agree with function file name.
943See Info node `(octave)Function Files'."
944 (interactive)
b7260dd4
LL
945 (when buffer-file-name
946 (pcase-let ((`(,start ,_end ,name-start ,name-end)
947 (octave-function-file-p)))
948 (when (and start name-start)
2ec12cb0
LL
949 (let* ((func (buffer-substring name-start name-end))
950 (file (file-name-sans-extension
951 (file-name-nondirectory buffer-file-name)))
952 (help-form (format "\
953a: Use function name `%s'
954b: Use file name `%s'
955q: Don't fix\n" func file))
956 (c (unless (equal file func)
957 (save-window-excursion
958 (help-form-show)
959 (read-char-choice
960 "Which name to use? (a/b/q) " '(?a ?b ?q))))))
961 (pcase c
962 (`?a (let ((newname (expand-file-name
963 (concat func (file-name-extension
964 buffer-file-name t)))))
965 (when (or (not (file-exists-p newname))
966 (yes-or-no-p
967 (format "Target file %s exists; proceed? " newname)))
968 (when (file-exists-p buffer-file-name)
969 (rename-file buffer-file-name newname t))
970 (set-visited-file-name newname))))
971 (`?b (save-excursion
972 (goto-char name-start)
973 (delete-region name-start name-end)
974 (insert file)))))))))
b7260dd4
LL
975
976(defun octave-update-function-file-comment (beg end)
977 "Query replace function names in function file comment."
978 (interactive
979 (progn
980 (barf-if-buffer-read-only)
981 (if (use-region-p)
982 (list (region-beginning) (region-end))
983 (or (octave-function-file-comment)
984 (error "No function file comment found")))))
e55d3b04 985 (save-excursion
b7260dd4
LL
986 (let* ((bounds (or (octave-function-file-p)
987 (error "Not in a function file buffer")))
988 (func (if (cddr bounds)
989 (apply #'buffer-substring (cddr bounds))
990 (error "Function name not found")))
991 (old-func (progn
992 (goto-char beg)
38d8527b
LL
993 (when (re-search-forward
994 "[=}]\\s-*\\(\\(?:\\sw\\|\\s_\\)+\\)\\_>"
995 (min (line-end-position 4) end)
996 t)
b7260dd4
LL
997 (match-string 1))))
998 (old-func (read-string (format (if old-func
999 "Name to replace (default %s): "
1000 "Name to replace: ")
1001 old-func)
1002 nil nil old-func)))
1003 (if (and func old-func (not (equal func old-func)))
1004 (perform-replace old-func func 'query
1005 nil 'delimited nil nil beg end)
1006 (message "Function names match")))))
e55d3b04 1007
5b78d7fc
LL
1008;; Adapted from texinfo-font-lock-keywords
1009(defvar octave-texinfo-font-lock-keywords
1010 `(("@\\([a-zA-Z]+\\|[^ \t\n]\\)" 1 font-lock-keyword-face prepend) ;commands
1011 ("^\\*\\([^\n:]*\\)" 1 font-lock-function-name-face prepend) ;menu items
1012 ("@\\(emph\\|i\\|sc\\){\\([^}]+\\)" 2 'italic prepend)
1013 ("@\\(strong\\|b\\){\\([^}]+\\)" 2 'bold prepend)
1014 ("@\\(kbd\\|key\\|url\\|uref\\){\\([^}]+\\)"
1015 2 font-lock-string-face prepend)
1016 ("@\\(file\\|email\\){\\([^}]+\\)" 2 font-lock-string-face prepend)
1017 ("@\\(samp\\|code\\|var\\|math\\|env\\|command\\|option\\){\\([^}]+\\)"
1018 2 font-lock-variable-name-face prepend)
1019 ("@\\(cite\\|x?ref\\|pxref\\|dfn\\|inforef\\){\\([^}]+\\)"
1020 2 font-lock-constant-face prepend)
1021 ("@\\(anchor\\){\\([^}]+\\)" 2 font-lock-type-face prepend)
1022 ("@\\(dmn\\|acronym\\|value\\){\\([^}]+\\)"
1023 2 font-lock-builtin-face prepend)
1024 ("@\\(end\\|itemx?\\) +\\(.+\\)" 2 font-lock-keyword-face prepend))
1025 "Additional keywords to highlight in texinfo comment block.")
1026
1027(defface octave-function-comment-block
1028 '((t (:inherit font-lock-doc-face)))
1029 "Face used to highlight function comment block."
1030 :group 'octave)
1031
1032(defun octave-font-lock-texinfo-comment ()
1033 (font-lock-add-keywords
1034 nil
1035 '(((lambda (limit)
1036 (while (and (search-forward "-*- texinfo -*-" limit t)
1037 (octave-in-comment-p))
1038 (let ((beg (nth 8 (syntax-ppss)))
1039 (end (progn
1040 (octave-skip-comment-forward (point-max))
1041 (point))))
1042 (put-text-property beg end 'font-lock-multiline t)
1043 (font-lock-prepend-text-property
1044 beg end 'face 'octave-function-comment-block)
1045 (dolist (kw octave-texinfo-font-lock-keywords)
1046 (goto-char beg)
1047 (while (re-search-forward (car kw) end 'move)
1048 (font-lock-apply-highlight (cdr kw))))))
1049 nil)))
1050 'append))
1051
f2727dfb
RS
1052\f
1053;;; Indentation
f2727dfb
RS
1054
1055(defun octave-indent-new-comment-line ()
1056 "Break Octave line at point, continuing comment if within one.
1057If within code, insert `octave-continuation-string' before breaking the
a1506d29
JB
1058line. If within a string, signal an error.
1059The new line is properly indented."
f2727dfb
RS
1060 (interactive)
1061 (delete-horizontal-space)
1062 (cond
1063 ((octave-in-comment-p)
1064 (indent-new-comment-line))
1065 ((octave-in-string-p)
1066 (error "Cannot split a code line inside a string"))
1067 (t
1068 (insert (concat " " octave-continuation-string))
03f70355 1069 (reindent-then-newline-and-indent))))
f2727dfb
RS
1070
1071(defun octave-indent-defun ()
e22bbd48 1072 "Properly indent the Octave function which contains point."
f2727dfb
RS
1073 (interactive)
1074 (save-excursion
ff80a446 1075 (mark-defun)
f2727dfb
RS
1076 (message "Indenting function...")
1077 (indent-region (point) (mark) nil))
1078 (message "Indenting function...done."))
1079
1080\f
1081;;; Motion
1082(defun octave-next-code-line (&optional arg)
1083 "Move ARG lines of Octave code forward (backward if ARG is negative).
1084Skips past all empty and comment lines. Default for ARG is 1.
1085
1086On success, return 0. Otherwise, go as far as possible and return -1."
1087 (interactive "p")
1088 (or arg (setq arg 1))
1089 (beginning-of-line)
1090 (let ((n 0)
1091 (inc (if (> arg 0) 1 -1)))
1092 (while (and (/= arg 0) (= n 0))
1093 (setq n (forward-line inc))
1094 (while (and (= n 0)
1095 (looking-at "\\s-*\\($\\|\\s<\\)"))
1096 (setq n (forward-line inc)))
1097 (setq arg (- arg inc)))
1098 n))
a1506d29 1099
f2727dfb
RS
1100(defun octave-previous-code-line (&optional arg)
1101 "Move ARG lines of Octave code backward (forward if ARG is negative).
1102Skips past all empty and comment lines. Default for ARG is 1.
1103
1104On success, return 0. Otherwise, go as far as possible and return -1."
1105 (interactive "p")
1106 (or arg (setq arg 1))
1107 (octave-next-code-line (- arg)))
1108
1109(defun octave-beginning-of-line ()
1110 "Move point to beginning of current Octave line.
1111If on an empty or comment line, go to the beginning of that line.
1112Otherwise, move backward to the beginning of the first Octave code line
1113which is not inside a continuation statement, i.e., which does not
1114follow a code line ending in `...' or `\\', or is inside an open
1115parenthesis list."
1116 (interactive)
1117 (beginning-of-line)
1118 (if (not (looking-at "\\s-*\\($\\|\\s<\\)"))
1119 (while (or (condition-case nil
1120 (progn
1121 (up-list -1)
1122 (beginning-of-line)
1123 t)
1124 (error nil))
1125 (and (or (looking-at "\\s-*\\($\\|\\s<\\)")
1126 (save-excursion
1127 (if (zerop (octave-previous-code-line))
1128 (looking-at octave-continuation-regexp))))
1129 (zerop (forward-line -1)))))))
1130
1131(defun octave-end-of-line ()
1132 "Move point to end of current Octave line.
1133If on an empty or comment line, go to the end of that line.
1134Otherwise, move forward to the end of the first Octave code line which
1135does not end in `...' or `\\' or is inside an open parenthesis list."
1136 (interactive)
1137 (end-of-line)
1138 (if (save-excursion
1139 (beginning-of-line)
1140 (looking-at "\\s-*\\($\\|\\s<\\)"))
1141 ()
1142 (while (or (condition-case nil
1143 (progn
1144 (up-list 1)
1145 (end-of-line)
1146 t)
1147 (error nil))
1148 (and (save-excursion
1149 (beginning-of-line)
1150 (or (looking-at "\\s-*\\($\\|\\s<\\)")
1151 (looking-at octave-continuation-regexp)))
1152 (zerop (forward-line 1)))))
1153 (end-of-line)))
a1506d29 1154
f2727dfb
RS
1155(defun octave-mark-block ()
1156 "Put point at the beginning of this Octave block, mark at the end.
1157The block marked is the one that contains point or follows point."
1158 (interactive)
ef54d315
SM
1159 (if (and (looking-at "\\sw\\|\\s_")
1160 (looking-back "\\sw\\|\\s_" (1- (point))))
1161 (skip-syntax-forward "w_"))
ec5d3ff7
SM
1162 (unless (or (looking-at "\\s(")
1163 (save-excursion
1164 (let* ((token (funcall smie-forward-token-function))
6d2a1e35 1165 (level (assoc token smie-grammar)))
ef54d315 1166 (and level (not (numberp (cadr level)))))))
ec5d3ff7
SM
1167 (backward-up-list 1))
1168 (mark-sexp))
f2727dfb 1169
f2727dfb
RS
1170(defun octave-beginning-of-defun (&optional arg)
1171 "Move backward to the beginning of an Octave function.
1172With positive ARG, do it that many times. Negative argument -N means
1173move forward to Nth following beginning of a function.
1174Returns t unless search stops at the beginning or end of the buffer."
f2727dfb
RS
1175 (let* ((arg (or arg 1))
1176 (inc (if (> arg 0) 1 -1))
ff80a446
SM
1177 (found nil)
1178 (case-fold-search nil))
f2727dfb 1179 (and (not (eobp))
e92f3bd3 1180 (not (and (> arg 0) (looking-at "\\_<function\\_>")))
f2727dfb
RS
1181 (skip-syntax-forward "w"))
1182 (while (and (/= arg 0)
1183 (setq found
e92f3bd3 1184 (re-search-backward "\\_<function\\_>" inc)))
070ccca4
LL
1185 (unless (octave-in-string-or-comment-p)
1186 (setq arg (- arg inc))))
f2727dfb
RS
1187 (if found
1188 (progn
1189 (and (< inc 0) (goto-char (match-beginning 0)))
1190 t))))
1191
f2727dfb
RS
1192\f
1193;;; Filling
1194(defun octave-auto-fill ()
d83ee578
KH
1195 "Perform auto-fill in Octave mode.
1196Returns nil if no feasible place to break the line could be found, and t
1197otherwise."
1198 (let (fc give-up)
1199 (if (or (null (setq fc (current-fill-column)))
1200 (save-excursion
a1506d29 1201 (beginning-of-line)
d83ee578 1202 (and auto-fill-inhibit-regexp
a584f30f 1203 (octave-looking-at-kw auto-fill-inhibit-regexp))))
d83ee578
KH
1204 nil ; Can't do anything
1205 (if (and (not (octave-in-comment-p))
1206 (> (current-column) fc))
1207 (setq fc (- fc (+ (length octave-continuation-string) 1))))
1208 (while (and (not give-up) (> (current-column) fc))
1209 (let* ((opoint (point))
1210 (fpoint
1211 (save-excursion
1212 (move-to-column (+ fc 1))
1213 (skip-chars-backward "^ \t\n")
1214 ;; If we're at the beginning of the line, break after
1215 ;; the first word
1216 (if (bolp)
1217 (re-search-forward "[ \t]" opoint t))
1218 ;; If we're in a comment line, don't break after the
1219 ;; comment chars
1220 (if (save-excursion
1221 (skip-syntax-backward " <")
1222 (bolp))
cb3d3ec1 1223 (re-search-forward "[ \t]" (line-end-position)
d83ee578
KH
1224 'move))
1225 ;; If we're not in a comment line and just ahead the
1226 ;; continuation string, don't break here.
1227 (if (and (not (octave-in-comment-p))
1228 (looking-at
1229 (concat "\\s-*"
1230 (regexp-quote
1231 octave-continuation-string)
1232 "\\s-*$")))
1233 (end-of-line))
1234 (skip-chars-backward " \t")
1235 (point))))
1236 (if (save-excursion
1237 (goto-char fpoint)
1238 (not (or (bolp) (eolp))))
1239 (let ((prev-column (current-column)))
1240 (if (save-excursion
1241 (skip-chars-backward " \t")
1242 (= (point) fpoint))
1243 (progn
1244 (octave-maybe-insert-continuation-string)
1245 (indent-new-comment-line t))
1246 (save-excursion
1247 (goto-char fpoint)
1248 (octave-maybe-insert-continuation-string)
1249 (indent-new-comment-line t)))
1250 (if (>= (current-column) prev-column)
1251 (setq give-up t)))
1252 (setq give-up t))))
1253 (not give-up))))
f2727dfb 1254
e02f48d7 1255(defun octave-fill-paragraph (&optional _arg)
ec5d3ff7
SM
1256 "Fill paragraph of Octave code, handling Octave comments."
1257 ;; FIXME: difference with generic fill-paragraph:
1258 ;; - code lines are only split, never joined.
1259 ;; - \n that end comments are never removed.
1260 ;; - insert continuation marker when splitting code lines.
1261 (interactive "P")
1262 (save-excursion
1263 (let ((end (progn (forward-paragraph) (copy-marker (point) t)))
1264 (beg (progn
1265 (forward-paragraph -1)
1266 (skip-chars-forward " \t\n")
1267 (beginning-of-line)
1268 (point)))
1269 (cfc (current-fill-column))
1270 comment-prefix)
1271 (goto-char beg)
1272 (while (< (point) end)
1273 (condition-case nil
1274 (indent-according-to-mode)
1275 (error nil))
1276 (move-to-column cfc)
1277 ;; First check whether we need to combine non-empty comment lines
1278 (if (and (< (current-column) cfc)
1279 (octave-in-comment-p)
1280 (not (save-excursion
1281 (beginning-of-line)
1282 (looking-at "^\\s-*\\s<+\\s-*$"))))
1283 ;; This is a nonempty comment line which does not extend
1284 ;; past the fill column. If it is followed by a nonempty
1285 ;; comment line with the same comment prefix, try to
1286 ;; combine them, and repeat this until either we reach the
1287 ;; fill-column or there is nothing more to combine.
1288 (progn
1289 ;; Get the comment prefix
1290 (save-excursion
1291 (beginning-of-line)
1292 (while (and (re-search-forward "\\s<+")
1293 (not (octave-in-comment-p))))
1294 (setq comment-prefix (match-string 0)))
1295 ;; And keep combining ...
1296 (while (and (< (current-column) cfc)
1297 (save-excursion
1298 (forward-line 1)
1299 (and (looking-at
1300 (concat "^\\s-*"
1301 comment-prefix
1302 "\\S<"))
1303 (not (looking-at
1304 (concat "^\\s-*"
1305 comment-prefix
1306 "\\s-*$"))))))
1307 (delete-char 1)
1308 (re-search-forward comment-prefix)
1309 (delete-region (match-beginning 0) (match-end 0))
1310 (fixup-whitespace)
1311 (move-to-column cfc))))
1312 ;; We might also try to combine continued code lines> Perhaps
1313 ;; some other time ...
1314 (skip-chars-forward "^ \t\n")
1315 (delete-horizontal-space)
1316 (if (or (< (current-column) cfc)
1317 (and (= (current-column) cfc) (eolp)))
1318 (forward-line 1)
1319 (if (not (eolp)) (insert " "))
1320 (or (octave-auto-fill)
1321 (forward-line 1))))
1322 t)))
f2727dfb
RS
1323
1324\f
1325;;; Completions
c82d5b11
SM
1326
1327(defun octave-completion-at-point-function ()
1328 "Find the text to complete and the corresponding table."
e92f3bd3 1329 (let* ((beg (save-excursion (skip-syntax-backward "w_") (point)))
ff80a446
SM
1330 (end (point)))
1331 (if (< beg (point))
1332 ;; Extend region past point, if applicable.
e92f3bd3
SM
1333 (save-excursion (skip-syntax-forward "w_")
1334 (setq end (point))))
584ea277
LL
1335 (list beg end (or (and inferior-octave-process
1336 (process-live-p inferior-octave-process)
1337 (inferior-octave-completion-table))
1338 (append octave-reserved-words
5b78d7fc 1339 octave-text-functions)))))
f2727dfb 1340
bcd70d97
SM
1341(define-obsolete-function-alias 'octave-complete-symbol
1342 'completion-at-point "24.1")
f2727dfb
RS
1343\f
1344;;; Electric characters && friends
c82d5b11 1345(define-skeleton octave-insert-defun
f2727dfb
RS
1346 "Insert an Octave function skeleton.
1347Prompt for the function's name, arguments and return values (to be
1348entered without parens)."
070ccca4 1349 (let* ((defname (file-name-sans-extension (buffer-name)))
c82d5b11
SM
1350 (name (read-string (format "Function name (default %s): " defname)
1351 nil nil defname))
1352 (args (read-string "Arguments: "))
1353 (vals (read-string "Return values: ")))
1354 (format "%s%s (%s)"
1355 (cond
1356 ((string-equal vals "") vals)
1357 ((string-match "[ ,]" vals) (concat "[" vals "] = "))
1358 (t (concat vals " = ")))
1359 name
1360 args))
b7260dd4
LL
1361 \n octave-block-comment-start "usage: " str \n
1362 octave-block-comment-start '(delete-horizontal-space) \n
1363 octave-block-comment-start '(delete-horizontal-space) \n
1364 "function " > str \n
1365 _ \n
c82d5b11 1366 "endfunction" > \n)
f2727dfb 1367\f
f2727dfb
RS
1368;;; Communication with the inferior Octave process
1369(defun octave-kill-process ()
1370 "Kill inferior Octave process and its buffer."
1371 (interactive)
1372 (if inferior-octave-process
1373 (progn
1374 (process-send-string inferior-octave-process "quit;\n")
1375 (accept-process-output inferior-octave-process)))
1376 (if inferior-octave-buffer
1377 (kill-buffer inferior-octave-buffer)))
1378
1379(defun octave-show-process-buffer ()
1380 "Make sure that `inferior-octave-buffer' is displayed."
1381 (interactive)
1382 (if (get-buffer inferior-octave-buffer)
1383 (display-buffer inferior-octave-buffer)
1384 (message "No buffer named %s" inferior-octave-buffer)))
1385
1386(defun octave-hide-process-buffer ()
1387 "Delete all windows that display `inferior-octave-buffer'."
1388 (interactive)
1389 (if (get-buffer inferior-octave-buffer)
1390 (delete-windows-on inferior-octave-buffer)
1391 (message "No buffer named %s" inferior-octave-buffer)))
1392
1393(defun octave-send-region (beg end)
1394 "Send current region to the inferior Octave process."
1395 (interactive "r")
a1506d29 1396 (inferior-octave t)
f2727dfb
RS
1397 (let ((proc inferior-octave-process)
1398 (string (buffer-substring-no-properties beg end))
1399 line)
5d8137ab 1400 (with-current-buffer inferior-octave-buffer
f2727dfb
RS
1401 (setq inferior-octave-output-list nil)
1402 (while (not (string-equal string ""))
1403 (if (string-match "\n" string)
1404 (setq line (substring string 0 (match-beginning 0))
1405 string (substring string (match-end 0)))
1406 (setq line string string ""))
1407 (setq inferior-octave-receive-in-progress t)
1408 (inferior-octave-send-list-and-digest (list (concat line "\n")))
1409 (while inferior-octave-receive-in-progress
1410 (accept-process-output proc))
1411 (insert-before-markers
1412 (mapconcat 'identity
1413 (append
1414 (if octave-send-echo-input (list line) (list ""))
1415 (mapcar 'inferior-octave-strip-ctrl-g
1416 inferior-octave-output-list)
1417 (list inferior-octave-output-string))
1418 "\n")))))
1419 (if octave-send-show-buffer
1420 (display-buffer inferior-octave-buffer)))
1421
1422(defun octave-send-block ()
a1506d29 1423 "Send current Octave block to the inferior Octave process."
f2727dfb
RS
1424 (interactive)
1425 (save-excursion
1426 (octave-mark-block)
1427 (octave-send-region (point) (mark))))
1428
1429(defun octave-send-defun ()
1430 "Send current Octave function to the inferior Octave process."
1431 (interactive)
1432 (save-excursion
ff80a446 1433 (mark-defun)
f2727dfb
RS
1434 (octave-send-region (point) (mark))))
1435
1436(defun octave-send-line (&optional arg)
1437 "Send current Octave code line to the inferior Octave process.
1438With positive prefix ARG, send that many lines.
1439If `octave-send-line-auto-forward' is non-nil, go to the next unsent
1440code line."
1441 (interactive "P")
1442 (or arg (setq arg 1))
1443 (if (> arg 0)
1444 (let (beg end)
1445 (beginning-of-line)
1446 (setq beg (point))
1447 (octave-next-code-line (- arg 1))
1448 (end-of-line)
1449 (setq end (point))
1450 (if octave-send-line-auto-forward
1451 (octave-next-code-line 1))
1452 (octave-send-region beg end))))
1453
1454(defun octave-eval-print-last-sexp ()
1455 "Evaluate Octave sexp before point and print value into current buffer."
1456 (interactive)
1457 (inferior-octave t)
1458 (let ((standard-output (current-buffer))
1459 (print-escape-newlines nil)
1460 (opoint (point)))
1461 (terpri)
a1506d29 1462 (prin1
f2727dfb
RS
1463 (save-excursion
1464 (forward-sexp -1)
1465 (inferior-octave-send-list-and-digest
1466 (list (concat (buffer-substring-no-properties (point) opoint)
1467 "\n")))
1468 (mapconcat 'identity inferior-octave-output-list "\n")))
1469 (terpri)))
070ccca4 1470
d4d0f9b3
LL
1471\f
1472
1473(defcustom octave-help-buffer "*Octave Help*"
1474 "Buffer name for `octave-help'."
1475 :type 'string
1476 :group 'octave
1477 :version "24.4")
1478
1479(define-button-type 'octave-help-file
1480 'follow-link t
1481 'action #'help-button-action
1482 'help-function (lambda (fn)
1483 (find-file fn)
1484 (octave-goto-function-definition)))
1485
1486(define-button-type 'octave-help-function
1487 'follow-link t
1488 'action (lambda (b)
1489 (octave-help
1490 (buffer-substring (button-start b) (button-end b)))))
1491
1492(defvar help-xref-following)
1493
1494(defun octave-help (fn)
1495 "Display the documentation of FN."
1496 (interactive (list (octave-completing-read)))
1497 (inferior-octave-send-list-and-digest
1498 (list (format "help \"%s\"\n" fn)))
1499 (let ((lines inferior-octave-output-list))
1500 (when (string-match "error: \\(.*\\)$" (car lines))
1501 (error "%s" (match-string 1 (car lines))))
1502 (with-help-window octave-help-buffer
1503 (princ (mapconcat 'identity lines "\n"))
1504 (with-current-buffer octave-help-buffer
1505 ;; Bound to t so that `help-buffer' returns current buffer for
1506 ;; `help-setup-xref'.
1507 (let ((help-xref-following t))
1508 (help-setup-xref (list 'octave-help fn)
1509 (called-interactively-p 'interactive)))
1510 ;; Note: can be turned off by suppress_verbose_help_message.
1511 ;;
1512 ;; Remove boring trailing text: Additional help for built-in functions
1513 ;; and operators ...
1514 (goto-char (point-max))
1515 (when (search-backward "\n\n\n" nil t)
1516 (goto-char (match-beginning 0))
1517 (delete-region (point) (point-max)))
1518 ;; File name highlight
1519 (goto-char (point-min))
1520 (when (re-search-forward "from the file \\(.*\\)$"
1521 (line-end-position)
1522 t)
1523 (let ((file (match-string 1)))
1524 (replace-match "" nil nil nil 1)
1525 (insert "`")
1526 (help-insert-xref-button (file-name-nondirectory file)
1527 'octave-help-file file)
1528 (insert "'")))
1529 ;; Make 'See also' clickable
1530 (with-syntax-table octave-mode-syntax-table
1531 (when (re-search-forward "^\\s-*See also:" nil t)
1532 (while (re-search-forward "\\_<\\(?:\\sw\\|\\s_\\)+\\_>" nil t)
1533 (make-text-button (match-beginning 0)
1534 (match-end 0)
1535 :type 'octave-help-function))))))))
1536
1537(defvar find-tag-marker-ring)
1538
1539(defun octave-find-definition (fn)
1540 "Find the definition of FN."
1541 (interactive (list (octave-completing-read)))
1542 (inferior-octave-send-list-and-digest
1543 ;; help NAME is more verbose
1544 (list (format "\
1545if iskeyword(\"%s\") disp(\"`%s' is a keyword\") else which(\"%s\") endif\n"
1546 fn fn fn)))
1547 (let* ((line (car inferior-octave-output-list))
1548 (file (when (and line (string-match "from the file \\(.*\\)$" line))
1549 (match-string 1 line))))
1550 (if (not file)
1551 (user-error "%s" (or line (format "`%s' not found" fn)))
1552 (require 'etags)
1553 (ring-insert find-tag-marker-ring (point-marker))
1554 (find-file file)
1555 (octave-goto-function-definition))))
1556
d1e49742 1557
be64c05d
LL
1558(provide 'octave)
1559;;; octave.el ends here