]> code.delx.au - gnu-emacs/blob - lisp/progmodes/octave.el
* progmodes/octave.el (inferior-octave-completion-table): No
[gnu-emacs] / 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 (insert-before-markers
720 (concat
721 (if inferior-octave-output-list
722 (concat (mapconcat
723 'identity inferior-octave-output-list "\n")
724 "\n"))
725 inferior-octave-output-string))
726
727 ;; And finally, everything is back to normal.
728 (set-process-filter proc 'comint-output-filter)
729 ;; Just in case, to be sure a cd in the startup file
730 ;; won't have detrimental effects.
731 (inferior-octave-resync-dirs)
732 ;; A trick to get the prompt highlighted.
733 (comint-send-string proc "\n")))
734
735 (defvar inferior-octave-completion-table
736 ;;
737 ;; Use cache to avod repetitive computation of completions due to
738 ;; bug#11906 - http://debbugs.gnu.org/11906 - which may cause
739 ;; noticeable delay. CACHE: (CMD TIME VALUE).
740 (let ((cache))
741 (completion-table-dynamic
742 (lambda (command)
743 (unless (and (equal (car cache) command)
744 (< (float-time) (+ 5 (cadr cache))))
745 (inferior-octave-send-list-and-digest
746 (list (concat "completion_matches (\"" command "\");\n")))
747 (setq cache (list command (float-time)
748 (sort (delete-dups inferior-octave-output-list)
749 'string-lessp))))
750 (car (cddr cache))))))
751
752 (defun inferior-octave-completion-at-point ()
753 "Return the data to complete the Octave symbol at point."
754 ;; http://debbugs.gnu.org/14300
755 (let* ((filecomp (string-match-p
756 "/" (or (comint--match-partial-filename) "")))
757 (end (point))
758 (start
759 (unless filecomp
760 (save-excursion
761 (skip-syntax-backward "w_" (comint-line-beginning-position))
762 (point)))))
763 (when (and start (> end start))
764 (list start end (completion-table-in-turn
765 inferior-octave-completion-table
766 'comint-completion-file-name-table)))))
767
768 (define-obsolete-function-alias 'inferior-octave-complete
769 'completion-at-point "24.1")
770
771 (defun inferior-octave-dynamic-list-input-ring ()
772 "List the buffer's input history in a help buffer."
773 ;; We cannot use `comint-dynamic-list-input-ring', because it replaces
774 ;; "completion" by "history reference" ...
775 (interactive)
776 (if (or (not (ring-p comint-input-ring))
777 (ring-empty-p comint-input-ring))
778 (message "No history")
779 (let ((history nil)
780 (history-buffer " *Input History*")
781 (index (1- (ring-length comint-input-ring)))
782 (conf (current-window-configuration)))
783 ;; We have to build up a list ourselves from the ring vector.
784 (while (>= index 0)
785 (setq history (cons (ring-ref comint-input-ring index) history)
786 index (1- index)))
787 ;; Change "completion" to "history reference"
788 ;; to make the display accurate.
789 (with-output-to-temp-buffer history-buffer
790 (display-completion-list history)
791 (set-buffer history-buffer))
792 (message "Hit space to flush")
793 (let ((ch (read-event)))
794 (if (eq ch ?\ )
795 (set-window-configuration conf)
796 (setq unread-command-events (list ch)))))))
797
798 (defun inferior-octave-output-digest (_proc string)
799 "Special output filter for the inferior Octave process.
800 Save all output between newlines into `inferior-octave-output-list', and
801 the rest to `inferior-octave-output-string'."
802 (setq string (concat inferior-octave-output-string string))
803 (while (string-match "\n" string)
804 (setq inferior-octave-output-list
805 (append inferior-octave-output-list
806 (list (substring string 0 (match-beginning 0))))
807 string (substring string (match-end 0))))
808 (if (string-match inferior-octave-prompt string)
809 (setq inferior-octave-receive-in-progress nil))
810 (setq inferior-octave-output-string string))
811
812 (defun inferior-octave-send-list-and-digest (list)
813 "Send LIST to the inferior Octave process and digest the output.
814 The elements of LIST have to be strings and are sent one by one. All
815 output is passed to the filter `inferior-octave-output-digest'."
816 (or (and inferior-octave-process
817 (process-live-p inferior-octave-process))
818 (error (substitute-command-keys
819 "No inferior octave process running. Type \\[run-octave]")))
820 (let* ((proc inferior-octave-process)
821 (filter (process-filter proc))
822 string)
823 (set-process-filter proc 'inferior-octave-output-digest)
824 (setq inferior-octave-output-list nil)
825 (unwind-protect
826 (while (setq string (car list))
827 (setq inferior-octave-output-string nil
828 inferior-octave-receive-in-progress t)
829 (comint-send-string proc string)
830 (while inferior-octave-receive-in-progress
831 (accept-process-output proc))
832 (setq list (cdr list)))
833 (set-process-filter proc filter))))
834
835 (defun inferior-octave-directory-tracker (string)
836 "Tracks `cd' commands issued to the inferior Octave process.
837 Use \\[inferior-octave-resync-dirs] to resync if Emacs gets confused."
838 (cond
839 ((string-match "^[ \t]*cd[ \t;]*$" string)
840 (cd "~"))
841 ((string-match "^[ \t]*cd[ \t]+\\([^ \t\n;]*\\)[ \t\n;]*" string)
842 (with-demoted-errors ; in case directory doesn't exist
843 (cd (substring string (match-beginning 1) (match-end 1)))))))
844
845 (defun inferior-octave-resync-dirs ()
846 "Resync the buffer's idea of the current directory.
847 This command queries the inferior Octave process about its current
848 directory and makes this the current buffer's default directory."
849 (interactive)
850 (inferior-octave-send-list-and-digest '("disp (pwd ())\n"))
851 (cd (car inferior-octave-output-list)))
852
853 \f
854 ;;; Miscellaneous useful functions
855
856 (defun octave-in-comment-p ()
857 "Return non-nil if point is inside an Octave comment."
858 (nth 4 (syntax-ppss)))
859
860 (defun octave-in-string-p ()
861 "Return non-nil if point is inside an Octave string."
862 (nth 3 (syntax-ppss)))
863
864 (defun octave-in-string-or-comment-p ()
865 "Return non-nil if point is inside an Octave string or comment."
866 (nth 8 (syntax-ppss)))
867
868 (defun octave-looking-at-kw (regexp)
869 "Like `looking-at', but sets `case-fold-search' nil."
870 (let ((case-fold-search nil))
871 (looking-at regexp)))
872
873 (defun octave-maybe-insert-continuation-string ()
874 (if (or (octave-in-comment-p)
875 (save-excursion
876 (beginning-of-line)
877 (looking-at octave-continuation-regexp)))
878 nil
879 (delete-horizontal-space)
880 (insert (concat " " octave-continuation-string))))
881
882 (defun octave-completing-read ()
883 (let ((def (or (thing-at-point 'symbol)
884 (save-excursion
885 (skip-syntax-backward "-(")
886 (thing-at-point 'symbol)))))
887 (completing-read
888 (format (if def "Function (default %s): "
889 "Function: ") def)
890 inferior-octave-completion-table
891 nil nil nil nil def)))
892
893 (defun octave-goto-function-definition ()
894 "Go to the first function definition."
895 (when (save-excursion
896 (goto-char (point-min))
897 (re-search-forward octave-function-header-regexp nil t))
898 (goto-char (match-beginning 3))
899 (match-string 3)))
900
901 (defun octave-function-file-p ()
902 "Return non-nil if the first token is \"function\".
903 The value is (START END NAME-START NAME-END) of the function."
904 (save-excursion
905 (goto-char (point-min))
906 (when (equal (funcall smie-forward-token-function) "function")
907 (forward-word -1)
908 (let* ((start (point))
909 (end (progn (forward-sexp 1) (point)))
910 (name (when (progn
911 (goto-char start)
912 (re-search-forward octave-function-header-regexp
913 end t))
914 (list (match-beginning 3) (match-end 3)))))
915 (cons start (cons end name))))))
916
917 ;; Like forward-comment but stop at non-comment blank
918 (defun octave-skip-comment-forward (limit)
919 (let ((ppss (syntax-ppss)))
920 (if (nth 4 ppss)
921 (goto-char (nth 8 ppss))
922 (goto-char (or (comment-search-forward limit t) (point)))))
923 (while (and (< (point) limit) (looking-at-p "\\s<"))
924 (forward-comment 1)))
925
926 ;;; First non-copyright comment block
927 (defun octave-function-file-comment ()
928 "Beginning and end positions of the function file comment."
929 (save-excursion
930 (goto-char (point-min))
931 ;; Copyright block: octave/libinterp/parse-tree/lex.ll around line 1634
932 (while (save-excursion
933 (when (comment-search-forward (point-max) t)
934 (when (eq (char-after) ?\{) ; case of block comment
935 (forward-char 1))
936 (skip-syntax-forward "-")
937 (let ((case-fold-search t))
938 (looking-at-p "\\(?:copyright\\|author\\)\\_>"))))
939 (octave-skip-comment-forward (point-max)))
940 (let ((beg (comment-search-forward (point-max) t)))
941 (when beg
942 (goto-char beg)
943 (octave-skip-comment-forward (point-max))
944 (list beg (point))))))
945
946 (defun octave-sync-function-file-names ()
947 "Ensure function name agree with function file name.
948 See Info node `(octave)Function Files'."
949 (interactive)
950 (when buffer-file-name
951 (pcase-let ((`(,start ,_end ,name-start ,name-end)
952 (octave-function-file-p)))
953 (when (and start name-start)
954 (let* ((func (buffer-substring name-start name-end))
955 (file (file-name-sans-extension
956 (file-name-nondirectory buffer-file-name)))
957 (help-form (format "\
958 a: Use function name `%s'
959 b: Use file name `%s'
960 q: Don't fix\n" func file))
961 (c (unless (equal file func)
962 (save-window-excursion
963 (help-form-show)
964 (read-char-choice
965 "Which name to use? (a/b/q) " '(?a ?b ?q))))))
966 (pcase c
967 (`?a (let ((newname (expand-file-name
968 (concat func (file-name-extension
969 buffer-file-name t)))))
970 (when (or (not (file-exists-p newname))
971 (yes-or-no-p
972 (format "Target file %s exists; proceed? " newname)))
973 (when (file-exists-p buffer-file-name)
974 (rename-file buffer-file-name newname t))
975 (set-visited-file-name newname))))
976 (`?b (save-excursion
977 (goto-char name-start)
978 (delete-region name-start name-end)
979 (insert file)))))))))
980
981 (defun octave-update-function-file-comment (beg end)
982 "Query replace function names in function file comment."
983 (interactive
984 (progn
985 (barf-if-buffer-read-only)
986 (if (use-region-p)
987 (list (region-beginning) (region-end))
988 (or (octave-function-file-comment)
989 (error "No function file comment found")))))
990 (save-excursion
991 (let* ((bounds (or (octave-function-file-p)
992 (error "Not in a function file buffer")))
993 (func (if (cddr bounds)
994 (apply #'buffer-substring (cddr bounds))
995 (error "Function name not found")))
996 (old-func (progn
997 (goto-char beg)
998 (when (re-search-forward
999 "[=}]\\s-*\\(\\(?:\\sw\\|\\s_\\)+\\)\\_>"
1000 (min (line-end-position 4) end)
1001 t)
1002 (match-string 1))))
1003 (old-func (read-string (format (if old-func
1004 "Name to replace (default %s): "
1005 "Name to replace: ")
1006 old-func)
1007 nil nil old-func)))
1008 (if (and func old-func (not (equal func old-func)))
1009 (perform-replace old-func func 'query
1010 nil 'delimited nil nil beg end)
1011 (message "Function names match")))))
1012
1013 (defface octave-function-comment-block
1014 '((t (:inherit font-lock-doc-face)))
1015 "Face used to highlight function comment block."
1016 :group 'octave)
1017
1018 (eval-when-compile (require 'texinfo))
1019
1020 (defun octave-font-lock-texinfo-comment ()
1021 (let ((kws
1022 (eval-when-compile
1023 (delq nil (mapcar
1024 (lambda (kw)
1025 (if (numberp (nth 1 kw))
1026 `(,(nth 0 kw) ,(nth 1 kw) ,(nth 2 kw) prepend)
1027 (message "Ignoring Texinfo highlight: %S" kw)))
1028 texinfo-font-lock-keywords)))))
1029 (font-lock-add-keywords
1030 nil
1031 `((,(lambda (limit)
1032 (while (and (search-forward "-*- texinfo -*-" limit t)
1033 (octave-in-comment-p))
1034 (let ((beg (nth 8 (syntax-ppss)))
1035 (end (progn
1036 (octave-skip-comment-forward (point-max))
1037 (point))))
1038 (put-text-property beg end 'font-lock-multiline t)
1039 (font-lock-prepend-text-property
1040 beg end 'face 'octave-function-comment-block)
1041 (dolist (kw kws)
1042 (goto-char beg)
1043 (while (re-search-forward (car kw) end 'move)
1044 (font-lock-apply-highlight (cdr kw))))))
1045 nil)))
1046 'append)))
1047
1048 \f
1049 ;;; Indentation
1050
1051 (defun octave-indent-new-comment-line ()
1052 "Break Octave line at point, continuing comment if within one.
1053 If within code, insert `octave-continuation-string' before breaking the
1054 line. If within a string, signal an error.
1055 The new line is properly indented."
1056 (interactive)
1057 (delete-horizontal-space)
1058 (cond
1059 ((octave-in-comment-p)
1060 (indent-new-comment-line))
1061 ((octave-in-string-p)
1062 (error "Cannot split a code line inside a string"))
1063 (t
1064 (insert (concat " " octave-continuation-string))
1065 (reindent-then-newline-and-indent))))
1066
1067 (defun octave-indent-defun ()
1068 "Properly indent the Octave function which contains point."
1069 (interactive)
1070 (save-excursion
1071 (mark-defun)
1072 (message "Indenting function...")
1073 (indent-region (point) (mark) nil))
1074 (message "Indenting function...done."))
1075
1076 \f
1077 ;;; Motion
1078 (defun octave-next-code-line (&optional arg)
1079 "Move ARG lines of Octave code forward (backward if ARG is negative).
1080 Skips past all empty and comment lines. Default for ARG is 1.
1081
1082 On success, return 0. Otherwise, go as far as possible and return -1."
1083 (interactive "p")
1084 (or arg (setq arg 1))
1085 (beginning-of-line)
1086 (let ((n 0)
1087 (inc (if (> arg 0) 1 -1)))
1088 (while (and (/= arg 0) (= n 0))
1089 (setq n (forward-line inc))
1090 (while (and (= n 0)
1091 (looking-at "\\s-*\\($\\|\\s<\\)"))
1092 (setq n (forward-line inc)))
1093 (setq arg (- arg inc)))
1094 n))
1095
1096 (defun octave-previous-code-line (&optional arg)
1097 "Move ARG lines of Octave code backward (forward if ARG is negative).
1098 Skips past all empty and comment lines. Default for ARG is 1.
1099
1100 On success, return 0. Otherwise, go as far as possible and return -1."
1101 (interactive "p")
1102 (or arg (setq arg 1))
1103 (octave-next-code-line (- arg)))
1104
1105 (defun octave-beginning-of-line ()
1106 "Move point to beginning of current Octave line.
1107 If on an empty or comment line, go to the beginning of that line.
1108 Otherwise, move backward to the beginning of the first Octave code line
1109 which is not inside a continuation statement, i.e., which does not
1110 follow a code line ending in `...' or `\\', or is inside an open
1111 parenthesis list."
1112 (interactive)
1113 (beginning-of-line)
1114 (if (not (looking-at "\\s-*\\($\\|\\s<\\)"))
1115 (while (or (condition-case nil
1116 (progn
1117 (up-list -1)
1118 (beginning-of-line)
1119 t)
1120 (error nil))
1121 (and (or (looking-at "\\s-*\\($\\|\\s<\\)")
1122 (save-excursion
1123 (if (zerop (octave-previous-code-line))
1124 (looking-at octave-continuation-regexp))))
1125 (zerop (forward-line -1)))))))
1126
1127 (defun octave-end-of-line ()
1128 "Move point to end of current Octave line.
1129 If on an empty or comment line, go to the end of that line.
1130 Otherwise, move forward to the end of the first Octave code line which
1131 does not end in `...' or `\\' or is inside an open parenthesis list."
1132 (interactive)
1133 (end-of-line)
1134 (if (save-excursion
1135 (beginning-of-line)
1136 (looking-at "\\s-*\\($\\|\\s<\\)"))
1137 ()
1138 (while (or (condition-case nil
1139 (progn
1140 (up-list 1)
1141 (end-of-line)
1142 t)
1143 (error nil))
1144 (and (save-excursion
1145 (beginning-of-line)
1146 (or (looking-at "\\s-*\\($\\|\\s<\\)")
1147 (looking-at octave-continuation-regexp)))
1148 (zerop (forward-line 1)))))
1149 (end-of-line)))
1150
1151 (defun octave-mark-block ()
1152 "Put point at the beginning of this Octave block, mark at the end.
1153 The block marked is the one that contains point or follows point."
1154 (interactive)
1155 (if (and (looking-at "\\sw\\|\\s_")
1156 (looking-back "\\sw\\|\\s_" (1- (point))))
1157 (skip-syntax-forward "w_"))
1158 (unless (or (looking-at "\\s(")
1159 (save-excursion
1160 (let* ((token (funcall smie-forward-token-function))
1161 (level (assoc token smie-grammar)))
1162 (and level (not (numberp (cadr level)))))))
1163 (backward-up-list 1))
1164 (mark-sexp))
1165
1166 (defun octave-beginning-of-defun (&optional arg)
1167 "Octave-specific `beginning-of-defun-function' (which see)."
1168 (or arg (setq arg 1))
1169 ;; Move out of strings or comments.
1170 (when (octave-in-string-or-comment-p)
1171 (goto-char (octave-in-string-or-comment-p)))
1172 (letrec ((orig (point))
1173 (toplevel (lambda (pos)
1174 (condition-case nil
1175 (progn
1176 (backward-up-list 1)
1177 (funcall toplevel (point)))
1178 (scan-error pos)))))
1179 (goto-char (funcall toplevel (point)))
1180 (when (and (> arg 0) (/= orig (point)))
1181 (setq arg (1- arg)))
1182 (forward-sexp (- arg))
1183 (/= orig (point))))
1184
1185 \f
1186 ;;; Filling
1187 (defun octave-auto-fill ()
1188 "Perform auto-fill in Octave mode.
1189 Returns nil if no feasible place to break the line could be found, and t
1190 otherwise."
1191 (let (fc give-up)
1192 (if (or (null (setq fc (current-fill-column)))
1193 (save-excursion
1194 (beginning-of-line)
1195 (and auto-fill-inhibit-regexp
1196 (octave-looking-at-kw auto-fill-inhibit-regexp))))
1197 nil ; Can't do anything
1198 (if (and (not (octave-in-comment-p))
1199 (> (current-column) fc))
1200 (setq fc (- fc (+ (length octave-continuation-string) 1))))
1201 (while (and (not give-up) (> (current-column) fc))
1202 (let* ((opoint (point))
1203 (fpoint
1204 (save-excursion
1205 (move-to-column (+ fc 1))
1206 (skip-chars-backward "^ \t\n")
1207 ;; If we're at the beginning of the line, break after
1208 ;; the first word
1209 (if (bolp)
1210 (re-search-forward "[ \t]" opoint t))
1211 ;; If we're in a comment line, don't break after the
1212 ;; comment chars
1213 (if (save-excursion
1214 (skip-syntax-backward " <")
1215 (bolp))
1216 (re-search-forward "[ \t]" (line-end-position)
1217 'move))
1218 ;; If we're not in a comment line and just ahead the
1219 ;; continuation string, don't break here.
1220 (if (and (not (octave-in-comment-p))
1221 (looking-at
1222 (concat "\\s-*"
1223 (regexp-quote
1224 octave-continuation-string)
1225 "\\s-*$")))
1226 (end-of-line))
1227 (skip-chars-backward " \t")
1228 (point))))
1229 (if (save-excursion
1230 (goto-char fpoint)
1231 (not (or (bolp) (eolp))))
1232 (let ((prev-column (current-column)))
1233 (if (save-excursion
1234 (skip-chars-backward " \t")
1235 (= (point) fpoint))
1236 (progn
1237 (octave-maybe-insert-continuation-string)
1238 (indent-new-comment-line t))
1239 (save-excursion
1240 (goto-char fpoint)
1241 (octave-maybe-insert-continuation-string)
1242 (indent-new-comment-line t)))
1243 (if (>= (current-column) prev-column)
1244 (setq give-up t)))
1245 (setq give-up t))))
1246 (not give-up))))
1247
1248 (defun octave-fill-paragraph (&optional _arg)
1249 "Fill paragraph of Octave code, handling Octave comments."
1250 ;; FIXME: difference with generic fill-paragraph:
1251 ;; - code lines are only split, never joined.
1252 ;; - \n that end comments are never removed.
1253 ;; - insert continuation marker when splitting code lines.
1254 (interactive "P")
1255 (save-excursion
1256 (let ((end (progn (forward-paragraph) (copy-marker (point) t)))
1257 (beg (progn
1258 (forward-paragraph -1)
1259 (skip-chars-forward " \t\n")
1260 (beginning-of-line)
1261 (point)))
1262 (cfc (current-fill-column))
1263 comment-prefix)
1264 (goto-char beg)
1265 (while (< (point) end)
1266 (condition-case nil
1267 (indent-according-to-mode)
1268 (error nil))
1269 (move-to-column cfc)
1270 ;; First check whether we need to combine non-empty comment lines
1271 (if (and (< (current-column) cfc)
1272 (octave-in-comment-p)
1273 (not (save-excursion
1274 (beginning-of-line)
1275 (looking-at "^\\s-*\\s<+\\s-*$"))))
1276 ;; This is a nonempty comment line which does not extend
1277 ;; past the fill column. If it is followed by a nonempty
1278 ;; comment line with the same comment prefix, try to
1279 ;; combine them, and repeat this until either we reach the
1280 ;; fill-column or there is nothing more to combine.
1281 (progn
1282 ;; Get the comment prefix
1283 (save-excursion
1284 (beginning-of-line)
1285 (while (and (re-search-forward "\\s<+")
1286 (not (octave-in-comment-p))))
1287 (setq comment-prefix (match-string 0)))
1288 ;; And keep combining ...
1289 (while (and (< (current-column) cfc)
1290 (save-excursion
1291 (forward-line 1)
1292 (and (looking-at
1293 (concat "^\\s-*"
1294 comment-prefix
1295 "\\S<"))
1296 (not (looking-at
1297 (concat "^\\s-*"
1298 comment-prefix
1299 "\\s-*$"))))))
1300 (delete-char 1)
1301 (re-search-forward comment-prefix)
1302 (delete-region (match-beginning 0) (match-end 0))
1303 (fixup-whitespace)
1304 (move-to-column cfc))))
1305 ;; We might also try to combine continued code lines> Perhaps
1306 ;; some other time ...
1307 (skip-chars-forward "^ \t\n")
1308 (delete-horizontal-space)
1309 (if (or (< (current-column) cfc)
1310 (and (= (current-column) cfc) (eolp)))
1311 (forward-line 1)
1312 (if (not (eolp)) (insert " "))
1313 (or (octave-auto-fill)
1314 (forward-line 1))))
1315 t)))
1316
1317 \f
1318 ;;; Completions
1319
1320 (defun octave-completion-at-point ()
1321 "Find the text to complete and the corresponding table."
1322 (let* ((beg (save-excursion (skip-syntax-backward "w_") (point)))
1323 (end (point)))
1324 (if (< beg (point))
1325 ;; Extend region past point, if applicable.
1326 (save-excursion (skip-syntax-forward "w_")
1327 (setq end (point))))
1328 (when (> end beg)
1329 (list beg end (or (and inferior-octave-process
1330 (process-live-p inferior-octave-process)
1331 inferior-octave-completion-table)
1332 octave-reserved-words)))))
1333
1334 (define-obsolete-function-alias 'octave-complete-symbol
1335 'completion-at-point "24.1")
1336 \f
1337 ;;; Electric characters && friends
1338 (define-skeleton octave-insert-defun
1339 "Insert an Octave function skeleton.
1340 Prompt for the function's name, arguments and return values (to be
1341 entered without parens)."
1342 (let* ((defname (file-name-sans-extension (buffer-name)))
1343 (name (read-string (format "Function name (default %s): " defname)
1344 nil nil defname))
1345 (args (read-string "Arguments: "))
1346 (vals (read-string "Return values: ")))
1347 (format "%s%s (%s)"
1348 (cond
1349 ((string-equal vals "") vals)
1350 ((string-match "[ ,]" vals) (concat "[" vals "] = "))
1351 (t (concat vals " = ")))
1352 name
1353 args))
1354 \n octave-block-comment-start "usage: " str \n
1355 octave-block-comment-start '(delete-horizontal-space) \n
1356 octave-block-comment-start '(delete-horizontal-space) \n
1357 "function " > str \n
1358 _ \n
1359 "endfunction" > \n)
1360 \f
1361 ;;; Communication with the inferior Octave process
1362 (defun octave-kill-process ()
1363 "Kill inferior Octave process and its buffer."
1364 (interactive)
1365 (if inferior-octave-process
1366 (progn
1367 (process-send-string inferior-octave-process "quit;\n")
1368 (accept-process-output inferior-octave-process)))
1369 (if inferior-octave-buffer
1370 (kill-buffer inferior-octave-buffer)))
1371
1372 (defun octave-show-process-buffer ()
1373 "Make sure that `inferior-octave-buffer' is displayed."
1374 (interactive)
1375 (if (get-buffer inferior-octave-buffer)
1376 (display-buffer inferior-octave-buffer)
1377 (message "No buffer named %s" inferior-octave-buffer)))
1378
1379 (defun octave-hide-process-buffer ()
1380 "Delete all windows that display `inferior-octave-buffer'."
1381 (interactive)
1382 (if (get-buffer inferior-octave-buffer)
1383 (delete-windows-on inferior-octave-buffer)
1384 (message "No buffer named %s" inferior-octave-buffer)))
1385
1386 (defun octave-send-region (beg end)
1387 "Send current region to the inferior Octave process."
1388 (interactive "r")
1389 (inferior-octave t)
1390 (let ((proc inferior-octave-process)
1391 (string (buffer-substring-no-properties beg end))
1392 line)
1393 (with-current-buffer inferior-octave-buffer
1394 (setq inferior-octave-output-list nil)
1395 (while (not (string-equal string ""))
1396 (if (string-match "\n" string)
1397 (setq line (substring string 0 (match-beginning 0))
1398 string (substring string (match-end 0)))
1399 (setq line string string ""))
1400 (setq inferior-octave-receive-in-progress t)
1401 (inferior-octave-send-list-and-digest (list (concat line "\n")))
1402 (while inferior-octave-receive-in-progress
1403 (accept-process-output proc))
1404 (insert-before-markers
1405 (mapconcat 'identity
1406 (append
1407 (if octave-send-echo-input (list line) (list ""))
1408 inferior-octave-output-list
1409 (list inferior-octave-output-string))
1410 "\n")))))
1411 (if octave-send-show-buffer
1412 (display-buffer inferior-octave-buffer)))
1413
1414 (defun octave-send-block ()
1415 "Send current Octave block to the inferior Octave process."
1416 (interactive)
1417 (save-excursion
1418 (octave-mark-block)
1419 (octave-send-region (point) (mark))))
1420
1421 (defun octave-send-defun ()
1422 "Send current Octave function to the inferior Octave process."
1423 (interactive)
1424 (save-excursion
1425 (mark-defun)
1426 (octave-send-region (point) (mark))))
1427
1428 (defun octave-send-line (&optional arg)
1429 "Send current Octave code line to the inferior Octave process.
1430 With positive prefix ARG, send that many lines.
1431 If `octave-send-line-auto-forward' is non-nil, go to the next unsent
1432 code line."
1433 (interactive "P")
1434 (or arg (setq arg 1))
1435 (if (> arg 0)
1436 (let (beg end)
1437 (beginning-of-line)
1438 (setq beg (point))
1439 (octave-next-code-line (- arg 1))
1440 (end-of-line)
1441 (setq end (point))
1442 (if octave-send-line-auto-forward
1443 (octave-next-code-line 1))
1444 (octave-send-region beg end))))
1445
1446 (defun octave-eval-print-last-sexp ()
1447 "Evaluate Octave sexp before point and print value into current buffer."
1448 (interactive)
1449 (inferior-octave t)
1450 (let ((standard-output (current-buffer))
1451 (print-escape-newlines nil)
1452 (opoint (point)))
1453 (terpri)
1454 (prin1
1455 (save-excursion
1456 (forward-sexp -1)
1457 (inferior-octave-send-list-and-digest
1458 (list (concat (buffer-substring-no-properties (point) opoint)
1459 "\n")))
1460 (mapconcat 'identity inferior-octave-output-list "\n")))
1461 (terpri)))
1462
1463 \f
1464
1465 (defcustom octave-help-buffer "*Octave Help*"
1466 "Buffer name for `octave-help'."
1467 :type 'string
1468 :group 'octave
1469 :version "24.4")
1470
1471 (define-button-type 'octave-help-file
1472 'follow-link t
1473 'action #'help-button-action
1474 'help-function 'octave-find-definition)
1475
1476 (define-button-type 'octave-help-function
1477 'follow-link t
1478 'action (lambda (b)
1479 (octave-help
1480 (buffer-substring (button-start b) (button-end b)))))
1481
1482 (defvar help-xref-following)
1483
1484 (defun octave-help (fn)
1485 "Display the documentation of FN."
1486 (interactive (list (octave-completing-read)))
1487 (inferior-octave-send-list-and-digest
1488 (list (format "help \"%s\"\n" fn)))
1489 (let ((lines inferior-octave-output-list))
1490 (when (string-match "error: \\(.*\\)$" (car lines))
1491 (error "%s" (match-string 1 (car lines))))
1492 (with-help-window octave-help-buffer
1493 (princ (mapconcat 'identity lines "\n"))
1494 (with-current-buffer octave-help-buffer
1495 ;; Bound to t so that `help-buffer' returns current buffer for
1496 ;; `help-setup-xref'.
1497 (let ((help-xref-following t))
1498 (help-setup-xref (list 'octave-help fn)
1499 (called-interactively-p 'interactive)))
1500 (setq-local info-lookup-mode 'octave-mode)
1501 ;; Note: can be turned off by suppress_verbose_help_message.
1502 ;;
1503 ;; Remove boring trailing text: Additional help for built-in functions
1504 ;; and operators ...
1505 (goto-char (point-max))
1506 (when (search-backward "\n\n\n" nil t)
1507 (goto-char (match-beginning 0))
1508 (delete-region (point) (point-max)))
1509 ;; File name highlight
1510 (goto-char (point-min))
1511 (when (re-search-forward "from the file \\(.*\\)$"
1512 (line-end-position)
1513 t)
1514 (let ((file (match-string 1)))
1515 (replace-match "" nil nil nil 1)
1516 (insert "`")
1517 (help-insert-xref-button (file-name-nondirectory file)
1518 'octave-help-file fn)
1519 (insert "'")))
1520 ;; Make 'See also' clickable
1521 (with-syntax-table octave-mode-syntax-table
1522 (when (re-search-forward "^\\s-*See also:" nil t)
1523 (while (re-search-forward "\\_<\\(?:\\sw\\|\\s_\\)+\\_>" nil t)
1524 (make-text-button (match-beginning 0)
1525 (match-end 0)
1526 :type 'octave-help-function))))))))
1527
1528 (defcustom octave-binary-file-extensions '("oct" "mex")
1529 "A list of binary file extensions for Octave."
1530 :type '(repeat string)
1531 :group 'octave
1532 :version "24.4")
1533
1534 (defvar find-tag-marker-ring)
1535
1536 (defun octave-find-definition (fn)
1537 "Find the definition of FN."
1538 (interactive (list (octave-completing-read)))
1539 (inferior-octave-send-list-and-digest
1540 ;; help NAME is more verbose
1541 (list (format "\
1542 if iskeyword(\"%s\") disp(\"`%s' is a keyword\") else which(\"%s\") endif\n"
1543 fn fn fn)))
1544 (let* ((line (car inferior-octave-output-list))
1545 (file (when (and line (string-match "from the file \\(.*\\)$" line))
1546 (match-string 1 line))))
1547 (if (not file)
1548 (user-error "%s" (or line (format "`%s' not found" fn)))
1549 (when (and (member (file-name-extension file)
1550 octave-binary-file-extensions)
1551 (not (yes-or-no-p (format "File `%s' may be binary; open? "
1552 (file-name-nondirectory file)))))
1553 (error "Aborted"))
1554 (require 'etags)
1555 (ring-insert find-tag-marker-ring (point-marker))
1556 (find-file file)
1557 (octave-goto-function-definition))))
1558
1559
1560 (provide 'octave)
1561 ;;; octave.el ends here