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