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