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