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