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