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