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