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