]> code.delx.au - gnu-emacs/blob - lisp/progmodes/octave.el
; Merge branch 'fix/no-undo-boundary-on-secondary-buffer-change'
[gnu-emacs] / lisp / progmodes / octave.el
1 ;;; octave.el --- editing octave source files under emacs -*- lexical-binding: t; -*-
2
3 ;; Copyright (C) 1997, 2001-2015 Free Software Foundation, Inc.
4
5 ;; Author: Kurt Hornik <Kurt.Hornik@wu-wien.ac.at>
6 ;; John Eaton <jwe@octave.org>
7 ;; Maintainer: emacs-devel@gnu.org
8 ;; Keywords: languages
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24
25 ;;; Commentary:
26
27 ;; This package provides Emacs support for Octave. It defines a major
28 ;; mode for editing Octave code and contains code for interacting with
29 ;; an inferior Octave process using comint.
30
31 ;; See the documentation of `octave-mode' and `run-octave' for further
32 ;; information on usage and customization.
33
34 ;;; Code:
35 (require 'comint)
36
37 ;;; For emacs < 24.3.
38 (require 'newcomment)
39 (eval-and-compile
40 (unless (fboundp 'user-error)
41 (defalias 'user-error 'error))
42 (unless (fboundp 'delete-consecutive-dups)
43 (defalias 'delete-consecutive-dups 'delete-dups))
44 (unless (fboundp 'completion-table-with-cache)
45 (defun completion-table-with-cache (fun &optional ignore-case)
46 ;; See eg bug#11906.
47 (let* (last-arg last-result
48 (new-fun
49 (lambda (arg)
50 (if (and last-arg (string-prefix-p last-arg arg ignore-case))
51 last-result
52 (prog1
53 (setq last-result (funcall fun arg))
54 (setq last-arg arg))))))
55 (completion-table-dynamic new-fun)))))
56 (eval-when-compile
57 (unless (fboundp 'setq-local)
58 (defmacro setq-local (var val)
59 "Set variable VAR to value VAL in current buffer."
60 (list 'set (list 'make-local-variable (list 'quote var)) val))))
61
62 (defgroup octave nil
63 "Editing Octave code."
64 :link '(custom-manual "(octave-mode)Top")
65 :link '(url-link "http://www.gnu.org/s/octave")
66 :link '(custom-group-link :tag "Font Lock Faces group" font-lock-faces)
67 :group 'languages)
68
69 (define-obsolete-function-alias 'octave-submit-bug-report
70 'report-emacs-bug "24.4")
71
72 (define-abbrev-table 'octave-abbrev-table nil
73 "Abbrev table for Octave's reserved words.
74 Used in `octave-mode' and `inferior-octave-mode' buffers.")
75
76 (defvar octave-comment-char ?#
77 "Character to start an Octave comment.")
78
79 (defvar octave-comment-start (char-to-string octave-comment-char)
80 "Octave-specific `comment-start' (which see).")
81
82 (defvar octave-comment-start-skip "\\(^\\|\\S<\\)\\(?:%!\\|\\s<+\\)\\s-*"
83 "Octave-specific `comment-start-skip' (which see).")
84
85 (defvar octave-function-header-regexp
86 (concat "^\\s-*\\_<\\(function\\)\\_>"
87 "\\([^=;(\n]*=[ \t]*\\|[ \t]*\\)\\(\\(?:\\w\\|\\s_\\)+\\)\\_>")
88 "Regexp to match an Octave function header.
89 The string `function' and its name are given by the first and third
90 parenthetical grouping.")
91
92 \f
93 (defvar octave-mode-map
94 (let ((map (make-sparse-keymap)))
95 (define-key map "\M-." 'octave-find-definition)
96 (define-key map "\M-\C-j" 'octave-indent-new-comment-line)
97 (define-key map "\C-c\C-p" 'octave-previous-code-line)
98 (define-key map "\C-c\C-n" 'octave-next-code-line)
99 (define-key map "\C-c\C-a" 'octave-beginning-of-line)
100 (define-key map "\C-c\C-e" 'octave-end-of-line)
101 (define-key map [remap down-list] 'smie-down-list)
102 (define-key map "\C-c\M-\C-h" 'octave-mark-block)
103 (define-key map "\C-c]" 'smie-close-block)
104 (define-key map "\C-c/" 'smie-close-block)
105 (define-key map "\C-c;" 'octave-update-function-file-comment)
106 (define-key map "\C-hd" 'octave-help)
107 (define-key map "\C-ha" 'octave-lookfor)
108 (define-key map "\C-c\C-l" 'octave-source-file)
109 (define-key map "\C-c\C-f" 'octave-insert-defun)
110 (define-key map "\C-c\C-il" 'octave-send-line)
111 (define-key map "\C-c\C-ib" 'octave-send-block)
112 (define-key map "\C-c\C-if" 'octave-send-defun)
113 (define-key map "\C-c\C-ir" 'octave-send-region)
114 (define-key map "\C-c\C-ia" 'octave-send-buffer)
115 (define-key map "\C-c\C-is" 'octave-show-process-buffer)
116 (define-key map "\C-c\C-iq" 'octave-hide-process-buffer)
117 (define-key map "\C-c\C-ik" 'octave-kill-process)
118 (define-key map "\C-c\C-i\C-l" 'octave-send-line)
119 (define-key map "\C-c\C-i\C-b" 'octave-send-block)
120 (define-key map "\C-c\C-i\C-f" 'octave-send-defun)
121 (define-key map "\C-c\C-i\C-r" 'octave-send-region)
122 (define-key map "\C-c\C-i\C-a" 'octave-send-buffer)
123 (define-key map "\C-c\C-i\C-s" 'octave-show-process-buffer)
124 (define-key map "\C-c\C-i\C-q" 'octave-hide-process-buffer)
125 (define-key map "\C-c\C-i\C-k" 'octave-kill-process)
126 map)
127 "Keymap used in Octave mode.")
128
129
130
131 (easy-menu-define octave-mode-menu octave-mode-map
132 "Menu for Octave mode."
133 '("Octave"
134 ["Split Line at Point" octave-indent-new-comment-line t]
135 ["Previous Code Line" octave-previous-code-line t]
136 ["Next Code Line" octave-next-code-line t]
137 ["Begin of Line" octave-beginning-of-line t]
138 ["End of Line" octave-end-of-line t]
139 ["Mark Block" octave-mark-block t]
140 ["Close Block" smie-close-block t]
141 "---"
142 ["Start Octave Process" run-octave t]
143 ["Documentation Lookup" info-lookup-symbol t]
144 ["Help on Function" octave-help t]
145 ["Search help" octave-lookfor t]
146 ["Find Function Definition" octave-find-definition t]
147 ["Insert Function" octave-insert-defun t]
148 ["Update Function File Comment" octave-update-function-file-comment t]
149 "---"
150 ["Function Syntax Hints" (eldoc-mode 'toggle)
151 :style toggle :selected (bound-and-true-p eldoc-mode)
152 :help "Display function signatures after typing `SPC' or `('"]
153 ["Delimiter Matching" show-paren-mode
154 :style toggle :selected show-paren-mode
155 :help "Highlight matched pairs such as `if ... end'"
156 :visible (fboundp 'smie--matching-block-data)]
157 ["Auto Fill" auto-fill-mode
158 :style toggle :selected auto-fill-function
159 :help "Automatic line breaking"]
160 ["Electric Layout" electric-layout-mode
161 :style toggle :selected electric-layout-mode
162 :help "Automatically insert newlines around some chars"]
163 "---"
164 ("Debug"
165 ["Send Current Line" octave-send-line t]
166 ["Send Current Block" octave-send-block t]
167 ["Send Current Function" octave-send-defun t]
168 ["Send Region" octave-send-region t]
169 ["Send Buffer" octave-send-buffer t]
170 ["Source Current File" octave-source-file t]
171 ["Show Process Buffer" octave-show-process-buffer t]
172 ["Hide Process Buffer" octave-hide-process-buffer t]
173 ["Kill Process" octave-kill-process t])
174 "---"
175 ["Octave Mode Manual" (info "(octave-mode)Top") t]
176 ["Customize Octave" (customize-group 'octave) t]
177 ["Submit Bug Report" report-emacs-bug t]))
178
179 (defvar octave-mode-syntax-table
180 (let ((table (make-syntax-table)))
181 (modify-syntax-entry ?\r " " table)
182 (modify-syntax-entry ?+ "." table)
183 (modify-syntax-entry ?- "." table)
184 (modify-syntax-entry ?= "." table)
185 (modify-syntax-entry ?* "." table)
186 (modify-syntax-entry ?/ "." table)
187 (modify-syntax-entry ?> "." table)
188 (modify-syntax-entry ?< "." table)
189 (modify-syntax-entry ?& "." table)
190 (modify-syntax-entry ?| "." table)
191 (modify-syntax-entry ?! "." table)
192 (modify-syntax-entry ?\\ "." 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 ;; The "b" flag only applies to the second letter of the comstart
199 ;; and the first letter of the comend, i.e. the "4b" below is ineffective.
200 ;; If we try to put `b' on the single-line comments, we get a similar
201 ;; problem where the % and # chars appear as first chars of the 2-char
202 ;; comend, so the multi-line ender is also turned into style-b.
203 ;; So we need the new "c" comment style.
204 (modify-syntax-entry ?\% "< 13" table)
205 (modify-syntax-entry ?\# "< 13" table)
206 (modify-syntax-entry ?\{ "(} 2c" table)
207 (modify-syntax-entry ?\} "){ 4c" table)
208 (modify-syntax-entry ?\n ">" table)
209 table)
210 "Syntax table in use in `octave-mode' buffers.")
211
212 (defcustom octave-font-lock-texinfo-comment t
213 "Control whether to highlight the texinfo comment block."
214 :type 'boolean
215 :version "24.4")
216
217 (defcustom octave-blink-matching-block t
218 "Control the blinking of matching Octave block keywords.
219 Non-nil means show matching begin of block when inserting a space,
220 newline or semicolon after an else or end keyword."
221 :type 'boolean)
222
223 (defcustom octave-block-offset 2
224 "Extra indentation applied to statements in Octave block structures."
225 :type 'integer)
226
227 (defvar octave-block-comment-start
228 (concat (make-string 2 octave-comment-char) " ")
229 "String to insert to start a new Octave comment on an empty line.")
230
231 (defcustom octave-continuation-offset 4
232 "Extra indentation applied to Octave continuation lines."
233 :type 'integer)
234
235 (eval-and-compile
236 (defconst octave-continuation-marker-regexp "\\\\\\|\\.\\.\\."))
237
238 (defvar octave-continuation-regexp
239 (concat "[^#%\n]*\\(" octave-continuation-marker-regexp
240 "\\)\\s-*\\(\\s<.*\\)?$"))
241
242 ;; Char \ is considered a bad decision for continuing a line.
243 (defconst octave-continuation-string "..."
244 "Character string used for Octave continuation lines.")
245
246 (defvar octave-mode-imenu-generic-expression
247 (list
248 ;; Functions
249 (list nil octave-function-header-regexp 3))
250 "Imenu expression for Octave mode. See `imenu-generic-expression'.")
251
252 (defcustom octave-mode-hook nil
253 "Hook to be run when Octave mode is started."
254 :type 'hook)
255
256 (defcustom octave-send-show-buffer t
257 "Non-nil means display `inferior-octave-buffer' after sending to it."
258 :type 'boolean)
259
260 (defcustom octave-send-line-auto-forward t
261 "Control auto-forward after sending to the inferior Octave process.
262 Non-nil means always go to the next Octave code line after sending."
263 :type 'boolean)
264
265 (defcustom octave-send-echo-input t
266 "Non-nil means echo input sent to the inferior Octave process."
267 :type 'boolean)
268
269 \f
270 ;;; SMIE indentation
271
272 (require 'smie)
273
274 (let-when-compile
275 ((operator-table
276 ;; Use '__operators__' in Octave REPL to get a full list?
277 '((assoc ";" "\n") (assoc ",") ;The doc says they have equal precedence!?
278 (right "=" "+=" "-=" "*=" "/=")
279 (assoc "&&") (assoc "||") ; The doc claims they have equal precedence!?
280 (assoc "&") (assoc "|") ; The doc claims they have equal precedence!?
281 (nonassoc "<" "<=" "==" ">=" ">" "!=" "~=")
282 (nonassoc ":") ;No idea what this is.
283 (assoc "+" "-")
284 (assoc "*" "/" "\\" ".\\" ".*" "./")
285 (nonassoc "'" ".'")
286 (nonassoc "++" "--" "!" "~") ;And unary "+" and "-".
287 (right "^" "**" ".^" ".**")
288 ;; It's not really an operator, but for indentation purposes it
289 ;; could be convenient to treat it as one.
290 (assoc "...")))
291
292 (matchedrules
293 ;; We can't distinguish the first element in a sequence with
294 ;; precedence grammars, so we can't distinguish the condition
295 ;; of the `if' from the subsequent body, for example.
296 ;; This has to be done later in the indentation rules.
297 '(("try" exp "catch" exp "end_try_catch")
298 ("unwind_protect" exp
299 "unwind_protect_cleanup" exp "end_unwind_protect")
300 ("for" exp "endfor")
301 ("parfor" exp "endparfor")
302 ("while" exp "endwhile")
303 ("if" exp "endif")
304 ("if" exp "else" exp "endif")
305 ("if" exp "elseif" exp "else" exp "endif")
306 ("if" exp "elseif" exp "elseif" exp "else" exp "endif")
307 ("switch" exp "case" exp "endswitch")
308 ("switch" exp "case" exp "otherwise" exp "endswitch")
309 ("switch" exp "case" exp "case" exp "otherwise" exp "endswitch")
310 ("function" exp "endfunction")
311 ("enumeration" exp "endenumeration")
312 ("events" exp "endevents")
313 ("methods" exp "endmethods")
314 ("properties" exp "endproperties")
315 ("classdef" exp "endclassdef")
316 ))
317
318 (bnf-table
319 `((atom)
320 ;; FIXME: We don't parse these declarations correctly since
321 ;; SMIE *really* likes to parse "a b = 2 c" as "(a b) = (2 c)".
322 ;; IOW to do it right, we'd need to change octave-smie-*ward-token
323 ;; so that the spaces between vars in var-decls are lexed as
324 ;; something like ",".
325 ;; Doesn't seem worth the trouble/slowdown for now.
326 ;; We could hack smie-rules so as to work around the bad parse,
327 ;; but even that doesn't seem worth the trouble.
328 (var-decls (atom "=" atom)) ;; (var-decls "," var-decls)
329 (single-exp (atom "=" atom))
330 (exp (exp "\n" exp)
331 ;; We need to mention at least one of the operators in this part
332 ;; of the grammar: if the BNF and the operator table have
333 ;; no overlap, SMIE can't know how they relate.
334 (exp ";" exp)
335 ("do" exp "until" single-exp)
336 ,@matchedrules
337 ;; For every rule that ends in "endfoo", add a corresponding
338 ;; rule which uses "end" instead.
339 ,@(mapcar (lambda (rule) (nconc (butlast rule) '("end")))
340 matchedrules)
341 ("global" var-decls) ("persistent" var-decls)
342 ;; These aren't super-important, but having them here
343 ;; makes it easier to extract all keywords.
344 ("break") ("continue") ("return")
345 ;; The following rules do not correspond to valid code AFAIK,
346 ;; but they lead to a grammar that degrades more gracefully
347 ;; on incomplete/incorrect code. It also helps us in
348 ;; computing octave--block-offset-keywords.
349 ("try" exp "end") ("unwind_protect" exp "end")
350 )
351 ;; (fundesc (atom "=" atom))
352 )))
353
354 (defconst octave-smie-grammar
355 (eval-when-compile
356 (smie-prec2->grammar
357 (smie-merge-prec2s
358 (smie-bnf->prec2 bnf-table '((assoc "\n" ";")))
359 (smie-precs->prec2 operator-table)))))
360
361 (defconst octave-operator-regexp
362 (eval-when-compile
363 (regexp-opt (remove "\n" (apply #'append
364 (mapcar #'cdr operator-table)))))))
365
366 ;; Tokenizing needs to be refined so that ";;" is treated as two
367 ;; tokens and also so as to recognize the \n separator (and
368 ;; corresponding continuation lines).
369
370 (defun octave-smie--funcall-p ()
371 "Return non-nil if we're in an expression context. Moves point."
372 (looking-at "[ \t]*("))
373
374 (defun octave-smie--end-index-p ()
375 (let ((ppss (syntax-ppss)))
376 (and (nth 1 ppss)
377 (memq (char-after (nth 1 ppss)) '(?\( ?\[ ?\{)))))
378
379 (defun octave-smie--in-parens-p ()
380 (let ((ppss (syntax-ppss)))
381 (and (nth 1 ppss)
382 (eq ?\( (char-after (nth 1 ppss))))))
383
384 (defun octave-smie-backward-token ()
385 (let ((pos (point)))
386 (forward-comment (- (point)))
387 (cond
388 ((and (not (eq (char-before) ?\;)) ;Coalesce ";" and "\n".
389 (> pos (line-end-position))
390 (if (looking-back octave-continuation-marker-regexp (- (point) 3))
391 (progn
392 (goto-char (match-beginning 0))
393 (forward-comment (- (point)))
394 nil)
395 t)
396 (not (octave-smie--in-parens-p)))
397 (skip-chars-forward " \t")
398 ;; Why bother distinguishing \n and ;?
399 ";") ;;"\n"
400 ((and (looking-back octave-operator-regexp (- (point) 3) 'greedy)
401 ;; Don't mistake a string quote for a transpose.
402 (not (looking-back "\\s\"" (1- (point)))))
403 (goto-char (match-beginning 0))
404 (match-string-no-properties 0))
405 (t
406 (let ((tok (smie-default-backward-token)))
407 (cond
408 ((equal tok "enumeration")
409 (if (save-excursion (smie-default-forward-token)
410 (octave-smie--funcall-p))
411 "enumeration (function)"
412 tok))
413 ((equal tok "end") (if (octave-smie--end-index-p) "end (index)" tok))
414 (t tok)))))))
415
416 (defun octave-smie-forward-token ()
417 (skip-chars-forward " \t")
418 (when (looking-at (eval-when-compile
419 (concat "\\(" octave-continuation-marker-regexp
420 "\\)[ \t]*\\($\\|[%#]\\)")))
421 (goto-char (match-end 1))
422 (forward-comment 1))
423 (cond
424 ((and (looking-at "[%#\n]")
425 (not (or (save-excursion (skip-chars-backward " \t")
426 ;; Only add implicit ; when needed.
427 (or (bolp) (eq (char-before) ?\;)))
428 (octave-smie--in-parens-p))))
429 (if (eolp) (forward-char 1) (forward-comment 1))
430 ;; Why bother distinguishing \n and ;?
431 ";") ;;"\n"
432 ((progn (forward-comment (point-max)) nil))
433 ((looking-at ";[ \t]*\\($\\|[%#]\\)")
434 ;; Combine the ; with the subsequent \n.
435 (goto-char (match-beginning 1))
436 (forward-comment 1)
437 ";")
438 ((and (looking-at octave-operator-regexp)
439 ;; Don't mistake a string quote for a transpose.
440 (not (looking-at "\\s\"")))
441 (goto-char (match-end 0))
442 (match-string-no-properties 0))
443 (t
444 (let ((tok (smie-default-forward-token)))
445 (cond
446 ((equal tok "enumeration")
447 (if (octave-smie--funcall-p)
448 "enumeration (function)"
449 tok))
450 ((equal tok "end") (if (octave-smie--end-index-p) "end (index)" tok))
451 (t tok))))))
452
453 (defconst octave--block-offset-keywords
454 (let* ((end-prec (nth 1 (assoc "end" octave-smie-grammar)))
455 (end-matchers
456 (delq nil
457 (mapcar (lambda (x) (if (eq end-prec (nth 2 x)) (car x)))
458 octave-smie-grammar))))
459 ;; Not sure if it would harm to keep "switch", but the previous code
460 ;; excluded it, presumably because there shouldn't be any code on
461 ;; the lines between "switch" and "case".
462 (delete "switch" end-matchers)))
463
464 (defun octave-smie-rules (kind token)
465 (pcase (cons kind token)
466 ;; We could set smie-indent-basic instead, but that would have two
467 ;; disadvantages:
468 ;; - changes to octave-block-offset wouldn't take effect immediately.
469 ;; - edebug wouldn't show the use of this variable.
470 (`(:elem . basic) octave-block-offset)
471 (`(:list-intro . ,(or "global" "persistent")) t)
472 ;; Since "case" is in the same BNF rules as switch..end, SMIE by default
473 ;; aligns it with "switch".
474 (`(:before . "case") (if (not (smie-rule-sibling-p)) octave-block-offset))
475 (`(:after . ";")
476 (if (apply #'smie-rule-parent-p octave--block-offset-keywords)
477 (smie-rule-parent octave-block-offset)
478 ;; For (invalid) code between switch and case.
479 ;; (if (smie-rule-parent-p "switch") 4)
480 nil))))
481
482 (defun octave-indent-comment ()
483 "A function for `smie-indent-functions' (which see)."
484 (save-excursion
485 (back-to-indentation)
486 (cond
487 ((octave-in-string-or-comment-p) nil)
488 ((looking-at-p "\\(\\s<\\)\\1\\{2,\\}")
489 0)
490 ;; Exclude %{, %} and %!.
491 ((and (looking-at-p "\\s<\\(?:[^{}!]\\|$\\)")
492 (not (looking-at-p "\\(\\s<\\)\\1")))
493 (comment-choose-indent)))))
494
495 \f
496 (defvar octave-reserved-words
497 (delq nil
498 (mapcar (lambda (x)
499 (setq x (car x))
500 (and (stringp x) (string-match "\\`[[:alpha:]]" x) x))
501 octave-smie-grammar))
502 "Reserved words in Octave.")
503
504 (defvar octave-font-lock-keywords
505 (list
506 ;; Fontify all builtin keywords.
507 (cons (concat "\\_<" (regexp-opt octave-reserved-words) "\\_>")
508 'font-lock-keyword-face)
509 ;; Note: 'end' also serves as the last index in an indexing expression,
510 ;; and 'enumerate' is also a function.
511 ;; Ref: http://www.mathworks.com/help/matlab/ref/end.html
512 ;; Ref: http://www.mathworks.com/help/matlab/ref/enumeration.html
513 (list (lambda (limit)
514 (while (re-search-forward "\\_<en\\(?:d\\|umeratio\\(n\\)\\)\\_>"
515 limit 'move)
516 (let ((beg (match-beginning 0))
517 (end (match-end 0)))
518 (unless (octave-in-string-or-comment-p)
519 (when (if (match-end 1)
520 (octave-smie--funcall-p)
521 (octave-smie--end-index-p))
522 (put-text-property beg end 'face nil)))))
523 nil))
524 ;; Fontify all operators.
525 (cons octave-operator-regexp 'font-lock-builtin-face)
526 ;; Fontify all function declarations.
527 (list octave-function-header-regexp
528 '(1 font-lock-keyword-face)
529 '(3 font-lock-function-name-face nil t)))
530 "Additional Octave expressions to highlight.")
531
532 (defun octave-syntax-propertize-function (start end)
533 (goto-char start)
534 (octave-syntax-propertize-sqs end)
535 (funcall (syntax-propertize-rules
536 ("\\\\" (0 (when (eq (nth 3 (save-excursion
537 (syntax-ppss (match-beginning 0))))
538 ?\")
539 (string-to-syntax "\\"))))
540 ;; Try to distinguish the string-quotes from the transpose-quotes.
541 ("\\(?:^\\|[[({,; ]\\)\\('\\)"
542 (1 (prog1 "\"'" (octave-syntax-propertize-sqs end)))))
543 (point) end))
544
545 (defun octave-syntax-propertize-sqs (end)
546 "Propertize the content/end of single-quote strings."
547 (when (eq (nth 3 (syntax-ppss)) ?\')
548 ;; A '..' string.
549 (when (re-search-forward
550 "\\(?:\\=\\|[^']\\)\\(?:''\\)*\\('\\)\\($\\|[^']\\)" end 'move)
551 (goto-char (match-beginning 2))
552 (when (eq (char-before (match-beginning 1)) ?\\)
553 ;; Backslash cannot escape a single quote.
554 (put-text-property (1- (match-beginning 1)) (match-beginning 1)
555 'syntax-table (string-to-syntax ".")))
556 (put-text-property (match-beginning 1) (match-end 1)
557 'syntax-table (string-to-syntax "\"'")))))
558
559 (defvar electric-layout-rules)
560
561 ;;;###autoload
562 (define-derived-mode octave-mode prog-mode "Octave"
563 "Major mode for editing Octave code.
564
565 Octave is a high-level language, primarily intended for numerical
566 computations. It provides a convenient command line interface
567 for solving linear and nonlinear problems numerically. Function
568 definitions can also be stored in files and used in batch mode.
569
570 See Info node `(octave-mode) Using Octave Mode' for more details.
571
572 Key bindings:
573 \\{octave-mode-map}"
574 :abbrev-table octave-abbrev-table
575 :group 'octave
576
577 (smie-setup octave-smie-grammar #'octave-smie-rules
578 :forward-token #'octave-smie-forward-token
579 :backward-token #'octave-smie-backward-token)
580 (setq-local smie-indent-basic 'octave-block-offset)
581 (add-hook 'smie-indent-functions #'octave-indent-comment nil t)
582
583 (setq-local smie-blink-matching-triggers
584 (cons ?\; smie-blink-matching-triggers))
585 (unless octave-blink-matching-block
586 (remove-hook 'post-self-insert-hook #'smie-blink-matching-open 'local))
587
588 (setq-local electric-indent-chars
589 (cons ?\; electric-indent-chars))
590 ;; IIUC matlab-mode takes the opposite approach: it makes RET insert
591 ;; a ";" at those places where it's correct (i.e. outside of parens).
592 (setq-local electric-layout-rules '((?\; . after)))
593
594 (setq-local comment-use-syntax t)
595 (setq-local comment-start octave-comment-start)
596 (setq-local comment-end "")
597 (setq-local comment-start-skip octave-comment-start-skip)
598 (setq-local comment-add 1)
599
600 (setq-local parse-sexp-ignore-comments t)
601 (setq-local paragraph-start (concat "\\s-*$\\|" page-delimiter))
602 (setq-local paragraph-separate paragraph-start)
603 (setq-local paragraph-ignore-fill-prefix t)
604 (setq-local fill-paragraph-function 'octave-fill-paragraph)
605
606 (setq-local fill-nobreak-predicate
607 (lambda () (eq (octave-in-string-p) ?')))
608 (with-no-warnings
609 (if (fboundp 'add-function) ; new in 24.4
610 (add-function :around (local 'comment-line-break-function)
611 #'octave--indent-new-comment-line)
612 (setq-local comment-line-break-function
613 (apply-partially #'octave--indent-new-comment-line
614 #'comment-indent-new-line))))
615
616 (setq font-lock-defaults '(octave-font-lock-keywords))
617
618 (setq-local syntax-propertize-function #'octave-syntax-propertize-function)
619
620 (setq-local imenu-generic-expression octave-mode-imenu-generic-expression)
621 (setq-local imenu-case-fold-search nil)
622
623 (setq-local add-log-current-defun-function #'octave-add-log-current-defun)
624
625 (add-hook 'completion-at-point-functions 'octave-completion-at-point nil t)
626 (add-hook 'before-save-hook 'octave-sync-function-file-names nil t)
627 (setq-local beginning-of-defun-function 'octave-beginning-of-defun)
628 (and octave-font-lock-texinfo-comment (octave-font-lock-texinfo-comment))
629 (add-function :before-until (local 'eldoc-documentation-function)
630 'octave-eldoc-function)
631
632 (easy-menu-add octave-mode-menu))
633
634 \f
635 (defcustom inferior-octave-program "octave"
636 "Program invoked by `inferior-octave'."
637 :type 'string)
638
639 (defcustom inferior-octave-buffer "*Inferior Octave*"
640 "Name of buffer for running an inferior Octave process."
641 :type 'string)
642
643 (defcustom inferior-octave-prompt
644 ;; For Octave >= 3.8, default is always 'octave', see
645 ;; http://hg.savannah.gnu.org/hgweb/octave/rev/708173343c50
646 "\\(?:^octave\\(?:.bin\\|.exe\\)?\\(?:-[.0-9]+\\)?\\(?::[0-9]+\\)?\\|^debug\\|^\\)>+ "
647 "Regexp to match prompts for the inferior Octave process."
648 :type 'regexp)
649
650 (defcustom inferior-octave-prompt-read-only comint-prompt-read-only
651 "If non-nil, the Octave prompt is read only.
652 See `comint-prompt-read-only' for details."
653 :type 'boolean
654 :version "24.4")
655
656 (defcustom inferior-octave-startup-file
657 (let ((n (file-name-nondirectory inferior-octave-program)))
658 (locate-user-emacs-file (format "init_%s.m" n) (format ".emacs-%s" n)))
659 "Name of the inferior Octave startup file.
660 The contents of this file are sent to the inferior Octave process on
661 startup."
662 :type '(choice (const :tag "None" nil) file)
663 :version "24.4")
664
665 (defcustom inferior-octave-startup-args '("-i" "--no-line-editing")
666 "List of command line arguments for the inferior Octave process.
667 For example, for suppressing the startup message and using `traditional'
668 mode, include \"-q\" and \"--traditional\"."
669 :type '(repeat string)
670 :version "24.4")
671
672 (defcustom inferior-octave-mode-hook nil
673 "Hook to be run when Inferior Octave mode is started."
674 :type 'hook)
675
676 (defcustom inferior-octave-error-regexp-alist
677 '(("error:\\s-*\\(.*?\\) at line \\([0-9]+\\), column \\([0-9]+\\)"
678 1 2 3 2 1)
679 ("warning:\\s-*\\([^:\n]+\\):.*at line \\([0-9]+\\), column \\([0-9]+\\)"
680 1 2 3 1 1))
681 "Value for `compilation-error-regexp-alist' in inferior octave."
682 :version "24.4"
683 :type '(repeat (choice (symbol :tag "Predefined symbol")
684 (sexp :tag "Error specification"))))
685
686 (defvar inferior-octave-compilation-font-lock-keywords
687 '(("\\_<PASS\\_>" . compilation-info-face)
688 ("\\_<FAIL\\_>" . compilation-error-face)
689 ("\\_<\\(warning\\):" 1 compilation-warning-face)
690 ("\\_<\\(error\\):" 1 compilation-error-face)
691 ("^\\s-*!!!!!.*\\|^.*failed$" . compilation-error-face))
692 "Value for `compilation-mode-font-lock-keywords' in inferior octave.")
693
694 (defvar inferior-octave-process nil)
695
696 (defvar inferior-octave-mode-map
697 (let ((map (make-sparse-keymap)))
698 (set-keymap-parent map comint-mode-map)
699 (define-key map "\M-." 'octave-find-definition)
700 (define-key map "\t" 'completion-at-point)
701 (define-key map "\C-hd" 'octave-help)
702 (define-key map "\C-ha" 'octave-lookfor)
703 ;; Same as in `shell-mode'.
704 (define-key map "\M-?" 'comint-dynamic-list-filename-completions)
705 (define-key map "\C-c\C-l" 'inferior-octave-dynamic-list-input-ring)
706 (define-key map [menu-bar inout list-history]
707 '("List Input History" . inferior-octave-dynamic-list-input-ring))
708 map)
709 "Keymap used in Inferior Octave mode.")
710
711 (defvar inferior-octave-mode-syntax-table
712 (let ((table (make-syntax-table octave-mode-syntax-table)))
713 table)
714 "Syntax table in use in `inferior-octave-mode' buffers.")
715
716 (defvar inferior-octave-font-lock-keywords
717 (list
718 (cons inferior-octave-prompt 'font-lock-type-face))
719 ;; Could certainly do more font locking in inferior Octave ...
720 "Additional expressions to highlight in Inferior Octave mode.")
721
722 (defvar inferior-octave-output-list nil)
723 (defvar inferior-octave-output-string nil)
724 (defvar inferior-octave-receive-in-progress nil)
725
726 (define-obsolete-variable-alias 'inferior-octave-startup-hook
727 'inferior-octave-mode-hook "24.4")
728
729 (defvar inferior-octave-dynamic-complete-functions
730 '(inferior-octave-completion-at-point comint-filename-completion)
731 "List of functions called to perform completion for inferior Octave.
732 This variable is used to initialize `comint-dynamic-complete-functions'
733 in the Inferior Octave buffer.")
734
735 (defvar info-lookup-mode)
736 (defvar compilation-error-regexp-alist)
737 (defvar compilation-mode-font-lock-keywords)
738
739 (declare-function compilation-forget-errors "compile" ())
740
741 (defun inferior-octave-process-live-p ()
742 (process-live-p inferior-octave-process))
743
744 (define-derived-mode inferior-octave-mode comint-mode "Inferior Octave"
745 "Major mode for interacting with an inferior Octave process.
746
747 See Info node `(octave-mode) Running Octave from Within Emacs' for more
748 details.
749
750 Key bindings:
751 \\{inferior-octave-mode-map}"
752 :abbrev-table octave-abbrev-table
753 :group 'octave
754
755 (setq comint-prompt-regexp inferior-octave-prompt)
756
757 (setq-local comment-use-syntax t)
758 (setq-local comment-start octave-comment-start)
759 (setq-local comment-end "")
760 (setq comment-column 32)
761 (setq-local comment-start-skip octave-comment-start-skip)
762
763 (setq font-lock-defaults '(inferior-octave-font-lock-keywords nil nil))
764
765 (setq-local info-lookup-mode 'octave-mode)
766 (setq-local eldoc-documentation-function 'octave-eldoc-function)
767
768 (setq-local comint-input-ring-file-name
769 (or (getenv "OCTAVE_HISTFILE") "~/.octave_hist"))
770 (setq-local comint-input-ring-size
771 (string-to-number (or (getenv "OCTAVE_HISTSIZE") "1024")))
772 (comint-read-input-ring t)
773 (setq-local comint-dynamic-complete-functions
774 inferior-octave-dynamic-complete-functions)
775 (setq-local comint-prompt-read-only inferior-octave-prompt-read-only)
776 (add-hook 'comint-input-filter-functions
777 'inferior-octave-directory-tracker nil t)
778 ;; http://thread.gmane.org/gmane.comp.gnu.octave.general/48572
779 (add-hook 'window-configuration-change-hook
780 'inferior-octave-track-window-width-change nil t)
781 (setq-local compilation-error-regexp-alist inferior-octave-error-regexp-alist)
782 (setq-local compilation-mode-font-lock-keywords
783 inferior-octave-compilation-font-lock-keywords)
784 (compilation-shell-minor-mode 1)
785 (compilation-forget-errors))
786
787 ;;;###autoload
788 (defun inferior-octave (&optional arg)
789 "Run an inferior Octave process, I/O via `inferior-octave-buffer'.
790 This buffer is put in Inferior Octave mode. See `inferior-octave-mode'.
791
792 Unless ARG is non-nil, switches to this buffer.
793
794 The elements of the list `inferior-octave-startup-args' are sent as
795 command line arguments to the inferior Octave process on startup.
796
797 Additional commands to be executed on startup can be provided either in
798 the file specified by `inferior-octave-startup-file' or by the default
799 startup file, `~/.emacs-octave'."
800 (interactive "P")
801 (let ((buffer (get-buffer-create inferior-octave-buffer)))
802 (unless arg
803 (pop-to-buffer buffer))
804 (unless (comint-check-proc buffer)
805 (with-current-buffer buffer
806 (inferior-octave-startup)
807 (inferior-octave-mode)))
808 buffer))
809
810 ;;;###autoload
811 (defalias 'run-octave 'inferior-octave)
812
813 (defun inferior-octave-startup ()
814 "Start an inferior Octave process."
815 (let ((proc (comint-exec-1
816 (substring inferior-octave-buffer 1 -1)
817 inferior-octave-buffer
818 inferior-octave-program
819 (append
820 inferior-octave-startup-args
821 ;; --no-gui is introduced in Octave > 3.7
822 (and (not (member "--no-gui" inferior-octave-startup-args))
823 (zerop (process-file inferior-octave-program
824 nil nil nil "--no-gui" "--help"))
825 '("--no-gui"))))))
826 (set-process-filter proc 'inferior-octave-output-digest)
827 (setq inferior-octave-process proc
828 inferior-octave-output-list nil
829 inferior-octave-output-string nil
830 inferior-octave-receive-in-progress t)
831
832 ;; This may look complicated ... However, we need to make sure that
833 ;; we additional startup code only AFTER Octave is ready (otherwise,
834 ;; output may be mixed up). Hence, we need to digest the Octave
835 ;; output to see when it issues a prompt.
836 (while inferior-octave-receive-in-progress
837 (unless (inferior-octave-process-live-p)
838 ;; Spit out the error messages.
839 (when inferior-octave-output-list
840 (princ (concat (mapconcat 'identity inferior-octave-output-list "\n")
841 "\n")
842 (process-mark inferior-octave-process)))
843 (error "Process `%s' died" inferior-octave-process))
844 (accept-process-output inferior-octave-process))
845 (goto-char (point-max))
846 (set-marker (process-mark proc) (point))
847 (insert-before-markers
848 (concat
849 (if (not (bobp)) "\f\n")
850 (if inferior-octave-output-list
851 (concat (mapconcat
852 'identity inferior-octave-output-list "\n")
853 "\n"))))
854
855 ;; An empty secondary prompt, as e.g. obtained by '--braindead',
856 ;; means trouble.
857 (inferior-octave-send-list-and-digest (list "PS2\n"))
858 (when (string-match "\\(PS2\\|ans\\) = *$"
859 (car inferior-octave-output-list))
860 (inferior-octave-send-list-and-digest (list "PS2 ('> ');\n")))
861
862 (inferior-octave-send-list-and-digest
863 (list "disp (getenv ('OCTAVE_SRCDIR'))\n"))
864 (process-put proc 'octave-srcdir
865 (unless (equal (car inferior-octave-output-list) "")
866 (car inferior-octave-output-list)))
867
868 ;; O.K., now we are ready for the Inferior Octave startup commands.
869 (inferior-octave-send-list-and-digest
870 (list "more off;\n"
871 (unless (equal inferior-octave-output-string ">> ")
872 ;; See http://hg.savannah.gnu.org/hgweb/octave/rev/708173343c50
873 "PS1 ('octave> ');\n")
874 (when (and inferior-octave-startup-file
875 (file-exists-p inferior-octave-startup-file))
876 (format "source ('%s');\n" inferior-octave-startup-file))))
877 (when inferior-octave-output-list
878 (insert-before-markers
879 (mapconcat 'identity inferior-octave-output-list "\n")))
880
881 ;; And finally, everything is back to normal.
882 (set-process-filter proc 'comint-output-filter)
883 ;; Just in case, to be sure a cd in the startup file won't have
884 ;; detrimental effects.
885 (with-demoted-errors (inferior-octave-resync-dirs))
886 ;; Generate a proper prompt, which is critical to
887 ;; `comint-history-isearch-backward-regexp'. Bug#14433.
888 (comint-send-string proc "\n")))
889
890 (defun inferior-octave-completion-table ()
891 (completion-table-with-cache
892 (lambda (command)
893 (inferior-octave-send-list-and-digest
894 (list (format "completion_matches ('%s');\n" command)))
895 (delete-consecutive-dups
896 (sort inferior-octave-output-list 'string-lessp)))))
897
898 (defun inferior-octave-completion-at-point ()
899 "Return the data to complete the Octave symbol at point."
900 ;; http://debbugs.gnu.org/14300
901 (unless (string-match-p "/" (or (comint--match-partial-filename) ""))
902 (let ((beg (save-excursion
903 (skip-syntax-backward "w_" (comint-line-beginning-position))
904 (point)))
905 (end (point)))
906 (when (and beg (> end beg))
907 (list beg end (completion-table-in-turn
908 (inferior-octave-completion-table)
909 'comint-completion-file-name-table))))))
910
911 (define-obsolete-function-alias 'inferior-octave-complete
912 'completion-at-point "24.1")
913
914 (defun inferior-octave-dynamic-list-input-ring ()
915 "List the buffer's input history in a help buffer."
916 ;; We cannot use `comint-dynamic-list-input-ring', because it replaces
917 ;; "completion" by "history reference" ...
918 (interactive)
919 (if (or (not (ring-p comint-input-ring))
920 (ring-empty-p comint-input-ring))
921 (message "No history")
922 (let ((history nil)
923 (history-buffer " *Input History*")
924 (index (1- (ring-length comint-input-ring)))
925 (conf (current-window-configuration)))
926 ;; We have to build up a list ourselves from the ring vector.
927 (while (>= index 0)
928 (setq history (cons (ring-ref comint-input-ring index) history)
929 index (1- index)))
930 ;; Change "completion" to "history reference"
931 ;; to make the display accurate.
932 (with-output-to-temp-buffer history-buffer
933 (display-completion-list history)
934 (set-buffer history-buffer))
935 (message "Hit space to flush")
936 (let ((ch (read-event)))
937 (if (eq ch ?\ )
938 (set-window-configuration conf)
939 (push ch unread-command-events))))))
940
941 (defun inferior-octave-output-digest (_proc string)
942 "Special output filter for the inferior Octave process.
943 Save all output between newlines into `inferior-octave-output-list', and
944 the rest to `inferior-octave-output-string'."
945 (setq string (concat inferior-octave-output-string string))
946 (while (string-match "\n" string)
947 (setq inferior-octave-output-list
948 (append inferior-octave-output-list
949 (list (substring string 0 (match-beginning 0))))
950 string (substring string (match-end 0))))
951 (if (string-match inferior-octave-prompt string)
952 (setq inferior-octave-receive-in-progress nil))
953 (setq inferior-octave-output-string string))
954
955 (defun inferior-octave-check-process ()
956 (or (inferior-octave-process-live-p)
957 (error (substitute-command-keys
958 "No inferior octave process running. Type \\[run-octave]"))))
959
960 (defun inferior-octave-send-list-and-digest (list)
961 "Send LIST to the inferior Octave process and digest the output.
962 The elements of LIST have to be strings and are sent one by one. All
963 output is passed to the filter `inferior-octave-output-digest'."
964 (inferior-octave-check-process)
965 (let* ((proc inferior-octave-process)
966 (filter (process-filter proc))
967 string)
968 (set-process-filter proc 'inferior-octave-output-digest)
969 (setq inferior-octave-output-list nil)
970 (unwind-protect
971 (while (setq string (car list))
972 (setq inferior-octave-output-string nil
973 inferior-octave-receive-in-progress t)
974 (comint-send-string proc string)
975 (while inferior-octave-receive-in-progress
976 (accept-process-output proc))
977 (setq list (cdr list)))
978 (set-process-filter proc filter))))
979
980 (defvar inferior-octave-directory-tracker-resync nil)
981 (make-variable-buffer-local 'inferior-octave-directory-tracker-resync)
982
983 (defun inferior-octave-directory-tracker (string)
984 "Tracks `cd' commands issued to the inferior Octave process.
985 Use \\[inferior-octave-resync-dirs] to resync if Emacs gets confused."
986 (when inferior-octave-directory-tracker-resync
987 (or (inferior-octave-resync-dirs 'noerror)
988 (setq inferior-octave-directory-tracker-resync nil)))
989 (cond
990 ((string-match "^[ \t]*cd[ \t;]*$" string)
991 (cd "~"))
992 ((string-match "^[ \t]*cd[ \t]+\\([^ \t\n;]*\\)[ \t\n;]*" string)
993 (condition-case err
994 (cd (match-string 1 string))
995 (error (setq inferior-octave-directory-tracker-resync t)
996 (message "%s: `%s'"
997 (error-message-string err)
998 (match-string 1 string)))))))
999
1000 (defun inferior-octave-resync-dirs (&optional noerror)
1001 "Resync the buffer's idea of the current directory.
1002 This command queries the inferior Octave process about its current
1003 directory and makes this the current buffer's default directory."
1004 (interactive)
1005 (inferior-octave-send-list-and-digest '("disp (pwd ())\n"))
1006 (condition-case err
1007 (progn
1008 (cd (car inferior-octave-output-list))
1009 t)
1010 (error (unless noerror (signal (car err) (cdr err))))))
1011
1012 (defcustom inferior-octave-minimal-columns 80
1013 "The minimal column width for the inferior Octave process."
1014 :type 'integer
1015 :version "24.4")
1016
1017 (defvar inferior-octave-last-column-width nil)
1018
1019 (defun inferior-octave-track-window-width-change ()
1020 ;; http://thread.gmane.org/gmane.comp.gnu.octave.general/48572
1021 (let ((width (max inferior-octave-minimal-columns (window-width))))
1022 (unless (eq inferior-octave-last-column-width width)
1023 (setq-local inferior-octave-last-column-width width)
1024 (when (inferior-octave-process-live-p)
1025 (inferior-octave-send-list-and-digest
1026 (list (format "putenv ('COLUMNS', '%s');\n" width)))))))
1027
1028 \f
1029 ;;; Miscellaneous useful functions
1030
1031 (defun octave-in-comment-p ()
1032 "Return non-nil if point is inside an Octave comment."
1033 (nth 4 (syntax-ppss)))
1034
1035 (defun octave-in-string-p ()
1036 "Return non-nil if point is inside an Octave string."
1037 (nth 3 (syntax-ppss)))
1038
1039 (defun octave-in-string-or-comment-p ()
1040 "Return non-nil if point is inside an Octave string or comment."
1041 (nth 8 (syntax-ppss)))
1042
1043 (defun octave-looking-at-kw (regexp)
1044 "Like `looking-at', but sets `case-fold-search' nil."
1045 (let ((case-fold-search nil))
1046 (looking-at regexp)))
1047
1048 (defun octave-maybe-insert-continuation-string ()
1049 (if (or (octave-in-comment-p)
1050 (save-excursion
1051 (beginning-of-line)
1052 (looking-at octave-continuation-regexp)))
1053 nil
1054 (delete-horizontal-space)
1055 (insert (concat " " octave-continuation-string))))
1056
1057 (defun octave-completing-read ()
1058 (let ((def (or (thing-at-point 'symbol)
1059 (save-excursion
1060 (skip-syntax-backward "-(")
1061 (thing-at-point 'symbol)))))
1062 (completing-read
1063 (format (if def "Function (default %s): "
1064 "Function: ") def)
1065 (inferior-octave-completion-table)
1066 nil nil nil nil def)))
1067
1068 (defun octave-goto-function-definition (fn)
1069 "Go to the function definition of FN in current buffer."
1070 (let ((search
1071 (lambda (re sub)
1072 (let ((orig (point)) found)
1073 (goto-char (point-min))
1074 (while (and (not found) (re-search-forward re nil t))
1075 (when (and (equal (match-string sub) fn)
1076 (not (nth 8 (syntax-ppss))))
1077 (setq found t)))
1078 (unless found (goto-char orig))
1079 found))))
1080 (pcase (and buffer-file-name (file-name-extension buffer-file-name))
1081 (`"cc" (funcall search
1082 "\\_<DEFUN\\(?:_DLD\\)?\\s-*(\\s-*\\(\\(?:\\sw\\|\\s_\\)+\\)" 1))
1083 (_ (funcall search octave-function-header-regexp 3)))))
1084
1085 (defun octave-function-file-p ()
1086 "Return non-nil if the first token is \"function\".
1087 The value is (START END NAME-START NAME-END) of the function."
1088 (save-excursion
1089 (goto-char (point-min))
1090 (when (equal (funcall smie-forward-token-function) "function")
1091 (forward-word -1)
1092 (let* ((start (point))
1093 (end (progn (forward-sexp 1) (point)))
1094 (name (when (progn
1095 (goto-char start)
1096 (re-search-forward octave-function-header-regexp
1097 end t))
1098 (list (match-beginning 3) (match-end 3)))))
1099 (cons start (cons end name))))))
1100
1101 ;; Like forward-comment but stop at non-comment blank
1102 (defun octave-skip-comment-forward (limit)
1103 (let ((ppss (syntax-ppss)))
1104 (if (nth 4 ppss)
1105 (goto-char (nth 8 ppss))
1106 (goto-char (or (comment-search-forward limit t) (point)))))
1107 (while (and (< (point) limit) (looking-at-p "\\s<"))
1108 (forward-comment 1)))
1109
1110 ;;; First non-copyright comment block
1111 (defun octave-function-file-comment ()
1112 "Beginning and end positions of the function file comment."
1113 (save-excursion
1114 (goto-char (point-min))
1115 ;; Copyright block: octave/libinterp/parse-tree/lex.ll around line 1634
1116 (while (save-excursion
1117 (when (comment-search-forward (point-max) t)
1118 (when (eq (char-after) ?\{) ; case of block comment
1119 (forward-char 1))
1120 (skip-syntax-forward "-")
1121 (let ((case-fold-search t))
1122 (looking-at-p "\\(?:copyright\\|author\\)\\_>"))))
1123 (octave-skip-comment-forward (point-max)))
1124 (let ((beg (comment-search-forward (point-max) t)))
1125 (when beg
1126 (goto-char beg)
1127 (octave-skip-comment-forward (point-max))
1128 (list beg (point))))))
1129
1130 (defun octave-sync-function-file-names ()
1131 "Ensure function name agree with function file name.
1132 See Info node `(octave)Function Files'."
1133 (interactive)
1134 (when buffer-file-name
1135 (pcase-let ((`(,start ,_end ,name-start ,name-end)
1136 (octave-function-file-p)))
1137 (when (and start name-start)
1138 (let* ((func (buffer-substring name-start name-end))
1139 (file (file-name-sans-extension
1140 (file-name-nondirectory buffer-file-name)))
1141 (help-form (format-message "\
1142 a: Use function name `%s'
1143 b: Use file name `%s'
1144 q: Don't fix\n" func file))
1145 (c (unless (equal file func)
1146 (save-window-excursion
1147 (help-form-show)
1148 (read-char-choice
1149 "Which name to use? (a/b/q) " '(?a ?b ?q))))))
1150 (pcase c
1151 (`?a (let ((newname (expand-file-name
1152 (concat func (file-name-extension
1153 buffer-file-name t)))))
1154 (when (or (not (file-exists-p newname))
1155 (yes-or-no-p
1156 (format "Target file %s exists; proceed? " newname)))
1157 (when (file-exists-p buffer-file-name)
1158 (rename-file buffer-file-name newname t))
1159 (set-visited-file-name newname))))
1160 (`?b (save-excursion
1161 (goto-char name-start)
1162 (delete-region name-start name-end)
1163 (insert file)))))))))
1164
1165 (defun octave-update-function-file-comment (beg end)
1166 "Query replace function names in function file comment."
1167 (interactive
1168 (progn
1169 (barf-if-buffer-read-only)
1170 (if (use-region-p)
1171 (list (region-beginning) (region-end))
1172 (or (octave-function-file-comment)
1173 (error "No function file comment found")))))
1174 (save-excursion
1175 (let* ((bounds (or (octave-function-file-p)
1176 (error "Not in a function file buffer")))
1177 (func (if (cddr bounds)
1178 (apply #'buffer-substring (cddr bounds))
1179 (error "Function name not found")))
1180 (old-func (progn
1181 (goto-char beg)
1182 (when (re-search-forward
1183 "[=}]\\s-*\\(\\(?:\\sw\\|\\s_\\)+\\)\\_>"
1184 (min (line-end-position 4) end)
1185 t)
1186 (match-string 1))))
1187 (old-func (read-string (format (if old-func
1188 "Name to replace (default %s): "
1189 "Name to replace: ")
1190 old-func)
1191 nil nil old-func)))
1192 (if (and func old-func (not (equal func old-func)))
1193 (perform-replace old-func func 'query
1194 nil 'delimited nil nil beg end)
1195 (message "Function names match")))))
1196
1197 (defface octave-function-comment-block
1198 '((t (:inherit font-lock-doc-face)))
1199 "Face used to highlight function comment block.")
1200
1201 (eval-when-compile (require 'texinfo))
1202
1203 (defun octave-font-lock-texinfo-comment ()
1204 (let ((kws
1205 (eval-when-compile
1206 (delq nil (mapcar
1207 (lambda (kw)
1208 (if (numberp (nth 1 kw))
1209 `(,(nth 0 kw) ,(nth 1 kw) ,(nth 2 kw) prepend)
1210 (message "Ignoring Texinfo highlight: %S" kw)))
1211 texinfo-font-lock-keywords)))))
1212 (font-lock-add-keywords
1213 nil
1214 `((,(lambda (limit)
1215 (while (and (< (point) limit)
1216 (search-forward "-*- texinfo -*-" limit t)
1217 (octave-in-comment-p))
1218 (let ((beg (nth 8 (syntax-ppss)))
1219 (end (progn
1220 (octave-skip-comment-forward (point-max))
1221 (point))))
1222 (put-text-property beg end 'font-lock-multiline t)
1223 (font-lock-prepend-text-property
1224 beg end 'face 'octave-function-comment-block)
1225 (dolist (kw kws)
1226 (goto-char beg)
1227 (while (re-search-forward (car kw) end 'move)
1228 (font-lock-apply-highlight (cdr kw))))))
1229 nil)))
1230 'append)))
1231
1232 \f
1233 ;;; Indentation
1234
1235 (defun octave-indent-new-comment-line (&optional soft)
1236 "Break Octave line at point, continuing comment if within one.
1237 Insert `octave-continuation-string' before breaking the line
1238 unless inside a list. Signal an error if within a single-quoted
1239 string."
1240 (interactive)
1241 (funcall comment-line-break-function soft))
1242
1243 (defun octave--indent-new-comment-line (orig &rest args)
1244 (cond
1245 ((octave-in-comment-p) nil)
1246 ((eq (octave-in-string-p) ?')
1247 (error "Cannot split a single-quoted string"))
1248 ((eq (octave-in-string-p) ?\")
1249 (insert octave-continuation-string))
1250 (t
1251 (delete-horizontal-space)
1252 (unless (and (cadr (syntax-ppss))
1253 (eq (char-after (cadr (syntax-ppss))) ?\())
1254 (insert " " octave-continuation-string))))
1255 (apply orig args)
1256 (indent-according-to-mode))
1257
1258 (define-obsolete-function-alias
1259 'octave-indent-defun 'prog-indent-sexp "24.4")
1260
1261 \f
1262 ;;; Motion
1263 (defun octave-next-code-line (&optional arg)
1264 "Move ARG lines of Octave code forward (backward if ARG is negative).
1265 Skips past all empty and comment lines. Default for ARG is 1.
1266
1267 On success, return 0. Otherwise, go as far as possible and return -1."
1268 (interactive "p")
1269 (or arg (setq arg 1))
1270 (beginning-of-line)
1271 (let ((n 0)
1272 (inc (if (> arg 0) 1 -1)))
1273 (while (and (/= arg 0) (= n 0))
1274 (setq n (forward-line inc))
1275 (while (and (= n 0)
1276 (looking-at "\\s-*\\($\\|\\s<\\)"))
1277 (setq n (forward-line inc)))
1278 (setq arg (- arg inc)))
1279 n))
1280
1281 (defun octave-previous-code-line (&optional arg)
1282 "Move ARG lines of Octave code backward (forward if ARG is negative).
1283 Skips past all empty and comment lines. Default for ARG is 1.
1284
1285 On success, return 0. Otherwise, go as far as possible and return -1."
1286 (interactive "p")
1287 (or arg (setq arg 1))
1288 (octave-next-code-line (- arg)))
1289
1290 (defun octave-beginning-of-line ()
1291 "Move point to beginning of current Octave line.
1292 If on an empty or comment line, go to the beginning of that line.
1293 Otherwise, move backward to the beginning of the first Octave code line
1294 which is not inside a continuation statement, i.e., which does not
1295 follow a code line ending with `...' or is inside an open
1296 parenthesis list."
1297 (interactive)
1298 (beginning-of-line)
1299 (unless (looking-at "\\s-*\\($\\|\\s<\\)")
1300 (while (or (when (cadr (syntax-ppss))
1301 (goto-char (cadr (syntax-ppss)))
1302 (beginning-of-line)
1303 t)
1304 (and (or (looking-at "\\s-*\\($\\|\\s<\\)")
1305 (save-excursion
1306 (if (zerop (octave-previous-code-line))
1307 (looking-at octave-continuation-regexp))))
1308 (zerop (forward-line -1)))))))
1309
1310 (defun octave-end-of-line ()
1311 "Move point to end of current Octave line.
1312 If on an empty or comment line, go to the end of that line.
1313 Otherwise, move forward to the end of the first Octave code line which
1314 does not end with `...' or is inside an open parenthesis list."
1315 (interactive)
1316 (end-of-line)
1317 (unless (save-excursion
1318 (beginning-of-line)
1319 (looking-at "\\s-*\\($\\|\\s<\\)"))
1320 (while (or (when (cadr (syntax-ppss))
1321 (condition-case nil
1322 (progn
1323 (up-list 1)
1324 (end-of-line)
1325 t)
1326 (error nil)))
1327 (and (save-excursion
1328 (beginning-of-line)
1329 (or (looking-at "\\s-*\\($\\|\\s<\\)")
1330 (looking-at octave-continuation-regexp)))
1331 (zerop (forward-line 1)))))
1332 (end-of-line)))
1333
1334 (defun octave-mark-block ()
1335 "Put point at the beginning of this Octave block, mark at the end.
1336 The block marked is the one that contains point or follows point."
1337 (interactive)
1338 (if (and (looking-at "\\sw\\|\\s_")
1339 (looking-back "\\sw\\|\\s_" (1- (point))))
1340 (skip-syntax-forward "w_"))
1341 (unless (or (looking-at "\\s(")
1342 (save-excursion
1343 (let* ((token (funcall smie-forward-token-function))
1344 (level (assoc token smie-grammar)))
1345 (and level (not (numberp (cadr level)))))))
1346 (backward-up-list 1))
1347 (mark-sexp))
1348
1349 (defun octave-beginning-of-defun (&optional arg)
1350 "Octave-specific `beginning-of-defun-function' (which see)."
1351 (or arg (setq arg 1))
1352 ;; Move out of strings or comments.
1353 (when (octave-in-string-or-comment-p)
1354 (goto-char (octave-in-string-or-comment-p)))
1355 (letrec ((orig (point))
1356 (toplevel (lambda (pos)
1357 (condition-case nil
1358 (progn
1359 (backward-up-list 1)
1360 (funcall toplevel (point)))
1361 (scan-error pos)))))
1362 (goto-char (funcall toplevel (point)))
1363 (when (and (> arg 0) (/= orig (point)))
1364 (setq arg (1- arg)))
1365 (forward-sexp (- arg))
1366 (and (< arg 0) (forward-sexp -1))
1367 (/= orig (point))))
1368
1369 (defun octave-fill-paragraph (&optional _arg)
1370 "Fill paragraph of Octave code, handling Octave comments."
1371 ;; FIXME: difference with generic fill-paragraph:
1372 ;; - code lines are only split, never joined.
1373 ;; - \n that end comments are never removed.
1374 ;; - insert continuation marker when splitting code lines.
1375 (interactive "P")
1376 (save-excursion
1377 (let ((end (progn (forward-paragraph) (copy-marker (point) t)))
1378 (beg (progn
1379 (forward-paragraph -1)
1380 (skip-chars-forward " \t\n")
1381 (beginning-of-line)
1382 (point)))
1383 (cfc (current-fill-column))
1384 comment-prefix)
1385 (goto-char beg)
1386 (while (< (point) end)
1387 (condition-case nil
1388 (indent-according-to-mode)
1389 (error nil))
1390 (move-to-column cfc)
1391 ;; First check whether we need to combine non-empty comment lines
1392 (if (and (< (current-column) cfc)
1393 (octave-in-comment-p)
1394 (not (save-excursion
1395 (beginning-of-line)
1396 (looking-at "^\\s-*\\s<+\\s-*$"))))
1397 ;; This is a nonempty comment line which does not extend
1398 ;; past the fill column. If it is followed by a nonempty
1399 ;; comment line with the same comment prefix, try to
1400 ;; combine them, and repeat this until either we reach the
1401 ;; fill-column or there is nothing more to combine.
1402 (progn
1403 ;; Get the comment prefix
1404 (save-excursion
1405 (beginning-of-line)
1406 (while (and (re-search-forward "\\s<+")
1407 (not (octave-in-comment-p))))
1408 (setq comment-prefix (match-string 0)))
1409 ;; And keep combining ...
1410 (while (and (< (current-column) cfc)
1411 (save-excursion
1412 (forward-line 1)
1413 (and (looking-at
1414 (concat "^\\s-*"
1415 comment-prefix
1416 "\\S<"))
1417 (not (looking-at
1418 (concat "^\\s-*"
1419 comment-prefix
1420 "\\s-*$"))))))
1421 (delete-char 1)
1422 (re-search-forward comment-prefix)
1423 (delete-region (match-beginning 0) (match-end 0))
1424 (fixup-whitespace)
1425 (move-to-column cfc))))
1426 ;; We might also try to combine continued code lines> Perhaps
1427 ;; some other time ...
1428 (skip-chars-forward "^ \t\n")
1429 (delete-horizontal-space)
1430 (if (or (< (current-column) cfc)
1431 (and (= (current-column) cfc) (eolp)))
1432 (forward-line 1)
1433 (if (not (eolp)) (insert " "))
1434 (or (funcall normal-auto-fill-function)
1435 (forward-line 1))))
1436 t)))
1437
1438 (defun octave-completion-at-point ()
1439 "Find the text to complete and the corresponding table."
1440 (let* ((beg (save-excursion (skip-syntax-backward "w_") (point)))
1441 (end (point)))
1442 (if (< beg (point))
1443 ;; Extend region past point, if applicable.
1444 (save-excursion (skip-syntax-forward "w_")
1445 (setq end (point))))
1446 (when (> end beg)
1447 (list beg end (or (and (inferior-octave-process-live-p)
1448 (inferior-octave-completion-table))
1449 octave-reserved-words)))))
1450
1451 (define-obsolete-function-alias 'octave-complete-symbol
1452 'completion-at-point "24.1")
1453
1454 (defun octave-add-log-current-defun ()
1455 "A function for `add-log-current-defun-function' (which see)."
1456 (save-excursion
1457 (end-of-line)
1458 (and (beginning-of-defun)
1459 (re-search-forward octave-function-header-regexp
1460 (line-end-position) t)
1461 (match-string 3))))
1462
1463 \f
1464 ;;; Electric characters && friends
1465 (define-skeleton octave-insert-defun
1466 "Insert an Octave function skeleton.
1467 Prompt for the function's name, arguments and return values (to be
1468 entered without parens)."
1469 (let* ((defname (file-name-sans-extension (buffer-name)))
1470 (name (read-string (format "Function name (default %s): " defname)
1471 nil nil defname))
1472 (args (read-string "Arguments: "))
1473 (vals (read-string "Return values: ")))
1474 (format "%s%s (%s)"
1475 (cond
1476 ((string-equal vals "") vals)
1477 ((string-match "[ ,]" vals) (concat "[" vals "] = "))
1478 (t (concat vals " = ")))
1479 name
1480 args))
1481 \n octave-block-comment-start "usage: " str \n
1482 octave-block-comment-start '(delete-horizontal-space) \n
1483 octave-block-comment-start '(delete-horizontal-space) \n
1484 "function " > str \n
1485 _ \n
1486 "endfunction" > \n)
1487
1488 ;;; Communication with the inferior Octave process
1489 (defun octave-kill-process ()
1490 "Kill inferior Octave process and its buffer."
1491 (interactive)
1492 (when (and (buffer-live-p (get-buffer inferior-octave-buffer))
1493 (or (yes-or-no-p (format "Kill %S and its buffer? "
1494 inferior-octave-process))
1495 (user-error "Aborted")))
1496 (when (inferior-octave-process-live-p)
1497 (set-process-query-on-exit-flag inferior-octave-process nil)
1498 (process-send-string inferior-octave-process "quit;\n")
1499 (accept-process-output inferior-octave-process))
1500 (kill-buffer inferior-octave-buffer)))
1501
1502 (defun octave-show-process-buffer ()
1503 "Make sure that `inferior-octave-buffer' is displayed."
1504 (interactive)
1505 (if (get-buffer inferior-octave-buffer)
1506 (display-buffer inferior-octave-buffer)
1507 (message "No buffer named %s" inferior-octave-buffer)))
1508
1509 (defun octave-hide-process-buffer ()
1510 "Delete all windows that display `inferior-octave-buffer'."
1511 (interactive)
1512 (if (get-buffer inferior-octave-buffer)
1513 (delete-windows-on inferior-octave-buffer)
1514 (message "No buffer named %s" inferior-octave-buffer)))
1515
1516 (defun octave-source-file (file)
1517 "Execute FILE in the inferior Octave process.
1518 This is done using Octave's source function. FILE defaults to
1519 current buffer file unless called with a prefix arg \\[universal-argument]."
1520 (interactive (list (or (and (not current-prefix-arg) buffer-file-name)
1521 (read-file-name "File: " nil nil t))))
1522 (or (stringp file)
1523 (signal 'wrong-type-argument (list 'stringp file)))
1524 (inferior-octave t)
1525 (with-current-buffer inferior-octave-buffer
1526 (comint-send-string inferior-octave-process
1527 (format "source '%s'\n" file))))
1528
1529 (defun octave-send-region (beg end)
1530 "Send current region to the inferior Octave process."
1531 (interactive "r")
1532 (inferior-octave t)
1533 (let ((proc inferior-octave-process)
1534 (string (buffer-substring-no-properties beg end))
1535 line)
1536 (with-current-buffer inferior-octave-buffer
1537 ;; http://lists.gnu.org/archive/html/emacs-devel/2013-10/msg00095.html
1538 (compilation-forget-errors)
1539 (setq inferior-octave-output-list nil)
1540 (while (not (string-equal string ""))
1541 (if (string-match "\n" string)
1542 (setq line (substring string 0 (match-beginning 0))
1543 string (substring string (match-end 0)))
1544 (setq line string string ""))
1545 (setq inferior-octave-receive-in-progress t)
1546 (inferior-octave-send-list-and-digest (list (concat line "\n")))
1547 (while inferior-octave-receive-in-progress
1548 (accept-process-output proc))
1549 (insert-before-markers
1550 (mapconcat 'identity
1551 (append
1552 (if octave-send-echo-input (list line) (list ""))
1553 inferior-octave-output-list
1554 (list inferior-octave-output-string))
1555 "\n")))))
1556 (if octave-send-show-buffer
1557 (display-buffer inferior-octave-buffer)))
1558
1559 (defun octave-send-buffer ()
1560 "Send current buffer to the inferior Octave process."
1561 (interactive)
1562 (octave-send-region (point-min) (point-max)))
1563
1564 (defun octave-send-block ()
1565 "Send current Octave block to the inferior Octave process."
1566 (interactive)
1567 (save-excursion
1568 (octave-mark-block)
1569 (octave-send-region (point) (mark))))
1570
1571 (defun octave-send-defun ()
1572 "Send current Octave function to the inferior Octave process."
1573 (interactive)
1574 (save-excursion
1575 (mark-defun)
1576 (octave-send-region (point) (mark))))
1577
1578 (defun octave-send-line (&optional arg)
1579 "Send current Octave code line to the inferior Octave process.
1580 With positive prefix ARG, send that many lines.
1581 If `octave-send-line-auto-forward' is non-nil, go to the next unsent
1582 code line."
1583 (interactive "P")
1584 (or arg (setq arg 1))
1585 (if (> arg 0)
1586 (let (beg end)
1587 (beginning-of-line)
1588 (setq beg (point))
1589 (octave-next-code-line (- arg 1))
1590 (end-of-line)
1591 (setq end (point))
1592 (if octave-send-line-auto-forward
1593 (octave-next-code-line 1))
1594 (octave-send-region beg end))))
1595
1596 (defun octave-eval-print-last-sexp ()
1597 "Evaluate Octave sexp before point and print value into current buffer."
1598 (interactive)
1599 (inferior-octave t)
1600 (let ((standard-output (current-buffer))
1601 (print-escape-newlines nil)
1602 (opoint (point)))
1603 (terpri)
1604 (prin1
1605 (save-excursion
1606 (forward-sexp -1)
1607 (inferior-octave-send-list-and-digest
1608 (list (concat (buffer-substring-no-properties (point) opoint)
1609 "\n")))
1610 (mapconcat 'identity inferior-octave-output-list "\n")))
1611 (terpri)))
1612
1613 \f
1614
1615 (defcustom octave-eldoc-message-style 'auto
1616 "Octave eldoc message style: auto, oneline, multiline."
1617 :type '(choice (const :tag "Automatic" auto)
1618 (const :tag "One Line" oneline)
1619 (const :tag "Multi Line" multiline))
1620 :version "24.4")
1621
1622 ;; (FN SIGNATURE1 SIGNATURE2 ...)
1623 (defvar octave-eldoc-cache nil)
1624
1625 (defun octave-eldoc-function-signatures (fn)
1626 (unless (equal fn (car octave-eldoc-cache))
1627 (inferior-octave-send-list-and-digest
1628 (list (format "print_usage ('%s');\n" fn)))
1629 (let (result)
1630 (dolist (line inferior-octave-output-list)
1631 (when (string-match
1632 "\\s-*\\(?:--[^:]+\\|usage\\):\\s-*\\(.*\\)$"
1633 line)
1634 (push (match-string 1 line) result)))
1635 (setq octave-eldoc-cache
1636 (cons (substring-no-properties fn)
1637 (nreverse result)))))
1638 (cdr octave-eldoc-cache))
1639
1640 (defun octave-eldoc-function ()
1641 "A function for `eldoc-documentation-function' (which see)."
1642 (when (inferior-octave-process-live-p)
1643 (let* ((ppss (syntax-ppss))
1644 (paren-pos (cadr ppss))
1645 (fn (save-excursion
1646 (if (and paren-pos
1647 ;; PAREN-POS must be after the prompt
1648 (>= paren-pos
1649 (if (eq (get-buffer-process (current-buffer))
1650 inferior-octave-process)
1651 (process-mark inferior-octave-process)
1652 (point-min)))
1653 (or (not (eq (get-buffer-process (current-buffer))
1654 inferior-octave-process))
1655 (< (process-mark inferior-octave-process)
1656 paren-pos))
1657 (eq (char-after paren-pos) ?\())
1658 (goto-char paren-pos)
1659 (setq paren-pos nil))
1660 (when (or (< (skip-syntax-backward "-") 0) paren-pos)
1661 (thing-at-point 'symbol))))
1662 (sigs (and fn (octave-eldoc-function-signatures fn)))
1663 (oneline (mapconcat 'identity sigs
1664 (propertize " | " 'face 'warning)))
1665 (multiline (mapconcat (lambda (s) (concat "-- " s)) sigs "\n")))
1666 ;;
1667 ;; Return the value according to style.
1668 (pcase octave-eldoc-message-style
1669 (`auto (if (< (length oneline) (window-width (minibuffer-window)))
1670 oneline
1671 multiline))
1672 (`oneline oneline)
1673 (`multiline multiline)))))
1674
1675 (defcustom octave-help-buffer "*Octave Help*"
1676 "Buffer name for `octave-help'."
1677 :type 'string
1678 :version "24.4")
1679
1680 ;; Used in a mode derived from help-mode.
1681 (declare-function help-button-action "help-mode" (button))
1682
1683 (define-button-type 'octave-help-file
1684 'follow-link t
1685 'action #'help-button-action
1686 'help-function 'octave-find-definition)
1687
1688 (define-button-type 'octave-help-function
1689 'follow-link t
1690 'action (lambda (b)
1691 (octave-help
1692 (buffer-substring (button-start b) (button-end b)))))
1693
1694 (defvar octave-help-mode-map
1695 (let ((map (make-sparse-keymap)))
1696 (define-key map "\M-." 'octave-find-definition)
1697 (define-key map "\C-hd" 'octave-help)
1698 (define-key map "\C-ha" 'octave-lookfor)
1699 map))
1700
1701 (define-derived-mode octave-help-mode help-mode "OctHelp"
1702 "Major mode for displaying Octave documentation."
1703 :abbrev-table nil
1704 :syntax-table octave-mode-syntax-table
1705 (eval-and-compile (require 'help-mode))
1706 ;; Don't highlight `EXAMPLE' as elisp symbols by using a regexp that
1707 ;; can never match.
1708 (setq-local help-xref-symbol-regexp "x\\`"))
1709
1710 (defun octave-help (fn)
1711 "Display the documentation of FN."
1712 (interactive (list (octave-completing-read)))
1713 (inferior-octave-send-list-and-digest
1714 (list (format "help ('%s');\n" fn)))
1715 (let ((lines inferior-octave-output-list)
1716 (inhibit-read-only t))
1717 (when (string-match "error: \\(.*\\)$" (car lines))
1718 (error "%s" (match-string 1 (car lines))))
1719 (with-help-window octave-help-buffer
1720 (princ (mapconcat 'identity lines "\n"))
1721 (with-current-buffer octave-help-buffer
1722 ;; Bound to t so that `help-buffer' returns current buffer for
1723 ;; `help-setup-xref'.
1724 (let ((help-xref-following t))
1725 (help-setup-xref (list 'octave-help fn)
1726 (called-interactively-p 'interactive)))
1727 ;; Note: can be turned off by suppress_verbose_help_message.
1728 ;;
1729 ;; Remove boring trailing text: Additional help for built-in functions
1730 ;; and operators ...
1731 (goto-char (point-max))
1732 (when (search-backward "\n\n\n" nil t)
1733 (goto-char (match-beginning 0))
1734 (delete-region (point) (point-max)))
1735 ;; File name highlight
1736 (goto-char (point-min))
1737 (when (re-search-forward "from the file \\(.*\\)$"
1738 (line-end-position)
1739 t)
1740 (let* ((file (match-string 1))
1741 (dir (file-name-directory
1742 (directory-file-name (file-name-directory file)))))
1743 (replace-match "" nil nil nil 1)
1744 (insert (substitute-command-keys "`"))
1745 ;; Include the parent directory which may be regarded as
1746 ;; the category for the FN.
1747 (help-insert-xref-button (file-relative-name file dir)
1748 'octave-help-file fn)
1749 (insert (substitute-command-keys "'"))))
1750 ;; Make 'See also' clickable.
1751 (with-syntax-table octave-mode-syntax-table
1752 (when (re-search-forward "^\\s-*See also:" nil t)
1753 (let ((end (save-excursion (re-search-forward "^\\s-*$" nil t))))
1754 (while (re-search-forward
1755 "\\s-*\\([^,\n]+?\\)\\s-*\\(?:[,]\\|[.]?$\\)" end t)
1756 (make-text-button (match-beginning 1) (match-end 1)
1757 :type 'octave-help-function)))))
1758 (octave-help-mode)))))
1759
1760 (defun octave-lookfor (str &optional all)
1761 "Search for the string STR in all function help strings.
1762 If ALL is non-nil search the entire help string else only search the first
1763 sentence."
1764 (interactive "sSearch for: \nP")
1765 (inferior-octave-send-list-and-digest
1766 (list (format "lookfor (%s'%s');\n"
1767 (if all "'-all', " "")
1768 str)))
1769 (let ((lines inferior-octave-output-list))
1770 (when (and (stringp (car lines))
1771 (string-match "error: \\(.*\\)$" (car lines)))
1772 (error "%s" (match-string 1 (car lines))))
1773 (with-help-window octave-help-buffer
1774 (with-current-buffer octave-help-buffer
1775 (if lines
1776 (insert (mapconcat 'identity lines "\n"))
1777 (insert (format "Nothing found for \"%s\".\n" str)))
1778 ;; Bound to t so that `help-buffer' returns current buffer for
1779 ;; `help-setup-xref'.
1780 (let ((help-xref-following t))
1781 (help-setup-xref (list 'octave-lookfor str all)
1782 (called-interactively-p 'interactive)))
1783 (goto-char (point-min))
1784 (when lines
1785 (while (re-search-forward "^\\([^[:blank:]]+\\) " nil 'noerror)
1786 (make-text-button (match-beginning 1) (match-end 1)
1787 :type 'octave-help-function)))
1788 (unless all
1789 (goto-char (point-max))
1790 (insert "\nRetry with ")
1791 (insert-text-button "'-all'"
1792 'follow-link t
1793 'action #'(lambda (_b)
1794 (octave-lookfor str '-all)))
1795 (insert ".\n"))
1796 (octave-help-mode)))))
1797
1798 (defcustom octave-source-directories nil
1799 "A list of directories for Octave sources.
1800 If the environment variable OCTAVE_SRCDIR is set, it is searched first."
1801 :type '(repeat directory)
1802 :version "24.4")
1803
1804 (defun octave-source-directories ()
1805 (let ((srcdir (or (and inferior-octave-process
1806 (process-get inferior-octave-process 'octave-srcdir))
1807 (getenv "OCTAVE_SRCDIR"))))
1808 (if srcdir
1809 (cons srcdir octave-source-directories)
1810 octave-source-directories)))
1811
1812 (defvar octave-find-definition-filename-function
1813 #'octave-find-definition-default-filename)
1814
1815 (defun octave-find-definition-default-filename (name)
1816 "Default value for `octave-find-definition-filename-function'."
1817 (pcase (file-name-extension name)
1818 (`"oct"
1819 (octave-find-definition-default-filename
1820 (concat "libinterp/dldfcn/"
1821 (file-name-sans-extension (file-name-nondirectory name))
1822 ".cc")))
1823 (`"cc"
1824 (let ((file (or (locate-file name (octave-source-directories))
1825 (locate-file (file-name-nondirectory name)
1826 (octave-source-directories)))))
1827 (or (and file (file-exists-p file))
1828 (error "File `%s' not found" name))
1829 file))
1830 (`"mex"
1831 (if (yes-or-no-p (format-message "File `%s' may be binary; open? "
1832 (file-name-nondirectory name)))
1833 name
1834 (user-error "Aborted")))
1835 (_ name)))
1836
1837 (defvar find-tag-marker-ring)
1838
1839 (defun octave-find-definition (fn)
1840 "Find the definition of FN.
1841 Functions implemented in C++ can be found if
1842 variable `octave-source-directories' is set correctly."
1843 (interactive (list (octave-completing-read)))
1844 (require 'etags)
1845 (let ((orig (point)))
1846 (if (and (derived-mode-p 'octave-mode)
1847 (octave-goto-function-definition fn))
1848 (ring-insert find-tag-marker-ring (copy-marker orig))
1849 (inferior-octave-send-list-and-digest
1850 ;; help NAME is more verbose
1851 (list (format "\
1852 if iskeyword('%s') disp('`%s'' is a keyword') else which('%s') endif\n"
1853 fn fn fn)))
1854 (let (line file)
1855 ;; Skip garbage lines such as
1856 ;; warning: fmincg.m: possible Matlab-style ....
1857 (while (and (not file) (consp inferior-octave-output-list))
1858 (setq line (pop inferior-octave-output-list))
1859 (when (string-match "from the file \\(.*\\)$" line)
1860 (setq file (match-string 1 line))))
1861 (if (not file)
1862 (user-error "%s" (or line (format-message "`%s' not found" fn)))
1863 (ring-insert find-tag-marker-ring (point-marker))
1864 (setq file (funcall octave-find-definition-filename-function file))
1865 (when file
1866 (find-file file)
1867 (octave-goto-function-definition fn)))))))
1868
1869 (provide 'octave)
1870 ;;; octave.el ends here