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