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