1 ;;; octave.el --- editing octave source files under emacs -*- lexical-binding: t; -*-
3 ;; Copyright (C) 1997, 2001-2014 Free Software Foundation, Inc.
5 ;; Author: Kurt Hornik <Kurt.Hornik@wu-wien.ac.at>
6 ;; John Eaton <jwe@octave.org>
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/>.
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.
40 (unless (fboundp 'user-error
)
41 (defalias 'user-error
'error
))
42 (unless (fboundp 'delete-consecutive-dups
)
43 (defalias 'delete-consecutive-dups
'delete-dups
)))
45 (unless (fboundp 'setq-local
)
46 (defmacro setq-local
(var val
)
47 "Set variable VAR to value VAL in current buffer."
48 (list 'set
(list 'make-local-variable
(list 'quote var
)) val
))))
51 "Editing Octave code."
52 :link
'(custom-manual "(octave-mode)Top")
53 :link
'(url-link "http://www.gnu.org/s/octave")
54 :link
'(custom-group-link :tag
"Font Lock Faces group" font-lock-faces
)
57 (define-obsolete-function-alias 'octave-submit-bug-report
58 'report-emacs-bug
"24.4")
60 (define-abbrev-table 'octave-abbrev-table nil
61 "Abbrev table for Octave's reserved words.
62 Used in `octave-mode' and `inferior-octave-mode' buffers.")
64 (defvar octave-comment-char ?
#
65 "Character to start an Octave comment.")
67 (defvar octave-comment-start
(char-to-string octave-comment-char
)
68 "Octave-specific `comment-start' (which see).")
70 (defvar octave-comment-start-skip
"\\(^\\|\\S<\\)\\(?:%!\\|\\s<+\\)\\s-*"
71 "Octave-specific `comment-start-skip' (which see).")
73 (defvar octave-begin-keywords
74 '("classdef" "do" "enumeration" "events" "for" "function" "if" "methods"
75 "parfor" "properties" "switch" "try" "unwind_protect" "while"))
77 (defvar octave-else-keywords
78 '("case" "catch" "else" "elseif" "otherwise" "unwind_protect_cleanup"))
80 (defvar octave-end-keywords
81 '("endclassdef" "endenumeration" "endevents" "endfor" "endfunction" "endif"
82 "endmethods" "endparfor" "endproperties" "endswitch" "end_try_catch"
83 "end_unwind_protect" "endwhile" "until" "end"))
85 (defvar octave-reserved-words
86 (append octave-begin-keywords
89 '("break" "continue" "global" "persistent" "return"))
90 "Reserved words in Octave.")
92 (defvar octave-function-header-regexp
93 (concat "^\\s-*\\_<\\(function\\)\\_>"
94 "\\([^=;(\n]*=[ \t]*\\|[ \t]*\\)\\(\\(?:\\w\\|\\s_\\)+\\)\\_>")
95 "Regexp to match an Octave function header.
96 The string `function' and its name are given by the first and third
97 parenthetical grouping.")
100 (defvar octave-mode-map
101 (let ((map (make-sparse-keymap)))
102 (define-key map
"\M-." 'octave-find-definition
)
103 (define-key map
"\M-\C-j" 'octave-indent-new-comment-line
)
104 (define-key map
"\C-c\C-p" 'octave-previous-code-line
)
105 (define-key map
"\C-c\C-n" 'octave-next-code-line
)
106 (define-key map
"\C-c\C-a" 'octave-beginning-of-line
)
107 (define-key map
"\C-c\C-e" 'octave-end-of-line
)
108 (define-key map
[remap down-list
] 'smie-down-list
)
109 (define-key map
"\C-c\M-\C-h" 'octave-mark-block
)
110 (define-key map
"\C-c]" 'smie-close-block
)
111 (define-key map
"\C-c/" 'smie-close-block
)
112 (define-key map
"\C-c;" 'octave-update-function-file-comment
)
113 (define-key map
"\C-hd" 'octave-help
)
114 (define-key map
"\C-ha" 'octave-lookfor
)
115 (define-key map
"\C-c\C-l" 'octave-source-file
)
116 (define-key map
"\C-c\C-f" 'octave-insert-defun
)
117 (define-key map
"\C-c\C-il" 'octave-send-line
)
118 (define-key map
"\C-c\C-ib" 'octave-send-block
)
119 (define-key map
"\C-c\C-if" 'octave-send-defun
)
120 (define-key map
"\C-c\C-ir" 'octave-send-region
)
121 (define-key map
"\C-c\C-ia" 'octave-send-buffer
)
122 (define-key map
"\C-c\C-is" 'octave-show-process-buffer
)
123 (define-key map
"\C-c\C-iq" 'octave-hide-process-buffer
)
124 (define-key map
"\C-c\C-ik" 'octave-kill-process
)
125 (define-key map
"\C-c\C-i\C-l" 'octave-send-line
)
126 (define-key map
"\C-c\C-i\C-b" 'octave-send-block
)
127 (define-key map
"\C-c\C-i\C-f" 'octave-send-defun
)
128 (define-key map
"\C-c\C-i\C-r" 'octave-send-region
)
129 (define-key map
"\C-c\C-i\C-a" 'octave-send-buffer
)
130 (define-key map
"\C-c\C-i\C-s" 'octave-show-process-buffer
)
131 (define-key map
"\C-c\C-i\C-q" 'octave-hide-process-buffer
)
132 (define-key map
"\C-c\C-i\C-k" 'octave-kill-process
)
134 "Keymap used in Octave mode.")
138 (easy-menu-define octave-mode-menu octave-mode-map
139 "Menu for Octave mode."
141 ["Split Line at Point" octave-indent-new-comment-line t
]
142 ["Previous Code Line" octave-previous-code-line t
]
143 ["Next Code Line" octave-next-code-line t
]
144 ["Begin of Line" octave-beginning-of-line t
]
145 ["End of Line" octave-end-of-line t
]
146 ["Mark Block" octave-mark-block t
]
147 ["Close Block" smie-close-block t
]
149 ["Start Octave Process" run-octave t
]
150 ["Documentation Lookup" info-lookup-symbol t
]
151 ["Help on Function" octave-help t
]
152 ["Search help" octave-lookfor t
]
153 ["Find Function Definition" octave-find-definition t
]
154 ["Insert Function" octave-insert-defun
t]
155 ["Update Function File Comment" octave-update-function-file-comment t
]
157 ["Function Syntax Hints" (call-interactively
158 (if (fboundp 'eldoc-post-insert-mode
)
159 'eldoc-post-insert-mode
161 :style toggle
:selected
(or (bound-and-true-p eldoc-post-insert-mode
)
162 (bound-and-true-p eldoc-mode
))
163 :help
"Display function signatures after typing `SPC' or `('"]
164 ["Delimiter Matching" show-paren-mode
165 :style toggle
:selected show-paren-mode
166 :help
"Highlight matched pairs such as `if ... end'"
167 :visible
(fboundp 'smie--matching-block-data
)]
168 ["Auto Fill" auto-fill-mode
169 :style toggle
:selected auto-fill-function
170 :help
"Automatic line breaking"]
171 ["Electric Layout" electric-layout-mode
172 :style toggle
:selected electric-layout-mode
173 :help
"Automatically insert newlines around some chars"]
176 ["Send Current Line" octave-send-line t
]
177 ["Send Current Block" octave-send-block t
]
178 ["Send Current Function" octave-send-defun
t]
179 ["Send Region" octave-send-region t
]
180 ["Send Buffer" octave-send-buffer t
]
181 ["Source Current File" octave-source-file t
]
182 ["Show Process Buffer" octave-show-process-buffer t
]
183 ["Hide Process Buffer" octave-hide-process-buffer t
]
184 ["Kill Process" octave-kill-process t
])
186 ["Octave Mode Manual" (info "(octave-mode)Top") t
]
187 ["Customize Octave" (customize-group 'octave
) t
]
188 ["Submit Bug Report" report-emacs-bug t
]))
190 (defvar octave-mode-syntax-table
191 (let ((table (make-syntax-table)))
192 (modify-syntax-entry ?
\r " " table
)
193 (modify-syntax-entry ?
+ "." table
)
194 (modify-syntax-entry ?-
"." table
)
195 (modify-syntax-entry ?
= "." table
)
196 (modify-syntax-entry ?
* "." table
)
197 (modify-syntax-entry ?
/ "." table
)
198 (modify-syntax-entry ?
> "." table
)
199 (modify-syntax-entry ?
< "." table
)
200 (modify-syntax-entry ?
& "." table
)
201 (modify-syntax-entry ?|
"." table
)
202 (modify-syntax-entry ?
! "." table
)
203 (modify-syntax-entry ?
\\ "." table
)
204 (modify-syntax-entry ?
\' "." table
)
205 (modify-syntax-entry ?\
` "." table
)
206 (modify-syntax-entry ?.
"." table
)
207 (modify-syntax-entry ?
\" "\"" table
)
208 (modify-syntax-entry ?_
"_" table
)
209 ;; The "b" flag only applies to the second letter of the comstart
210 ;; and the first letter of the comend, i.e. the "4b" below is ineffective.
211 ;; If we try to put `b' on the single-line comments, we get a similar
212 ;; problem where the % and # chars appear as first chars of the 2-char
213 ;; comend, so the multi-line ender is also turned into style-b.
214 ;; So we need the new "c" comment style.
215 (modify-syntax-entry ?\%
"< 13" table
)
216 (modify-syntax-entry ?\
# "< 13" table
)
217 (modify-syntax-entry ?\
{ "(} 2c" table
)
218 (modify-syntax-entry ?\
} "){ 4c" table
)
219 (modify-syntax-entry ?
\n ">" table
)
221 "Syntax table in use in `octave-mode' buffers.")
223 (defcustom octave-font-lock-texinfo-comment t
224 "Control whether to highlight the texinfo comment block."
229 (defcustom octave-blink-matching-block t
230 "Control the blinking of matching Octave block keywords.
231 Non-nil means show matching begin of block when inserting a space,
232 newline or semicolon after an else or end keyword."
236 (defcustom octave-block-offset
2
237 "Extra indentation applied to statements in Octave block structures."
241 (defvar octave-block-comment-start
242 (concat (make-string 2 octave-comment-char
) " ")
243 "String to insert to start a new Octave comment on an empty line.")
245 (defcustom octave-continuation-offset
4
246 "Extra indentation applied to Octave continuation lines."
251 (defconst octave-continuation-marker-regexp
"\\\\\\|\\.\\.\\."))
253 (defvar octave-continuation-regexp
254 (concat "[^#%\n]*\\(" octave-continuation-marker-regexp
255 "\\)\\s-*\\(\\s<.*\\)?$"))
257 ;; Char \ is considered a bad decision for continuing a line.
258 (defconst octave-continuation-string
"..."
259 "Character string used for Octave continuation lines.")
261 (defvar octave-mode-imenu-generic-expression
264 (list nil octave-function-header-regexp
3))
265 "Imenu expression for Octave mode. See `imenu-generic-expression'.")
267 (defcustom octave-mode-hook nil
268 "Hook to be run when Octave mode is started."
272 (defcustom octave-send-show-buffer t
273 "Non-nil means display `inferior-octave-buffer' after sending to it."
277 (defcustom octave-send-line-auto-forward t
278 "Control auto-forward after sending to the inferior Octave process.
279 Non-nil means always go to the next Octave code line after sending."
283 (defcustom octave-send-echo-input t
284 "Non-nil means echo input sent to the inferior Octave process."
293 ;; Use '__operators__' in Octave REPL to get a full list.
294 (defconst octave-operator-table
295 '((assoc ";" "\n") (assoc ",") ; The doc claims they have equal precedence!?
296 (right "=" "+=" "-=" "*=" "/=")
297 (assoc "&&") (assoc "||") ; The doc claims they have equal precedence!?
298 (assoc "&") (assoc "|") ; The doc claims they have equal precedence!?
299 (nonassoc "<" "<=" "==" ">=" ">" "!=" "~=")
300 (nonassoc ":") ;No idea what this is.
302 (assoc "*" "/" "\\" ".\\" ".*" "./")
304 (nonassoc "++" "--" "!" "~") ;And unary "+" and "-".
305 (right "^" "**" ".^" ".**")
306 ;; It's not really an operator, but for indentation purposes it
307 ;; could be convenient to treat it as one.
310 (defconst octave-smie-bnf-table
312 ;; We can't distinguish the first element in a sequence with
313 ;; precedence grammars, so we can't distinguish the condition
314 ;; if the `if' from the subsequent body, for example.
315 ;; This has to be done later in the indentation rules.
317 ;; We need to mention at least one of the operators in this part
318 ;; of the grammar: if the BNF and the operator table have
319 ;; no overlap, SMIE can't know how they relate.
321 ("try" exp
"catch" exp
"end_try_catch")
322 ("try" exp
"catch" exp
"end")
323 ("unwind_protect" exp
324 "unwind_protect_cleanup" exp
"end_unwind_protect")
325 ("unwind_protect" exp
"unwind_protect_cleanup" exp
"end")
328 ("parfor" exp
"endparfor")
330 ("do" exp
"until" atom
)
331 ("while" exp
"endwhile")
334 ("if" exp
"else" exp
"endif")
335 ("if" exp
"elseif" exp
"else" exp
"endif")
336 ("if" exp
"elseif" exp
"elseif" exp
"else" exp
"endif")
337 ("if" exp
"elseif" exp
"elseif" exp
"else" exp
"end")
338 ("switch" exp
"case" exp
"endswitch")
339 ("switch" exp
"case" exp
"otherwise" exp
"endswitch")
340 ("switch" exp
"case" exp
"case" exp
"otherwise" exp
"endswitch")
341 ("switch" exp
"case" exp
"case" exp
"otherwise" exp
"end")
342 ("function" exp
"endfunction")
343 ("function" exp
"end")
344 ("enumeration" exp
"endenumeration")
345 ("enumeration" exp
"end")
346 ("events" exp
"endevents")
348 ("methods" exp
"endmethods")
349 ("methods" exp
"end")
350 ("properties" exp
"endproperties")
351 ("properties" exp
"end")
352 ("classdef" exp
"endclassdef")
353 ("classdef" exp
"end"))
354 ;; (fundesc (atom "=" atom))
357 (defconst octave-smie-grammar
360 (smie-bnf->prec2 octave-smie-bnf-table
363 (smie-precs->prec2 octave-operator-table
))))
365 ;; Tokenizing needs to be refined so that ";;" is treated as two
366 ;; tokens and also so as to recognize the \n separator (and
367 ;; corresponding continuation lines).
369 (defconst octave-operator-regexp
370 (regexp-opt (remove "\n" (apply 'append
371 (mapcar 'cdr octave-operator-table
)))))
373 (defun octave-smie-backward-token ()
375 (forward-comment (- (point)))
377 ((and (not (eq (char-before) ?\
;)) ;Coalesce ";" and "\n".
378 (> pos
(line-end-position))
379 (if (looking-back octave-continuation-marker-regexp
(- (point) 3))
381 (goto-char (match-beginning 0))
382 (forward-comment (- (point)))
385 ;; Ignore it if it's within parentheses.
386 (let ((ppss (syntax-ppss)))
387 (not (and (nth 1 ppss
)
388 (eq ?\
( (char-after (nth 1 ppss
)))))))
389 (skip-chars-forward " \t")
390 ;; Why bother distinguishing \n and ;?
392 ((and (looking-back octave-operator-regexp
(- (point) 3) 'greedy
)
393 ;; Don't mistake a string quote for a transpose.
394 (not (looking-back "\\s\"" (1- (point)))))
395 (goto-char (match-beginning 0))
396 (match-string-no-properties 0))
398 (smie-default-backward-token)))))
400 (defun octave-smie-forward-token ()
401 (skip-chars-forward " \t")
402 (when (looking-at (eval-when-compile
403 (concat "\\(" octave-continuation-marker-regexp
404 "\\)[ \t]*\\($\\|[%#]\\)")))
405 (goto-char (match-end 1))
408 ((and (looking-at "[%#\n]")
409 (not (or (save-excursion (skip-chars-backward " \t")
410 ;; Only add implicit ; when needed.
411 (or (bolp) (eq (char-before) ?\
;)))
412 ;; Ignore it if it's within parentheses.
413 (let ((ppss (syntax-ppss)))
415 (eq ?\
( (char-after (nth 1 ppss
))))))))
416 (if (eolp) (forward-char 1) (forward-comment 1))
417 ;; Why bother distinguishing \n and ;?
419 ((progn (forward-comment (point-max)) nil
))
420 ((looking-at ";[ \t]*\\($\\|[%#]\\)")
421 ;; Combine the ; with the subsequent \n.
422 (goto-char (match-beginning 1))
425 ((and (looking-at octave-operator-regexp
)
426 ;; Don't mistake a string quote for a transpose.
427 (not (looking-at "\\s\"")))
428 (goto-char (match-end 0))
429 (match-string-no-properties 0))
431 (smie-default-forward-token))))
433 (defun octave-smie-rules (kind token
)
434 (pcase (cons kind token
)
435 ;; We could set smie-indent-basic instead, but that would have two
437 ;; - changes to octave-block-offset wouldn't take effect immediately.
438 ;; - edebug wouldn't show the use of this variable.
439 (`(:elem . basic
) octave-block-offset
)
440 ;; Since "case" is in the same BNF rules as switch..end, SMIE by default
441 ;; aligns it with "switch".
442 (`(:before .
"case") (if (not (smie-rule-sibling-p)) octave-block-offset
))
444 (if (smie-rule-parent-p "classdef" "events" "enumeration" "function" "if"
445 "while" "else" "elseif" "for" "parfor"
446 "properties" "methods" "otherwise" "case"
447 "try" "catch" "unwind_protect"
448 "unwind_protect_cleanup")
449 (smie-rule-parent octave-block-offset
)
450 ;; For (invalid) code between switch and case.
451 ;; (if (smie-rule-parent-p "switch") 4)
454 (defun octave-indent-comment ()
455 "A function for `smie-indent-functions' (which see)."
457 (back-to-indentation)
459 ((octave-in-string-or-comment-p) nil
)
460 ((looking-at-p "\\(\\s<\\)\\1\\{2,\\}")
462 ;; Exclude %{, %} and %!.
463 ((and (looking-at-p "\\s<\\(?:[^{}!]\\|$\\)")
464 (not (looking-at-p "\\(\\s<\\)\\1")))
465 (comment-choose-indent)))))
468 (defvar octave-font-lock-keywords
470 ;; Fontify all builtin keywords.
471 (cons (concat "\\_<\\("
472 (regexp-opt octave-reserved-words
)
474 'font-lock-keyword-face
)
475 ;; Note: 'end' also serves as the last index in an indexing expression.
476 ;; Ref: http://www.mathworks.com/help/matlab/ref/end.html
477 (list (lambda (limit)
478 (while (re-search-forward "\\_<end\\_>" limit
'move
)
479 (let ((beg (match-beginning 0))
481 (unless (octave-in-string-or-comment-p)
486 (when (memq (char-after) '(?\
( ?\
[ ?\
{))
487 (put-text-property beg end
'face nil
))
489 (error (goto-char end
))))))
491 ;; Fontify all operators.
492 (cons octave-operator-regexp
'font-lock-builtin-face
)
493 ;; Fontify all function declarations.
494 (list octave-function-header-regexp
495 '(1 font-lock-keyword-face
)
496 '(3 font-lock-function-name-face nil t
)))
497 "Additional Octave expressions to highlight.")
499 (defun octave-syntax-propertize-function (start end
)
501 (octave-syntax-propertize-sqs end
)
502 (funcall (syntax-propertize-rules
503 ("\\\\" (0 (when (eq (nth 3 (save-excursion
504 (syntax-ppss (match-beginning 0))))
506 (string-to-syntax "\\"))))
507 ;; Try to distinguish the string-quotes from the transpose-quotes.
508 ("\\(?:^\\|[[({,; ]\\)\\('\\)"
509 (1 (prog1 "\"'" (octave-syntax-propertize-sqs end
)))))
512 (defun octave-syntax-propertize-sqs (end)
513 "Propertize the content/end of single-quote strings."
514 (when (eq (nth 3 (syntax-ppss)) ?
\')
516 (when (re-search-forward
517 "\\(?:\\=\\|[^']\\)\\(?:''\\)*\\('\\)\\($\\|[^']\\)" end
'move
)
518 (goto-char (match-beginning 2))
519 (when (eq (char-before (match-beginning 1)) ?
\\)
520 ;; Backslash cannot escape a single quote.
521 (put-text-property (1- (match-beginning 1)) (match-beginning 1)
522 'syntax-table
(string-to-syntax ".")))
523 (put-text-property (match-beginning 1) (match-end 1)
524 'syntax-table
(string-to-syntax "\"'")))))
526 (defvar electric-layout-rules
)
529 (define-derived-mode octave-mode prog-mode
"Octave"
530 "Major mode for editing Octave code.
532 Octave is a high-level language, primarily intended for numerical
533 computations. It provides a convenient command line interface
534 for solving linear and nonlinear problems numerically. Function
535 definitions can also be stored in files and used in batch mode.
537 See Info node `(octave-mode) Using Octave Mode' for more details.
541 :abbrev-table octave-abbrev-table
544 (smie-setup octave-smie-grammar
#'octave-smie-rules
545 :forward-token
#'octave-smie-forward-token
546 :backward-token
#'octave-smie-backward-token
)
547 (setq-local smie-indent-basic
'octave-block-offset
)
548 (add-hook 'smie-indent-functions
#'octave-indent-comment nil t
)
550 (setq-local smie-blink-matching-triggers
551 (cons ?\
; smie-blink-matching-triggers))
552 (unless octave-blink-matching-block
553 (remove-hook 'post-self-insert-hook
#'smie-blink-matching-open
'local
))
555 (setq-local electric-indent-chars
556 (cons ?\
; electric-indent-chars))
557 ;; IIUC matlab-mode takes the opposite approach: it makes RET insert
558 ;; a ";" at those places where it's correct (i.e. outside of parens).
559 (setq-local electric-layout-rules
'((?\
; . after)))
561 (setq-local comment-use-syntax t
)
562 (setq-local comment-start octave-comment-start
)
563 (setq-local comment-end
"")
564 (setq-local comment-start-skip octave-comment-start-skip
)
565 (setq-local comment-add
1)
567 (setq-local parse-sexp-ignore-comments t
)
568 (setq-local paragraph-start
(concat "\\s-*$\\|" page-delimiter
))
569 (setq-local paragraph-separate paragraph-start
)
570 (setq-local paragraph-ignore-fill-prefix t
)
571 (setq-local fill-paragraph-function
'octave-fill-paragraph
)
573 (setq-local fill-nobreak-predicate
574 (lambda () (eq (octave-in-string-p) ?
')))
576 (if (fboundp 'add-function
) ; new in 24.4
577 (add-function :around
(local 'comment-line-break-function
)
578 #'octave--indent-new-comment-line
)
579 (setq-local comment-line-break-function
580 (apply-partially #'octave--indent-new-comment-line
581 #'comment-indent-new-line
))))
583 (setq font-lock-defaults
'(octave-font-lock-keywords))
585 (setq-local syntax-propertize-function
#'octave-syntax-propertize-function
)
587 (setq-local imenu-generic-expression octave-mode-imenu-generic-expression
)
588 (setq-local imenu-case-fold-search nil
)
590 (setq-local add-log-current-defun-function
#'octave-add-log-current-defun
)
592 (add-hook 'completion-at-point-functions
'octave-completion-at-point nil t
)
593 (add-hook 'before-save-hook
'octave-sync-function-file-names nil t
)
594 (setq-local beginning-of-defun-function
'octave-beginning-of-defun
)
595 (and octave-font-lock-texinfo-comment
(octave-font-lock-texinfo-comment))
596 (setq-local eldoc-documentation-function
'octave-eldoc-function
)
598 (easy-menu-add octave-mode-menu
))
601 (defcustom inferior-octave-program
"octave"
602 "Program invoked by `inferior-octave'."
606 (defcustom inferior-octave-buffer
"*Inferior Octave*"
607 "Name of buffer for running an inferior Octave process."
611 (defcustom inferior-octave-prompt
612 ;; For Octave >= 3.8, default is always 'octave', see
613 ;; http://hg.savannah.gnu.org/hgweb/octave/rev/708173343c50
614 "\\(?:^octave\\(?:.bin\\|.exe\\)?\\(?:-[.0-9]+\\)?\\(?::[0-9]+\\)?\\|^debug\\|^\\)>+ "
615 "Regexp to match prompts for the inferior Octave process."
619 (defcustom inferior-octave-prompt-read-only comint-prompt-read-only
620 "If non-nil, the Octave prompt is read only.
621 See `comint-prompt-read-only' for details."
626 (defcustom inferior-octave-startup-file
627 (let ((n (file-name-nondirectory inferior-octave-program
)))
628 (locate-user-emacs-file (format "init_%s.m" n
) (format ".emacs-%s" n
)))
629 "Name of the inferior Octave startup file.
630 The contents of this file are sent to the inferior Octave process on
632 :type
'(choice (const :tag
"None" nil
) file
)
636 (defcustom inferior-octave-startup-args
'("-i" "--no-line-editing")
637 "List of command line arguments for the inferior Octave process.
638 For example, for suppressing the startup message and using `traditional'
639 mode, include \"-q\" and \"--traditional\"."
640 :type
'(repeat string
)
644 (defcustom inferior-octave-mode-hook nil
645 "Hook to be run when Inferior Octave mode is started."
649 (defcustom inferior-octave-error-regexp-alist
650 '(("error:\\s-*\\(.*?\\) at line \\([0-9]+\\), column \\([0-9]+\\)"
652 ("warning:\\s-*\\([^:\n]+\\):.*at line \\([0-9]+\\), column \\([0-9]+\\)"
654 "Value for `compilation-error-regexp-alist' in inferior octave."
656 :type
'(repeat (choice (symbol :tag
"Predefined symbol")
657 (sexp :tag
"Error specification")))
660 (defvar inferior-octave-compilation-font-lock-keywords
661 '(("\\_<PASS\\_>" . compilation-info-face
)
662 ("\\_<FAIL\\_>" . compilation-error-face
)
663 ("\\_<\\(warning\\):" 1 compilation-warning-face
)
664 ("\\_<\\(error\\):" 1 compilation-error-face
)
665 ("^\\s-*!!!!!.*\\|^.*failed$" . compilation-error-face
))
666 "Value for `compilation-mode-font-lock-keywords' in inferior octave.")
668 (defvar inferior-octave-process nil
)
670 (defvar inferior-octave-mode-map
671 (let ((map (make-sparse-keymap)))
672 (set-keymap-parent map comint-mode-map
)
673 (define-key map
"\M-." 'octave-find-definition
)
674 (define-key map
"\t" 'completion-at-point
)
675 (define-key map
"\C-hd" 'octave-help
)
676 (define-key map
"\C-ha" 'octave-lookfor
)
677 ;; Same as in `shell-mode'.
678 (define-key map
"\M-?" 'comint-dynamic-list-filename-completions
)
679 (define-key map
"\C-c\C-l" 'inferior-octave-dynamic-list-input-ring
)
680 (define-key map
[menu-bar inout list-history
]
681 '("List Input History" . inferior-octave-dynamic-list-input-ring
))
683 "Keymap used in Inferior Octave mode.")
685 (defvar inferior-octave-mode-syntax-table
686 (let ((table (make-syntax-table octave-mode-syntax-table
)))
688 "Syntax table in use in `inferior-octave-mode' buffers.")
690 (defvar inferior-octave-font-lock-keywords
692 (cons inferior-octave-prompt
'font-lock-type-face
))
693 ;; Could certainly do more font locking in inferior Octave ...
694 "Additional expressions to highlight in Inferior Octave mode.")
696 (defvar inferior-octave-output-list nil
)
697 (defvar inferior-octave-output-string nil
)
698 (defvar inferior-octave-receive-in-progress nil
)
700 (define-obsolete-variable-alias 'inferior-octave-startup-hook
701 'inferior-octave-mode-hook
"24.4")
703 (defvar inferior-octave-dynamic-complete-functions
704 '(inferior-octave-completion-at-point comint-filename-completion
)
705 "List of functions called to perform completion for inferior Octave.
706 This variable is used to initialize `comint-dynamic-complete-functions'
707 in the Inferior Octave buffer.")
709 (defvar info-lookup-mode
)
710 (defvar compilation-error-regexp-alist
)
711 (defvar compilation-mode-font-lock-keywords
)
713 (declare-function compilation-forget-errors
"compile" ())
715 (defun inferior-octave-process-live-p ()
716 (process-live-p inferior-octave-process
))
718 (define-derived-mode inferior-octave-mode comint-mode
"Inferior Octave"
719 "Major mode for interacting with an inferior Octave process.
721 See Info node `(octave-mode) Running Octave from Within Emacs' for more
725 \\{inferior-octave-mode-map}"
726 :abbrev-table octave-abbrev-table
729 (setq comint-prompt-regexp inferior-octave-prompt
)
731 (setq-local comment-use-syntax t
)
732 (setq-local comment-start octave-comment-start
)
733 (setq-local comment-end
"")
734 (setq comment-column
32)
735 (setq-local comment-start-skip octave-comment-start-skip
)
737 (setq font-lock-defaults
'(inferior-octave-font-lock-keywords nil nil
))
739 (setq-local info-lookup-mode
'octave-mode
)
740 (setq-local eldoc-documentation-function
'octave-eldoc-function
)
742 (setq comint-input-ring-file-name
743 (or (getenv "OCTAVE_HISTFILE") "~/.octave_hist")
744 comint-input-ring-size
(or (getenv "OCTAVE_HISTSIZE") 1024))
745 (comint-read-input-ring t
)
746 (setq-local comint-dynamic-complete-functions
747 inferior-octave-dynamic-complete-functions
)
748 (setq-local comint-prompt-read-only inferior-octave-prompt-read-only
)
749 (add-hook 'comint-input-filter-functions
750 'inferior-octave-directory-tracker nil t
)
751 ;; http://thread.gmane.org/gmane.comp.gnu.octave.general/48572
752 (add-hook 'window-configuration-change-hook
753 'inferior-octave-track-window-width-change nil t
)
754 (setq-local compilation-error-regexp-alist inferior-octave-error-regexp-alist
)
755 (setq-local compilation-mode-font-lock-keywords
756 inferior-octave-compilation-font-lock-keywords
)
757 (compilation-shell-minor-mode 1)
758 (compilation-forget-errors))
761 (defun inferior-octave (&optional arg
)
762 "Run an inferior Octave process, I/O via `inferior-octave-buffer'.
763 This buffer is put in Inferior Octave mode. See `inferior-octave-mode'.
765 Unless ARG is non-nil, switches to this buffer.
767 The elements of the list `inferior-octave-startup-args' are sent as
768 command line arguments to the inferior Octave process on startup.
770 Additional commands to be executed on startup can be provided either in
771 the file specified by `inferior-octave-startup-file' or by the default
772 startup file, `~/.emacs-octave'."
774 (let ((buffer (get-buffer-create inferior-octave-buffer
)))
776 (pop-to-buffer buffer
))
777 (unless (comint-check-proc buffer
)
778 (with-current-buffer buffer
779 (inferior-octave-startup)
780 (inferior-octave-mode)))
784 (defalias 'run-octave
'inferior-octave
)
786 (defun inferior-octave-startup ()
787 "Start an inferior Octave process."
788 (let ((proc (comint-exec-1
789 (substring inferior-octave-buffer
1 -
1)
790 inferior-octave-buffer
791 inferior-octave-program
793 inferior-octave-startup-args
794 ;; --no-gui is introduced in Octave > 3.7
795 (and (not (member "--no-gui" inferior-octave-startup-args
))
796 (zerop (process-file inferior-octave-program
797 nil nil nil
"--no-gui" "--help"))
799 (set-process-filter proc
'inferior-octave-output-digest
)
800 (setq inferior-octave-process proc
801 inferior-octave-output-list nil
802 inferior-octave-output-string nil
803 inferior-octave-receive-in-progress t
)
805 ;; This may look complicated ... However, we need to make sure that
806 ;; we additional startup code only AFTER Octave is ready (otherwise,
807 ;; output may be mixed up). Hence, we need to digest the Octave
808 ;; output to see when it issues a prompt.
809 (while inferior-octave-receive-in-progress
810 (unless (inferior-octave-process-live-p)
811 ;; Spit out the error messages.
812 (when inferior-octave-output-list
813 (princ (concat (mapconcat 'identity inferior-octave-output-list
"\n")
815 (process-mark inferior-octave-process
)))
816 (error "Process `%s' died" inferior-octave-process
))
817 (accept-process-output inferior-octave-process
))
818 (goto-char (point-max))
819 (set-marker (process-mark proc
) (point))
820 (insert-before-markers
822 (if (not (bobp)) "\f\n")
823 (if inferior-octave-output-list
825 'identity inferior-octave-output-list
"\n")
828 ;; An empty secondary prompt, as e.g. obtained by '--braindead',
830 (inferior-octave-send-list-and-digest (list "PS2\n"))
831 (when (string-match "\\(PS2\\|ans\\) = *$"
832 (car inferior-octave-output-list
))
833 (inferior-octave-send-list-and-digest (list "PS2 ('> ');\n")))
835 (inferior-octave-send-list-and-digest
836 (list "disp (getenv ('OCTAVE_SRCDIR'))\n"))
837 (process-put proc
'octave-srcdir
838 (unless (equal (car inferior-octave-output-list
) "")
839 (car inferior-octave-output-list
)))
841 ;; O.K., now we are ready for the Inferior Octave startup commands.
842 (inferior-octave-send-list-and-digest
844 (unless (equal inferior-octave-output-string
">> ")
845 ;; See http://hg.savannah.gnu.org/hgweb/octave/rev/708173343c50
846 "PS1 ('octave> ');\n")
847 (when (and inferior-octave-startup-file
848 (file-exists-p inferior-octave-startup-file
))
849 (format "source ('%s');\n" inferior-octave-startup-file
))))
850 (when inferior-octave-output-list
851 (insert-before-markers
852 (mapconcat 'identity inferior-octave-output-list
"\n")))
854 ;; And finally, everything is back to normal.
855 (set-process-filter proc
'comint-output-filter
)
856 ;; Just in case, to be sure a cd in the startup file won't have
857 ;; detrimental effects.
858 (with-demoted-errors (inferior-octave-resync-dirs))
859 ;; Generate a proper prompt, which is critical to
860 ;; `comint-history-isearch-backward-regexp'. Bug#14433.
861 (comint-send-string proc
"\n")))
863 (defun inferior-octave-completion-table ()
864 (completion-table-with-cache
866 (inferior-octave-send-list-and-digest
867 (list (format "completion_matches ('%s');\n" command
)))
868 (delete-consecutive-dups
869 (sort inferior-octave-output-list
'string-lessp
)))))
871 (defun inferior-octave-completion-at-point ()
872 "Return the data to complete the Octave symbol at point."
873 ;; http://debbugs.gnu.org/14300
874 (unless (string-match-p "/" (or (comint--match-partial-filename) ""))
875 (let ((beg (save-excursion
876 (skip-syntax-backward "w_" (comint-line-beginning-position))
879 (when (and beg
(> end beg
))
880 (list beg end
(completion-table-in-turn
881 (inferior-octave-completion-table)
882 'comint-completion-file-name-table
))))))
884 (define-obsolete-function-alias 'inferior-octave-complete
885 'completion-at-point
"24.1")
887 (defun inferior-octave-dynamic-list-input-ring ()
888 "List the buffer's input history in a help buffer."
889 ;; We cannot use `comint-dynamic-list-input-ring', because it replaces
890 ;; "completion" by "history reference" ...
892 (if (or (not (ring-p comint-input-ring
))
893 (ring-empty-p comint-input-ring
))
894 (message "No history")
896 (history-buffer " *Input History*")
897 (index (1- (ring-length comint-input-ring
)))
898 (conf (current-window-configuration)))
899 ;; We have to build up a list ourselves from the ring vector.
901 (setq history
(cons (ring-ref comint-input-ring index
) history
)
903 ;; Change "completion" to "history reference"
904 ;; to make the display accurate.
905 (with-output-to-temp-buffer history-buffer
906 (display-completion-list history
)
907 (set-buffer history-buffer
))
908 (message "Hit space to flush")
909 (let ((ch (read-event)))
911 (set-window-configuration conf
)
912 (setq unread-command-events
(list ch
)))))))
914 (defun inferior-octave-output-digest (_proc string
)
915 "Special output filter for the inferior Octave process.
916 Save all output between newlines into `inferior-octave-output-list', and
917 the rest to `inferior-octave-output-string'."
918 (setq string
(concat inferior-octave-output-string string
))
919 (while (string-match "\n" string
)
920 (setq inferior-octave-output-list
921 (append inferior-octave-output-list
922 (list (substring string
0 (match-beginning 0))))
923 string
(substring string
(match-end 0))))
924 (if (string-match inferior-octave-prompt string
)
925 (setq inferior-octave-receive-in-progress nil
))
926 (setq inferior-octave-output-string string
))
928 (defun inferior-octave-check-process ()
929 (or (inferior-octave-process-live-p)
930 (error (substitute-command-keys
931 "No inferior octave process running. Type \\[run-octave]"))))
933 (defun inferior-octave-send-list-and-digest (list)
934 "Send LIST to the inferior Octave process and digest the output.
935 The elements of LIST have to be strings and are sent one by one. All
936 output is passed to the filter `inferior-octave-output-digest'."
937 (inferior-octave-check-process)
938 (let* ((proc inferior-octave-process
)
939 (filter (process-filter proc
))
941 (set-process-filter proc
'inferior-octave-output-digest
)
942 (setq inferior-octave-output-list nil
)
944 (while (setq string
(car list
))
945 (setq inferior-octave-output-string nil
946 inferior-octave-receive-in-progress t
)
947 (comint-send-string proc string
)
948 (while inferior-octave-receive-in-progress
949 (accept-process-output proc
))
950 (setq list
(cdr list
)))
951 (set-process-filter proc filter
))))
953 (defvar inferior-octave-directory-tracker-resync nil
)
954 (make-variable-buffer-local 'inferior-octave-directory-tracker-resync
)
956 (defun inferior-octave-directory-tracker (string)
957 "Tracks `cd' commands issued to the inferior Octave process.
958 Use \\[inferior-octave-resync-dirs] to resync if Emacs gets confused."
959 (when inferior-octave-directory-tracker-resync
960 (or (inferior-octave-resync-dirs 'noerror
)
961 (setq inferior-octave-directory-tracker-resync nil
)))
963 ((string-match "^[ \t]*cd[ \t;]*$" string
)
965 ((string-match "^[ \t]*cd[ \t]+\\([^ \t\n;]*\\)[ \t\n;]*" string
)
967 (cd (match-string 1 string
))
968 (error (setq inferior-octave-directory-tracker-resync t
)
970 (error-message-string err
)
971 (match-string 1 string
)))))))
973 (defun inferior-octave-resync-dirs (&optional noerror
)
974 "Resync the buffer's idea of the current directory.
975 This command queries the inferior Octave process about its current
976 directory and makes this the current buffer's default directory."
978 (inferior-octave-send-list-and-digest '("disp (pwd ())\n"))
981 (cd (car inferior-octave-output-list
))
983 (error (unless noerror
(signal (car err
) (cdr err
))))))
985 (defcustom inferior-octave-minimal-columns
80
986 "The minimal column width for the inferior Octave process."
991 (defvar inferior-octave-last-column-width nil
)
993 (defun inferior-octave-track-window-width-change ()
994 ;; http://thread.gmane.org/gmane.comp.gnu.octave.general/48572
995 (let ((width (max inferior-octave-minimal-columns
(window-width))))
996 (unless (eq inferior-octave-last-column-width width
)
997 (setq-local inferior-octave-last-column-width width
)
998 (when (inferior-octave-process-live-p)
999 (inferior-octave-send-list-and-digest
1000 (list (format "putenv ('COLUMNS', '%s');\n" width
)))))))
1003 ;;; Miscellaneous useful functions
1005 (defun octave-in-comment-p ()
1006 "Return non-nil if point is inside an Octave comment."
1007 (nth 4 (syntax-ppss)))
1009 (defun octave-in-string-p ()
1010 "Return non-nil if point is inside an Octave string."
1011 (nth 3 (syntax-ppss)))
1013 (defun octave-in-string-or-comment-p ()
1014 "Return non-nil if point is inside an Octave string or comment."
1015 (nth 8 (syntax-ppss)))
1017 (defun octave-looking-at-kw (regexp)
1018 "Like `looking-at', but sets `case-fold-search' nil."
1019 (let ((case-fold-search nil
))
1020 (looking-at regexp
)))
1022 (defun octave-maybe-insert-continuation-string ()
1023 (if (or (octave-in-comment-p)
1026 (looking-at octave-continuation-regexp
)))
1028 (delete-horizontal-space)
1029 (insert (concat " " octave-continuation-string
))))
1031 (defun octave-completing-read ()
1032 (let ((def (or (thing-at-point 'symbol
)
1034 (skip-syntax-backward "-(")
1035 (thing-at-point 'symbol
)))))
1037 (format (if def
"Function (default %s): "
1039 (inferior-octave-completion-table)
1040 nil nil nil nil def
)))
1042 (defun octave-goto-function-definition (fn)
1043 "Go to the function definition of FN in current buffer."
1046 (let ((orig (point)) found
)
1047 (goto-char (point-min))
1048 (while (and (not found
) (re-search-forward re nil t
))
1049 (when (and (equal (match-string sub
) fn
)
1050 (not (nth 8 (syntax-ppss))))
1052 (unless found
(goto-char orig
))
1054 (pcase (and buffer-file-name
(file-name-extension buffer-file-name
))
1055 ("cc" (funcall search
1056 "\\_<DEFUN\\(?:_DLD\\)?\\s-*(\\s-*\\(\\(?:\\sw\\|\\s_\\)+\\)" 1))
1057 (t (funcall search octave-function-header-regexp
3)))))
1059 (defun octave-function-file-p ()
1060 "Return non-nil if the first token is \"function\".
1061 The value is (START END NAME-START NAME-END) of the function."
1063 (goto-char (point-min))
1064 (when (equal (funcall smie-forward-token-function
) "function")
1066 (let* ((start (point))
1067 (end (progn (forward-sexp 1) (point)))
1070 (re-search-forward octave-function-header-regexp
1072 (list (match-beginning 3) (match-end 3)))))
1073 (cons start
(cons end name
))))))
1075 ;; Like forward-comment but stop at non-comment blank
1076 (defun octave-skip-comment-forward (limit)
1077 (let ((ppss (syntax-ppss)))
1079 (goto-char (nth 8 ppss
))
1080 (goto-char (or (comment-search-forward limit t
) (point)))))
1081 (while (and (< (point) limit
) (looking-at-p "\\s<"))
1082 (forward-comment 1)))
1084 ;;; First non-copyright comment block
1085 (defun octave-function-file-comment ()
1086 "Beginning and end positions of the function file comment."
1088 (goto-char (point-min))
1089 ;; Copyright block: octave/libinterp/parse-tree/lex.ll around line 1634
1090 (while (save-excursion
1091 (when (comment-search-forward (point-max) t
)
1092 (when (eq (char-after) ?\
{) ; case of block comment
1094 (skip-syntax-forward "-")
1095 (let ((case-fold-search t
))
1096 (looking-at-p "\\(?:copyright\\|author\\)\\_>"))))
1097 (octave-skip-comment-forward (point-max)))
1098 (let ((beg (comment-search-forward (point-max) t
)))
1101 (octave-skip-comment-forward (point-max))
1102 (list beg
(point))))))
1104 (defun octave-sync-function-file-names ()
1105 "Ensure function name agree with function file name.
1106 See Info node `(octave)Function Files'."
1108 (when buffer-file-name
1109 (pcase-let ((`(,start
,_end
,name-start
,name-end
)
1110 (octave-function-file-p)))
1111 (when (and start name-start
)
1112 (let* ((func (buffer-substring name-start name-end
))
1113 (file (file-name-sans-extension
1114 (file-name-nondirectory buffer-file-name
)))
1115 (help-form (format "\
1116 a: Use function name `%s'
1117 b: Use file name `%s'
1118 q: Don't fix\n" func file
))
1119 (c (unless (equal file func
)
1120 (save-window-excursion
1123 "Which name to use? (a/b/q) " '(?a ?b ?q
))))))
1125 (?a
(let ((newname (expand-file-name
1126 (concat func
(file-name-extension
1127 buffer-file-name t
)))))
1128 (when (or (not (file-exists-p newname
))
1130 (format "Target file %s exists; proceed? " newname
)))
1131 (when (file-exists-p buffer-file-name
)
1132 (rename-file buffer-file-name newname t
))
1133 (set-visited-file-name newname
))))
1135 (goto-char name-start
)
1136 (delete-region name-start name-end
)
1137 (insert file
)))))))))
1139 (defun octave-update-function-file-comment (beg end
)
1140 "Query replace function names in function file comment."
1143 (barf-if-buffer-read-only)
1145 (list (region-beginning) (region-end))
1146 (or (octave-function-file-comment)
1147 (error "No function file comment found")))))
1149 (let* ((bounds (or (octave-function-file-p)
1150 (error "Not in a function file buffer")))
1151 (func (if (cddr bounds
)
1152 (apply #'buffer-substring
(cddr bounds
))
1153 (error "Function name not found")))
1156 (when (re-search-forward
1157 "[=}]\\s-*\\(\\(?:\\sw\\|\\s_\\)+\\)\\_>"
1158 (min (line-end-position 4) end
)
1161 (old-func (read-string (format (if old-func
1162 "Name to replace (default %s): "
1163 "Name to replace: ")
1166 (if (and func old-func
(not (equal func old-func
)))
1167 (perform-replace old-func func
'query
1168 nil
'delimited nil nil beg end
)
1169 (message "Function names match")))))
1171 (defface octave-function-comment-block
1172 '((t (:inherit font-lock-doc-face
)))
1173 "Face used to highlight function comment block."
1176 (eval-when-compile (require 'texinfo
))
1178 (defun octave-font-lock-texinfo-comment ()
1183 (if (numberp (nth 1 kw
))
1184 `(,(nth 0 kw
) ,(nth 1 kw
) ,(nth 2 kw
) prepend
)
1185 (message "Ignoring Texinfo highlight: %S" kw
)))
1186 texinfo-font-lock-keywords
)))))
1187 (font-lock-add-keywords
1190 (while (and (< (point) limit
)
1191 (search-forward "-*- texinfo -*-" limit t
)
1192 (octave-in-comment-p))
1193 (let ((beg (nth 8 (syntax-ppss)))
1195 (octave-skip-comment-forward (point-max))
1197 (put-text-property beg end
'font-lock-multiline t
)
1198 (font-lock-prepend-text-property
1199 beg end
'face
'octave-function-comment-block
)
1202 (while (re-search-forward (car kw
) end
'move
)
1203 (font-lock-apply-highlight (cdr kw
))))))
1210 (defun octave-indent-new-comment-line (&optional soft
)
1211 "Break Octave line at point, continuing comment if within one.
1212 Insert `octave-continuation-string' before breaking the line
1213 unless inside a list. Signal an error if within a single-quoted
1216 (funcall comment-line-break-function soft
))
1218 (defun octave--indent-new-comment-line (orig &rest args
)
1220 ((octave-in-comment-p) nil
)
1221 ((eq (octave-in-string-p) ?
')
1222 (error "Cannot split a single-quoted string"))
1223 ((eq (octave-in-string-p) ?
\")
1224 (insert octave-continuation-string
))
1226 (delete-horizontal-space)
1227 (unless (and (cadr (syntax-ppss))
1228 (eq (char-after (cadr (syntax-ppss))) ?\
())
1229 (insert " " octave-continuation-string
))))
1231 (indent-according-to-mode))
1233 (define-obsolete-function-alias
1234 'octave-indent-defun
'prog-indent-sexp
"24.4")
1238 (defun octave-next-code-line (&optional arg
)
1239 "Move ARG lines of Octave code forward (backward if ARG is negative).
1240 Skips past all empty and comment lines. Default for ARG is 1.
1242 On success, return 0. Otherwise, go as far as possible and return -1."
1244 (or arg
(setq arg
1))
1247 (inc (if (> arg
0) 1 -
1)))
1248 (while (and (/= arg
0) (= n
0))
1249 (setq n
(forward-line inc
))
1251 (looking-at "\\s-*\\($\\|\\s<\\)"))
1252 (setq n
(forward-line inc
)))
1253 (setq arg
(- arg inc
)))
1256 (defun octave-previous-code-line (&optional arg
)
1257 "Move ARG lines of Octave code backward (forward if ARG is negative).
1258 Skips past all empty and comment lines. Default for ARG is 1.
1260 On success, return 0. Otherwise, go as far as possible and return -1."
1262 (or arg
(setq arg
1))
1263 (octave-next-code-line (- arg
)))
1265 (defun octave-beginning-of-line ()
1266 "Move point to beginning of current Octave line.
1267 If on an empty or comment line, go to the beginning of that line.
1268 Otherwise, move backward to the beginning of the first Octave code line
1269 which is not inside a continuation statement, i.e., which does not
1270 follow a code line ending with `...' or is inside an open
1274 (unless (looking-at "\\s-*\\($\\|\\s<\\)")
1275 (while (or (when (cadr (syntax-ppss))
1276 (goto-char (cadr (syntax-ppss)))
1279 (and (or (looking-at "\\s-*\\($\\|\\s<\\)")
1281 (if (zerop (octave-previous-code-line))
1282 (looking-at octave-continuation-regexp
))))
1283 (zerop (forward-line -
1)))))))
1285 (defun octave-end-of-line ()
1286 "Move point to end of current Octave line.
1287 If on an empty or comment line, go to the end of that line.
1288 Otherwise, move forward to the end of the first Octave code line which
1289 does not end with `...' or is inside an open parenthesis list."
1292 (unless (save-excursion
1294 (looking-at "\\s-*\\($\\|\\s<\\)"))
1295 (while (or (when (cadr (syntax-ppss))
1302 (and (save-excursion
1304 (or (looking-at "\\s-*\\($\\|\\s<\\)")
1305 (looking-at octave-continuation-regexp
)))
1306 (zerop (forward-line 1)))))
1309 (defun octave-mark-block ()
1310 "Put point at the beginning of this Octave block, mark at the end.
1311 The block marked is the one that contains point or follows point."
1313 (if (and (looking-at "\\sw\\|\\s_")
1314 (looking-back "\\sw\\|\\s_" (1- (point))))
1315 (skip-syntax-forward "w_"))
1316 (unless (or (looking-at "\\s(")
1318 (let* ((token (funcall smie-forward-token-function
))
1319 (level (assoc token smie-grammar
)))
1320 (and level
(not (numberp (cadr level
)))))))
1321 (backward-up-list 1))
1324 (defun octave-beginning-of-defun (&optional arg
)
1325 "Octave-specific `beginning-of-defun-function' (which see)."
1326 (or arg
(setq arg
1))
1327 ;; Move out of strings or comments.
1328 (when (octave-in-string-or-comment-p)
1329 (goto-char (octave-in-string-or-comment-p)))
1330 (letrec ((orig (point))
1331 (toplevel (lambda (pos)
1334 (backward-up-list 1)
1335 (funcall toplevel
(point)))
1336 (scan-error pos
)))))
1337 (goto-char (funcall toplevel
(point)))
1338 (when (and (> arg
0) (/= orig
(point)))
1339 (setq arg
(1- arg
)))
1340 (forward-sexp (- arg
))
1341 (and (< arg
0) (forward-sexp -
1))
1344 (defun octave-fill-paragraph (&optional _arg
)
1345 "Fill paragraph of Octave code, handling Octave comments."
1346 ;; FIXME: difference with generic fill-paragraph:
1347 ;; - code lines are only split, never joined.
1348 ;; - \n that end comments are never removed.
1349 ;; - insert continuation marker when splitting code lines.
1352 (let ((end (progn (forward-paragraph) (copy-marker (point) t
)))
1354 (forward-paragraph -
1)
1355 (skip-chars-forward " \t\n")
1358 (cfc (current-fill-column))
1361 (while (< (point) end
)
1363 (indent-according-to-mode)
1365 (move-to-column cfc
)
1366 ;; First check whether we need to combine non-empty comment lines
1367 (if (and (< (current-column) cfc
)
1368 (octave-in-comment-p)
1369 (not (save-excursion
1371 (looking-at "^\\s-*\\s<+\\s-*$"))))
1372 ;; This is a nonempty comment line which does not extend
1373 ;; past the fill column. If it is followed by a nonempty
1374 ;; comment line with the same comment prefix, try to
1375 ;; combine them, and repeat this until either we reach the
1376 ;; fill-column or there is nothing more to combine.
1378 ;; Get the comment prefix
1381 (while (and (re-search-forward "\\s<+")
1382 (not (octave-in-comment-p))))
1383 (setq comment-prefix
(match-string 0)))
1384 ;; And keep combining ...
1385 (while (and (< (current-column) cfc
)
1397 (re-search-forward comment-prefix
)
1398 (delete-region (match-beginning 0) (match-end 0))
1400 (move-to-column cfc
))))
1401 ;; We might also try to combine continued code lines> Perhaps
1402 ;; some other time ...
1403 (skip-chars-forward "^ \t\n")
1404 (delete-horizontal-space)
1405 (if (or (< (current-column) cfc
)
1406 (and (= (current-column) cfc
) (eolp)))
1408 (if (not (eolp)) (insert " "))
1409 (or (funcall normal-auto-fill-function
)
1413 (defun octave-completion-at-point ()
1414 "Find the text to complete and the corresponding table."
1415 (let* ((beg (save-excursion (skip-syntax-backward "w_") (point)))
1418 ;; Extend region past point, if applicable.
1419 (save-excursion (skip-syntax-forward "w_")
1420 (setq end
(point))))
1422 (list beg end
(or (and (inferior-octave-process-live-p)
1423 (inferior-octave-completion-table))
1424 octave-reserved-words
)))))
1426 (define-obsolete-function-alias 'octave-complete-symbol
1427 'completion-at-point
"24.1")
1429 (defun octave-add-log-current-defun ()
1430 "A function for `add-log-current-defun-function' (which see)."
1433 (and (beginning-of-defun)
1434 (re-search-forward octave-function-header-regexp
1435 (line-end-position) t
)
1439 ;;; Electric characters && friends
1440 (define-skeleton octave-insert-defun
1441 "Insert an Octave function skeleton.
1442 Prompt for the function's name, arguments and return values (to be
1443 entered without parens)."
1444 (let* ((defname (file-name-sans-extension (buffer-name)))
1445 (name (read-string (format "Function name (default %s): " defname
)
1447 (args (read-string "Arguments: "))
1448 (vals (read-string "Return values: ")))
1451 ((string-equal vals
"") vals
)
1452 ((string-match "[ ,]" vals
) (concat "[" vals
"] = "))
1453 (t (concat vals
" = ")))
1456 \n octave-block-comment-start
"usage: " str
\n
1457 octave-block-comment-start
'(delete-horizontal-space) \n
1458 octave-block-comment-start
'(delete-horizontal-space) \n
1459 "function " > str
\n
1463 ;;; Communication with the inferior Octave process
1464 (defun octave-kill-process ()
1465 "Kill inferior Octave process and its buffer."
1467 (when (and (buffer-live-p (get-buffer inferior-octave-buffer
))
1468 (or (yes-or-no-p (format "Kill %S and its buffer? "
1469 inferior-octave-process
))
1470 (user-error "Aborted")))
1471 (when (inferior-octave-process-live-p)
1472 (set-process-query-on-exit-flag inferior-octave-process nil
)
1473 (process-send-string inferior-octave-process
"quit;\n")
1474 (accept-process-output inferior-octave-process
))
1475 (kill-buffer inferior-octave-buffer
)))
1477 (defun octave-show-process-buffer ()
1478 "Make sure that `inferior-octave-buffer' is displayed."
1480 (if (get-buffer inferior-octave-buffer
)
1481 (display-buffer inferior-octave-buffer
)
1482 (message "No buffer named %s" inferior-octave-buffer
)))
1484 (defun octave-hide-process-buffer ()
1485 "Delete all windows that display `inferior-octave-buffer'."
1487 (if (get-buffer inferior-octave-buffer
)
1488 (delete-windows-on inferior-octave-buffer
)
1489 (message "No buffer named %s" inferior-octave-buffer
)))
1491 (defun octave-source-file (file)
1492 "Execute FILE in the inferior Octave process.
1493 This is done using Octave's source function. FILE defaults to
1494 current buffer file unless called with a prefix arg \\[universal-argument]."
1495 (interactive (list (or (and (not current-prefix-arg
) buffer-file-name
)
1496 (read-file-name "File: " nil nil t
))))
1498 (signal 'wrong-type-argument
(list 'stringp file
)))
1500 (with-current-buffer inferior-octave-buffer
1501 (comint-send-string inferior-octave-process
1502 (format "source '%s'\n" file
))))
1504 (defun octave-send-region (beg end
)
1505 "Send current region to the inferior Octave process."
1508 (let ((proc inferior-octave-process
)
1509 (string (buffer-substring-no-properties beg end
))
1511 (with-current-buffer inferior-octave-buffer
1512 ;; http://lists.gnu.org/archive/html/emacs-devel/2013-10/msg00095.html
1513 (compilation-forget-errors)
1514 (setq inferior-octave-output-list nil
)
1515 (while (not (string-equal string
""))
1516 (if (string-match "\n" string
)
1517 (setq line
(substring string
0 (match-beginning 0))
1518 string
(substring string
(match-end 0)))
1519 (setq line string string
""))
1520 (setq inferior-octave-receive-in-progress t
)
1521 (inferior-octave-send-list-and-digest (list (concat line
"\n")))
1522 (while inferior-octave-receive-in-progress
1523 (accept-process-output proc
))
1524 (insert-before-markers
1525 (mapconcat 'identity
1527 (if octave-send-echo-input
(list line
) (list ""))
1528 inferior-octave-output-list
1529 (list inferior-octave-output-string
))
1531 (if octave-send-show-buffer
1532 (display-buffer inferior-octave-buffer
)))
1534 (defun octave-send-buffer ()
1535 "Send current buffer to the inferior Octave process."
1537 (octave-send-region (point-min) (point-max)))
1539 (defun octave-send-block ()
1540 "Send current Octave block to the inferior Octave process."
1544 (octave-send-region (point) (mark))))
1546 (defun octave-send-defun ()
1547 "Send current Octave function to the inferior Octave process."
1551 (octave-send-region (point) (mark))))
1553 (defun octave-send-line (&optional arg
)
1554 "Send current Octave code line to the inferior Octave process.
1555 With positive prefix ARG, send that many lines.
1556 If `octave-send-line-auto-forward' is non-nil, go to the next unsent
1559 (or arg
(setq arg
1))
1564 (octave-next-code-line (- arg
1))
1567 (if octave-send-line-auto-forward
1568 (octave-next-code-line 1))
1569 (octave-send-region beg end
))))
1571 (defun octave-eval-print-last-sexp ()
1572 "Evaluate Octave sexp before point and print value into current buffer."
1575 (let ((standard-output (current-buffer))
1576 (print-escape-newlines nil
)
1582 (inferior-octave-send-list-and-digest
1583 (list (concat (buffer-substring-no-properties (point) opoint
)
1585 (mapconcat 'identity inferior-octave-output-list
"\n")))
1590 (defcustom octave-eldoc-message-style
'auto
1591 "Octave eldoc message style: auto, oneline, multiline."
1592 :type
'(choice (const :tag
"Automatic" auto
)
1593 (const :tag
"One Line" oneline
)
1594 (const :tag
"Multi Line" multiline
))
1598 ;; (FN SIGNATURE1 SIGNATURE2 ...)
1599 (defvar octave-eldoc-cache nil
)
1601 (defun octave-eldoc-function-signatures (fn)
1602 (unless (equal fn
(car octave-eldoc-cache
))
1603 (inferior-octave-send-list-and-digest
1604 (list (format "print_usage ('%s');\n" fn
)))
1606 (dolist (line inferior-octave-output-list
)
1608 "\\s-*\\(?:--[^:]+\\|usage\\):\\s-*\\(.*\\)$"
1610 (push (match-string 1 line
) result
)))
1611 (setq octave-eldoc-cache
1612 (cons (substring-no-properties fn
)
1613 (nreverse result
)))))
1614 (cdr octave-eldoc-cache
))
1616 (defun octave-eldoc-function ()
1617 "A function for `eldoc-documentation-function' (which see)."
1618 (when (inferior-octave-process-live-p)
1619 (let* ((ppss (syntax-ppss))
1620 (paren-pos (cadr ppss
))
1623 ;; PAREN-POS must be after the prompt
1625 (if (eq (get-buffer-process (current-buffer))
1626 inferior-octave-process
)
1627 (process-mark inferior-octave-process
)
1629 (or (not (eq (get-buffer-process (current-buffer))
1630 inferior-octave-process
))
1631 (< (process-mark inferior-octave-process
)
1633 (eq (char-after paren-pos
) ?\
())
1634 (goto-char paren-pos
)
1635 (setq paren-pos nil
))
1636 (when (or (< (skip-syntax-backward "-") 0) paren-pos
)
1637 (thing-at-point 'symbol
))))
1638 (sigs (and fn
(octave-eldoc-function-signatures fn
)))
1639 (oneline (mapconcat 'identity sigs
1640 (propertize " | " 'face
'warning
)))
1641 (multiline (mapconcat (lambda (s) (concat "-- " s
)) sigs
"\n")))
1643 ;; Return the value according to style.
1644 (pcase octave-eldoc-message-style
1645 (`auto
(if (< (length oneline
) (window-width (minibuffer-window)))
1649 (`multiline multiline
)))))
1651 (defcustom octave-help-buffer
"*Octave Help*"
1652 "Buffer name for `octave-help'."
1657 ;; Used in a mode derived from help-mode.
1658 (declare-function help-button-action
"help-mode" (button))
1660 (define-button-type 'octave-help-file
1662 'action
#'help-button-action
1663 'help-function
'octave-find-definition
)
1665 (define-button-type 'octave-help-function
1669 (buffer-substring (button-start b
) (button-end b
)))))
1671 (defvar octave-help-mode-map
1672 (let ((map (make-sparse-keymap)))
1673 (define-key map
"\M-." 'octave-find-definition
)
1674 (define-key map
"\C-hd" 'octave-help
)
1675 (define-key map
"\C-ha" 'octave-lookfor
)
1678 (define-derived-mode octave-help-mode help-mode
"OctHelp"
1679 "Major mode for displaying Octave documentation."
1681 :syntax-table octave-mode-syntax-table
1682 (eval-and-compile (require 'help-mode
))
1683 ;; Don't highlight `EXAMPLE' as elisp symbols by using a regexp that
1685 (setq-local help-xref-symbol-regexp
"x\\`"))
1687 (defun octave-help (fn)
1688 "Display the documentation of FN."
1689 (interactive (list (octave-completing-read)))
1690 (inferior-octave-send-list-and-digest
1691 (list (format "help ('%s');\n" fn
)))
1692 (let ((lines inferior-octave-output-list
)
1693 (inhibit-read-only t
))
1694 (when (string-match "error: \\(.*\\)$" (car lines
))
1695 (error "%s" (match-string 1 (car lines
))))
1696 (with-help-window octave-help-buffer
1697 (princ (mapconcat 'identity lines
"\n"))
1698 (with-current-buffer octave-help-buffer
1699 ;; Bound to t so that `help-buffer' returns current buffer for
1700 ;; `help-setup-xref'.
1701 (let ((help-xref-following t
))
1702 (help-setup-xref (list 'octave-help fn
)
1703 (called-interactively-p 'interactive
)))
1704 ;; Note: can be turned off by suppress_verbose_help_message.
1706 ;; Remove boring trailing text: Additional help for built-in functions
1707 ;; and operators ...
1708 (goto-char (point-max))
1709 (when (search-backward "\n\n\n" nil t
)
1710 (goto-char (match-beginning 0))
1711 (delete-region (point) (point-max)))
1712 ;; File name highlight
1713 (goto-char (point-min))
1714 (when (re-search-forward "from the file \\(.*\\)$"
1717 (let* ((file (match-string 1))
1718 (dir (file-name-directory
1719 (directory-file-name (file-name-directory file
)))))
1720 (replace-match "" nil nil nil
1)
1722 ;; Include the parent directory which may be regarded as
1723 ;; the category for the FN.
1724 (help-insert-xref-button (file-relative-name file dir
)
1725 'octave-help-file fn
)
1727 ;; Make 'See also' clickable.
1728 (with-syntax-table octave-mode-syntax-table
1729 (when (re-search-forward "^\\s-*See also:" nil t
)
1730 (let ((end (save-excursion (re-search-forward "^\\s-*$" nil t
))))
1731 (while (re-search-forward
1732 "\\s-*\\([^,\n]+?\\)\\s-*\\(?:[,]\\|[.]?$\\)" end t
)
1733 (make-text-button (match-beginning 1) (match-end 1)
1734 :type
'octave-help-function
)))))
1735 (octave-help-mode)))))
1737 (defun octave-lookfor (str &optional all
)
1738 "Search for the string STR in all function help strings.
1739 If ALL is non-nil search the entire help string else only search the first
1741 (interactive "sSearch for: \nP")
1742 (inferior-octave-send-list-and-digest
1743 (list (format "lookfor (%s'%s');\n"
1744 (if all
"'-all', " "")
1746 (let ((lines inferior-octave-output-list
))
1747 (when (and (stringp (car lines
))
1748 (string-match "error: \\(.*\\)$" (car lines
)))
1749 (error "%s" (match-string 1 (car lines
))))
1750 (with-help-window octave-help-buffer
1751 (with-current-buffer octave-help-buffer
1753 (insert (mapconcat 'identity lines
"\n"))
1754 (insert (format "Nothing found for \"%s\".\n" str
)))
1755 ;; Bound to t so that `help-buffer' returns current buffer for
1756 ;; `help-setup-xref'.
1757 (let ((help-xref-following t
))
1758 (help-setup-xref (list 'octave-lookfor str all
)
1759 (called-interactively-p 'interactive
)))
1760 (goto-char (point-min))
1762 (while (re-search-forward "^\\([^[:blank:]]+\\) " nil
'noerror
)
1763 (make-text-button (match-beginning 1) (match-end 1)
1764 :type
'octave-help-function
)))
1766 (goto-char (point-max))
1767 (insert "\nRetry with ")
1768 (insert-text-button "'-all'"
1770 'action
#'(lambda (_b)
1771 (octave-lookfor str
'-all
)))
1773 (octave-help-mode)))))
1775 (defcustom octave-source-directories nil
1776 "A list of directories for Octave sources.
1777 If the environment variable OCTAVE_SRCDIR is set, it is searched first."
1778 :type
'(repeat directory
)
1782 (defun octave-source-directories ()
1783 (let ((srcdir (or (and inferior-octave-process
1784 (process-get inferior-octave-process
'octave-srcdir
))
1785 (getenv "OCTAVE_SRCDIR"))))
1787 (cons srcdir octave-source-directories
)
1788 octave-source-directories
)))
1790 (defvar octave-find-definition-filename-function
1791 #'octave-find-definition-default-filename
)
1793 (defun octave-find-definition-default-filename (name)
1794 "Default value for `octave-find-definition-filename-function'."
1795 (pcase (file-name-extension name
)
1797 (octave-find-definition-default-filename
1798 (concat "libinterp/dldfcn/"
1799 (file-name-sans-extension (file-name-nondirectory name
))
1802 (let ((file (or (locate-file name
(octave-source-directories))
1803 (locate-file (file-name-nondirectory name
)
1804 (octave-source-directories)))))
1805 (or (and file
(file-exists-p file
))
1806 (error "File `%s' not found" name
))
1809 (if (yes-or-no-p (format "File `%s' may be binary; open? "
1810 (file-name-nondirectory name
)))
1812 (user-error "Aborted")))
1815 (defvar find-tag-marker-ring
)
1817 (defun octave-find-definition (fn)
1818 "Find the definition of FN.
1819 Functions implemented in C++ can be found if
1820 variable `octave-source-directories' is set correctly."
1821 (interactive (list (octave-completing-read)))
1823 (let ((orig (point)))
1824 (if (and (derived-mode-p 'octave-mode
)
1825 (octave-goto-function-definition fn
))
1826 (ring-insert find-tag-marker-ring
(copy-marker orig
))
1827 (inferior-octave-send-list-and-digest
1828 ;; help NAME is more verbose
1830 if iskeyword('%s') disp('`%s'' is a keyword') else which('%s') endif\n"
1833 ;; Skip garbage lines such as
1834 ;; warning: fmincg.m: possible Matlab-style ....
1835 (while (and (not file
) (consp inferior-octave-output-list
))
1836 (setq line
(pop inferior-octave-output-list
))
1837 (when (string-match "from the file \\(.*\\)$" line
)
1838 (setq file
(match-string 1 line
))))
1840 (user-error "%s" (or line
(format "`%s' not found" fn
)))
1841 (ring-insert find-tag-marker-ring
(point-marker))
1842 (setq file
(funcall octave-find-definition-filename-function file
))
1845 (octave-goto-function-definition fn
)))))))
1848 ;;; octave.el ends here