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