octave-mod.el 51.5 KB
Newer Older
Richard M. Stallman's avatar
Richard M. Stallman committed
1
;;; octave-mod.el --- editing Octave source files under Emacs
Richard M. Stallman's avatar
Richard M. Stallman committed
2

Glenn Morris's avatar
Glenn Morris committed
3
;; Copyright (C) 1997, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
4
;; Free Software Foundation, Inc.
Richard M. Stallman's avatar
Richard M. Stallman committed
5

6
;; Author: Kurt Hornik <Kurt.Hornik@wu-wien.ac.at>
Richard M. Stallman's avatar
Richard M. Stallman committed
7
;; Author: John Eaton <jwe@bevo.che.wisc.edu>
8
;; Maintainer: Kurt Hornik <Kurt.Hornik@wu-wien.ac.at>
Richard M. Stallman's avatar
Richard M. Stallman committed
9 10 11 12
;; Keywords: languages

;; This file is part of GNU Emacs.

13
;; GNU Emacs is free software: you can redistribute it and/or modify
Richard M. Stallman's avatar
Richard M. Stallman committed
14
;; it under the terms of the GNU General Public License as published by
15 16
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
Richard M. Stallman's avatar
Richard M. Stallman committed
17 18 19 20 21 22 23

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
24
;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
Richard M. Stallman's avatar
Richard M. Stallman committed
25 26 27

;;; Commentary:

28 29 30 31 32 33
;; This package provides Emacs support for Octave.
;; It defines Octave mode, a major mode for editing
;; Octave code.

;; The file octave-inf.el contains code for interacting with an inferior
;; Octave process using comint.
Richard M. Stallman's avatar
Richard M. Stallman committed
34

35
;; See the documentation of `octave-mode' and
36
;; `run-octave' for further information on usage and customization.
Richard M. Stallman's avatar
Richard M. Stallman committed
37

38
;;; Code:
39
(require 'custom)
Richard M. Stallman's avatar
Richard M. Stallman committed
40

Andreas Schwab's avatar
Andreas Schwab committed
41 42
(defgroup octave nil
  "Major mode for editing Octave source files."
43
  :link '(custom-group-link :tag "Font Lock Faces group" font-lock-faces)
Andreas Schwab's avatar
Andreas Schwab committed
44 45
  :group 'languages)

46 47 48 49
(defvar inferior-octave-output-list nil)
(defvar inferior-octave-output-string nil)
(defvar inferior-octave-receive-in-progress nil)

50 51
(declare-function inferior-octave-send-list-and-digest "octave-inf" (list))

52
(defconst octave-maintainer-address
53
  "Kurt Hornik <Kurt.Hornik@wu-wien.ac.at>, bug-gnu-emacs@gnu.org"
54 55
  "Current maintainer of the Emacs Octave package.")

56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
(define-abbrev-table 'octave-abbrev-table
  (mapcar (lambda (e) (append e '(nil 0 t)))
          '(("`a" "all_va_args")
            ("`b" "break")
            ("`cs" "case")
            ("`ca" "catch")
            ("`c" "continue")
            ("`el" "else")
            ("`eli" "elseif")
            ("`et" "end_try_catch")
            ("`eu" "end_unwind_protect")
            ("`ef" "endfor")
            ("`efu" "endfunction")
            ("`ei" "endif")
            ("`es" "endswitch")
            ("`ew" "endwhile")
            ("`f" "for")
            ("`fu" "function")
            ("`gl" "global")
            ("`gp" "gplot")
            ("`gs" "gsplot")
            ("`if" "if ()")
            ("`o" "otherwise")
            ("`rp" "replot")
            ("`r" "return")
            ("`s" "switch")
            ("`t" "try")
            ("`u" "until ()")
            ("`up" "unwind_protect")
            ("`upc" "unwind_protect_cleanup")
            ("`w" "while ()")))
87
  "Abbrev table for Octave's reserved words.
88
Used in `octave-mode' and inferior-octave-mode buffers.
89 90
All Octave abbrevs start with a grave accent (`)."
  :regexp "\\(?:[^`]\\|^\\)\\(\\(?:\\<\\|`\\)\\w+\\)\\W*")
91 92 93 94

(defvar octave-comment-char ?#
  "Character to start an Octave comment.")
(defvar octave-comment-start
95
  (string octave-comment-char ?\ )
96 97 98 99 100
  "String to insert to start a new Octave in-line comment.")
(defvar octave-comment-start-skip "\\s<+\\s-*"
  "Regexp to match the start of an Octave comment up to its body.")

(defvar octave-begin-keywords
101
  '("do" "for" "function" "if" "switch" "try" "unwind_protect" "while"))
102
(defvar octave-else-keywords
103
  '("case" "catch" "else" "elseif" "otherwise" "unwind_protect_cleanup"))
104 105
;; FIXME: only use specific "end" tokens here to avoid confusion when "end"
;; is used in indexing (the real fix is much more complex).
106
(defvar octave-end-keywords
107 108
  '("endfor" "endfunction" "endif" "endswitch" "end_try_catch"
    "end_unwind_protect" "endwhile" "until"))
109 110

(defvar octave-reserved-words
111 112 113
  (append octave-begin-keywords
	  octave-else-keywords
	  octave-end-keywords
114
	  '("break" "continue" "end" "global" "persistent" "return"))
115 116 117 118
  "Reserved words in Octave.")

(defvar octave-text-functions
  '("casesen" "cd" "chdir" "clear" "diary" "dir" "document" "echo"
119 120
    "edit_history" "format" "help" "history" "hold"
    "load" "ls" "more" "run_history" "save" "type"
121
    "which" "who" "whos")
122
  "Text functions in Octave.")
123 124

(defvar octave-variables
125 126 127 128
  '("DEFAULT_EXEC_PATH" "DEFAULT_LOADPATH"
    "EDITOR" "EXEC_PATH" "F_DUPFD" "F_GETFD" "F_GETFL" "F_SETFD"
    "F_SETFL" "I" "IMAGE_PATH" "Inf" "J"
    "NaN" "OCTAVE_VERSION" "O_APPEND" "O_CREAT" "O_EXCL"
129 130 131 132 133 134 135
    "O_NONBLOCK" "O_RDONLY" "O_RDWR" "O_TRUNC" "O_WRONLY" "PAGER" "PS1"
    "PS2" "PS4" "PWD" "SEEK_CUR" "SEEK_END" "SEEK_SET" "__F_DUPFD__"
    "__F_GETFD__" "__F_GETFL__" "__F_SETFD__" "__F_SETFL__" "__I__"
    "__Inf__" "__J__" "__NaN__" "__OCTAVE_VERSION__" "__O_APPEND__"
    "__O_CREAT__" "__O_EXCL__" "__O_NONBLOCK__" "__O_RDONLY__"
    "__O_RDWR__" "__O_TRUNC__" "__O_WRONLY__" "__PWD__" "__SEEK_CUR__"
    "__SEEK_END__" "__SEEK_SET__" "__argv__" "__e__" "__eps__"
136
    "__i__" "__inf__" "__j__" "__nan__" "__pi__"
137 138
    "__program_invocation_name__" "__program_name__" "__realmax__"
    "__realmin__" "__stderr__" "__stdin__" "__stdout__" "ans" "argv"
139 140 141 142 143 144
    "beep_on_error" "completion_append_char"
    "crash_dumps_octave_core" "default_save_format"
    "e" "echo_executing_commands" "eps"
    "error_text" "gnuplot_binary" "history_file"
    "history_size" "ignore_function_time_stamp"
    "inf" "nan" "nargin" "output_max_field_width" "output_precision"
145 146
    "page_output_immediately" "page_screen_output" "pi"
    "print_answer_id_name" "print_empty_dimensions"
147 148 149
    "program_invocation_name" "program_name"
    "realmax" "realmin" "return_last_computed_value" "save_precision"
    "saving_history" "sighup_dumps_octave_core" "sigterm_dumps_octave_core"
150 151
    "silent_functions" "split_long_rows" "stderr" "stdin" "stdout"
    "string_fill_char" "struct_levels_to_print"
152
    "suppress_verbose_help_message")
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
  "Builtin variables in Octave.")

(defvar octave-function-header-regexp
  (concat "^\\s-*\\<\\(function\\)\\>"
	  "\\([^=;\n]*=[ \t]*\\|[ \t]*\\)\\(\\w+\\)\\>")
  "Regexp to match an Octave function header.
The string `function' and its name are given by the first and third
parenthetical grouping.")

(defvar octave-font-lock-keywords
  (list
   ;; Fontify all builtin keywords.
   (cons (concat "\\<\\("
		 (mapconcat 'identity octave-reserved-words "\\|")
		 (mapconcat 'identity octave-text-functions "\\|")
		 "\\)\\>")
	 'font-lock-keyword-face)
   ;; Fontify all builtin operators.
   (cons "\\(&\\||\\|<=\\|>=\\|==\\|<\\|>\\|!=\\|!\\)"
172 173 174
	 (if (boundp 'font-lock-builtin-face)
	     'font-lock-builtin-face
	   'font-lock-preprocessor-face))
175 176 177 178 179 180 181 182 183 184 185
   ;; Fontify all builtin variables.
   (cons (concat "\\<\\("
		 (mapconcat 'identity octave-variables "\\|")
		 "\\)\\>")
	 'font-lock-variable-name-face)
   ;; Fontify all function declarations.
   (list octave-function-header-regexp
	 '(1 font-lock-keyword-face)
	 '(3 font-lock-function-name-face nil t)))
  "Additional Octave expressions to highlight.")

Andreas Schwab's avatar
Andreas Schwab committed
186
(defcustom inferior-octave-buffer "*Inferior Octave*"
187
  "Name of buffer for running an inferior Octave process."
Andreas Schwab's avatar
Andreas Schwab committed
188 189
  :type 'string
  :group 'octave-inferior)
190 191 192

(defvar inferior-octave-process nil)

193
(defvar octave-mode-map
Richard M. Stallman's avatar
Richard M. Stallman committed
194 195 196 197 198 199
  (let ((map (make-sparse-keymap)))
    (define-key map "`" 'octave-abbrev-start)
    (define-key map ";" 'octave-electric-semi)
    (define-key map " " 'octave-electric-space)
    (define-key map "\n" 'octave-reindent-then-newline-and-indent)
    (define-key map "\e;" 'octave-indent-for-comment)
200
    (define-key map "\e\n" 'octave-indent-new-comment-line)
Richard M. Stallman's avatar
Richard M. Stallman committed
201 202 203 204
    (define-key map "\e\t" 'octave-complete-symbol)
    (define-key map "\M-\C-a" 'octave-beginning-of-defun)
    (define-key map "\M-\C-e" 'octave-end-of-defun)
    (define-key map "\M-\C-h" 'octave-mark-defun)
205
    (define-key map "\M-\C-q" 'octave-indent-defun)
Richard M. Stallman's avatar
Richard M. Stallman committed
206
    (define-key map "\C-c;" 'octave-comment-region)
207
    (define-key map "\C-c:" 'octave-uncomment-region)
Richard M. Stallman's avatar
Richard M. Stallman committed
208 209 210 211
    (define-key map "\C-c\C-b" 'octave-submit-bug-report)
    (define-key map "\C-c\C-p" 'octave-previous-code-line)
    (define-key map "\C-c\C-n" 'octave-next-code-line)
    (define-key map "\C-c\C-a" 'octave-beginning-of-line)
212
    (define-key map "\C-c\C-e" 'octave-end-of-line)
Richard M. Stallman's avatar
Richard M. Stallman committed
213 214 215 216 217 218
    (define-key map "\C-c\M-\C-n" 'octave-forward-block)
    (define-key map "\C-c\M-\C-p" 'octave-backward-block)
    (define-key map "\C-c\M-\C-u" 'octave-backward-up-block)
    (define-key map "\C-c\M-\C-d" 'octave-down-block)
    (define-key map "\C-c\M-\C-h" 'octave-mark-block)
    (define-key map "\C-c]" 'octave-close-block)
219
    (define-key map "\C-c\C-f" 'octave-insert-defun)
Richard M. Stallman's avatar
Richard M. Stallman committed
220
    (define-key map "\C-c\C-h" 'octave-help)
221 222 223
    (define-key map "\C-c\C-il" 'octave-send-line)
    (define-key map "\C-c\C-ib" 'octave-send-block)
    (define-key map "\C-c\C-if" 'octave-send-defun)
224
    (define-key map "\C-c\C-ir" 'octave-send-region)
225 226 227 228 229 230
    (define-key map "\C-c\C-is" 'octave-show-process-buffer)
    (define-key map "\C-c\C-ih" 'octave-hide-process-buffer)
    (define-key map "\C-c\C-ik" 'octave-kill-process)
    (define-key map "\C-c\C-i\C-l" 'octave-send-line)
    (define-key map "\C-c\C-i\C-b" 'octave-send-block)
    (define-key map "\C-c\C-i\C-f" 'octave-send-defun)
231
    (define-key map "\C-c\C-i\C-r" 'octave-send-region)
232 233 234
    (define-key map "\C-c\C-i\C-s" 'octave-show-process-buffer)
    (define-key map "\C-c\C-i\C-h" 'octave-hide-process-buffer)
    (define-key map "\C-c\C-i\C-k" 'octave-kill-process)
235 236 237
    map)
  "Keymap used in Octave mode.")

Richard M. Stallman's avatar
Richard M. Stallman committed
238 239

(defvar octave-mode-menu
240
  '("Octave"
241
    ("Lines"
242 243 244 245 246
      ["Previous Code Line"	octave-previous-code-line t]
      ["Next Code Line"		octave-next-code-line t]
      ["Begin of Continuation"	octave-beginning-of-line t]
      ["End of Continuation"	octave-end-of-line t]
      ["Split Line at Point"	octave-indent-new-comment-line t])
247
    ("Blocks"
248 249 250 251 252 253
      ["Next Block"		octave-forward-block t]
      ["Previous Block"		octave-backward-block t]
      ["Down Block"		octave-down-block t]
      ["Up Block"		octave-backward-up-block t]
      ["Mark Block"		octave-mark-block t]
      ["Close Block"		octave-close-block t])
254
    ("Functions"
255 256 257 258 259 260
      ["Begin of Function"	octave-beginning-of-defun t]
      ["End of Function"	octave-end-of-defun t]
      ["Mark Function"		octave-mark-defun t]
      ["Indent Function"	octave-indent-defun t]
      ["Insert Function"	octave-insert-defun t])
    "-"
261
    ("Debug"
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
      ["Send Current Line"	octave-send-line t]
      ["Send Current Block"	octave-send-block t]
      ["Send Current Function"	octave-send-defun t]
      ["Send Region"		octave-send-region t]
      ["Show Process Buffer"	octave-show-process-buffer t]
      ["Hide Process Buffer"	octave-hide-process-buffer t]
      ["Kill Process"		octave-kill-process t])
    "-"
    ["Indent Line"		indent-according-to-mode t]
    ["Complete Symbol"		octave-complete-symbol t]
    "-"
    ["Toggle Abbrev Mode"	abbrev-mode t]
    ["Toggle Auto-Fill Mode"	auto-fill-mode t]
    "-"
    ["Submit Bug Report"	octave-submit-bug-report t]
    "-"
    ["Describe Octave Mode"	octave-describe-major-mode t]
    ["Lookup Octave Index"	octave-help t])
Richard M. Stallman's avatar
Richard M. Stallman committed
280 281
  "Menu for Octave mode.")

282
(defvar octave-mode-syntax-table
Richard M. Stallman's avatar
Richard M. Stallman committed
283 284 285 286 287 288 289 290 291 292 293 294 295 296
  (let ((table (make-syntax-table)))
    (modify-syntax-entry ?\r " "  table)
    (modify-syntax-entry ?+ "."   table)
    (modify-syntax-entry ?- "."   table)
    (modify-syntax-entry ?= "."   table)
    (modify-syntax-entry ?* "."   table)
    (modify-syntax-entry ?/ "."   table)
    (modify-syntax-entry ?> "."   table)
    (modify-syntax-entry ?< "."   table)
    (modify-syntax-entry ?& "."   table)
    (modify-syntax-entry ?| "."   table)
    (modify-syntax-entry ?! "."   table)
    (modify-syntax-entry ?\\ "\\" table)
    (modify-syntax-entry ?\' "."  table)
297 298
    ;; Was "w" for abbrevs, but now that it's not necessary any more,
    (modify-syntax-entry ?\` "."  table)
Richard M. Stallman's avatar
Richard M. Stallman committed
299 300 301
    (modify-syntax-entry ?\" "\"" table)
    (modify-syntax-entry ?. "w"   table)
    (modify-syntax-entry ?_ "w"   table)
302
    (modify-syntax-entry ?\% "<"  table)
Richard M. Stallman's avatar
Richard M. Stallman committed
303 304
    (modify-syntax-entry ?\# "<"  table)
    (modify-syntax-entry ?\n ">"  table)
305 306
    table)
  "Syntax table in use in `octave-mode' buffers.")
Richard M. Stallman's avatar
Richard M. Stallman committed
307

Andreas Schwab's avatar
Andreas Schwab committed
308
(defcustom octave-auto-indent nil
309
  "Non-nil means indent line after a semicolon or space in Octave mode."
Andreas Schwab's avatar
Andreas Schwab committed
310
  :type 'boolean
311
  :group 'octave)
312

Andreas Schwab's avatar
Andreas Schwab committed
313
(defcustom octave-auto-newline nil
314
  "Non-nil means automatically newline after a semicolon in Octave mode."
Andreas Schwab's avatar
Andreas Schwab committed
315 316
  :type 'boolean
  :group 'octave)
Richard M. Stallman's avatar
Richard M. Stallman committed
317

Andreas Schwab's avatar
Andreas Schwab committed
318
(defcustom octave-blink-matching-block t
319
  "Control the blinking of matching Octave block keywords.
Richard M. Stallman's avatar
Richard M. Stallman committed
320
Non-nil means show matching begin of block when inserting a space,
Andreas Schwab's avatar
Andreas Schwab committed
321 322 323 324
newline or semicolon after an else or end keyword."
  :type 'boolean
  :group 'octave)
(defcustom octave-block-offset 2
325
  "Extra indentation applied to statements in Octave block structures."
Andreas Schwab's avatar
Andreas Schwab committed
326 327
  :type 'integer
  :group 'octave)
Richard M. Stallman's avatar
Richard M. Stallman committed
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344

(defvar octave-block-begin-regexp
  (concat "\\<\\("
	  (mapconcat 'identity octave-begin-keywords "\\|")
	  "\\)\\>"))
(defvar octave-block-else-regexp
  (concat "\\<\\("
	  (mapconcat 'identity octave-else-keywords "\\|")
	  "\\)\\>"))
(defvar octave-block-end-regexp
  (concat "\\<\\("
	  (mapconcat 'identity octave-end-keywords "\\|")
	  "\\)\\>"))
(defvar octave-block-begin-or-end-regexp
  (concat octave-block-begin-regexp "\\|" octave-block-end-regexp))
(defvar octave-block-else-or-end-regexp
  (concat octave-block-else-regexp "\\|" octave-block-end-regexp))
345 346
;; FIXME: only use specific "end" tokens here to avoid confusion when "end"
;; is used in indexing (the real fix is much more complex).
Richard M. Stallman's avatar
Richard M. Stallman committed
347
(defvar octave-block-match-alist
348 349 350 351 352 353 354 355
  '(("do" . ("until"))
    ("for" . ("endfor"))
    ("function" . ("endfunction"))
    ("if" . ("else" "elseif" "endif"))
    ("switch" . ("case" "otherwise" "endswitch"))
    ("try" . ("catch" "end_try_catch"))
    ("unwind_protect" . ("unwind_protect_cleanup" "end_unwind_protect"))
    ("while" . ("endwhile")))
Richard M. Stallman's avatar
Richard M. Stallman committed
356 357 358 359 360 361 362 363
  "Alist with Octave's matching block keywords.
Has Octave's begin keywords as keys and a list of the matching else or
end keywords as associated values.")

(defvar octave-block-comment-start
  (concat (make-string 2 octave-comment-char) " ")
  "String to insert to start a new Octave comment on an empty line.")

Andreas Schwab's avatar
Andreas Schwab committed
364
(defcustom octave-continuation-offset 4
365
  "Extra indentation applied to Octave continuation lines."
Andreas Schwab's avatar
Andreas Schwab committed
366 367
  :type 'integer
  :group 'octave)
Richard M. Stallman's avatar
Richard M. Stallman committed
368 369
(defvar octave-continuation-regexp
  "[^#%\n]*\\(\\\\\\|\\.\\.\\.\\)\\s-*\\(\\s<.*\\)?$")
Andreas Schwab's avatar
Andreas Schwab committed
370
(defcustom octave-continuation-string "\\"
371
  "Character string used for Octave continuation lines.  Normally \\."
Andreas Schwab's avatar
Andreas Schwab committed
372 373
  :type 'string
  :group 'octave)
Richard M. Stallman's avatar
Richard M. Stallman committed
374 375 376 377 378

(defvar octave-completion-alist nil
  "Alist of Octave symbols for completion in Octave mode.
Each element looks like (VAR . VAR), where the car and cdr are the same
symbol (an Octave command or variable name).
379
Currently, only builtin variables can be completed.")
Richard M. Stallman's avatar
Richard M. Stallman committed
380 381 382 383 384 385 386

(defvar octave-mode-imenu-generic-expression
  (list
   ;; Functions
   (list nil octave-function-header-regexp 3))
  "Imenu expression for Octave mode.  See `imenu-generic-expression'.")

Andreas Schwab's avatar
Andreas Schwab committed
387
(defcustom octave-mode-hook nil
388
  "Hook to be run when Octave mode is started."
Andreas Schwab's avatar
Andreas Schwab committed
389 390 391 392
  :type 'hook
  :group 'octave)

(defcustom octave-send-show-buffer t
393
  "Non-nil means display `inferior-octave-buffer' after sending to it."
Andreas Schwab's avatar
Andreas Schwab committed
394 395 396
  :type 'boolean
  :group 'octave)
(defcustom octave-send-line-auto-forward t
397
  "Control auto-forward after sending to the inferior Octave process.
Andreas Schwab's avatar
Andreas Schwab committed
398 399 400 401
Non-nil means always go to the next Octave code line after sending."
  :type 'boolean
  :group 'octave)
(defcustom octave-send-echo-input t
402
  "Non-nil means echo input sent to the inferior Octave process."
Andreas Schwab's avatar
Andreas Schwab committed
403 404
  :type 'boolean
  :group 'octave)
Richard M. Stallman's avatar
Richard M. Stallman committed
405 406 407 408 409 410 411 412


;;;###autoload
(defun octave-mode ()
  "Major mode for editing Octave code.

This mode makes it easier to write Octave code by helping with
indentation, doing some of the typing for you (with Abbrev mode) and by
413
showing keywords, comments, strings, etc.. in different faces (with
Richard M. Stallman's avatar
Richard M. Stallman committed
414 415 416 417 418 419 420 421 422
Font Lock mode on terminals that support it).

Octave itself is a high-level language, primarily intended for numerical
computations.  It provides a convenient command line interface for
solving linear and nonlinear problems numerically.  Function definitions
can also be stored in files, and it can be used in a batch mode (which
is why you need this mode!).

The latest released version of Octave is always available via anonymous
423
ftp from ftp.octave.org in the directory `/pub/octave'.  Complete
Richard M. Stallman's avatar
Richard M. Stallman committed
424 425 426 427 428 429 430 431 432 433 434 435
source and binaries for several popular systems are available.

Type \\[list-abbrevs] to display the built-in abbrevs for Octave keywords.

Keybindings
===========

\\{octave-mode-map}

Variables you can use to customize Octave mode
==============================================

436
`octave-auto-indent'
437 438 439
  Non-nil means indent current line after a semicolon or space.
  Default is nil.

440
`octave-auto-newline'
Richard M. Stallman's avatar
Richard M. Stallman committed
441 442 443
  Non-nil means auto-insert a newline and indent after a semicolon.
  Default is nil.

444
`octave-blink-matching-block'
Richard M. Stallman's avatar
Richard M. Stallman committed
445 446 447
  Non-nil means show matching begin of block when inserting a space,
  newline or semicolon after an else or end keyword.  Default is t.

448
`octave-block-offset'
Richard M. Stallman's avatar
Richard M. Stallman committed
449 450 451
  Extra indentation applied to statements in block structures.
  Default is 2.

452
`octave-continuation-offset'
Richard M. Stallman's avatar
Richard M. Stallman committed
453 454 455
  Extra indentation applied to Octave continuation lines.
  Default is 4.

456
`octave-continuation-string'
Richard M. Stallman's avatar
Richard M. Stallman committed
457 458 459
  String used for Octave continuation lines.
  Default is a backslash.

460
`octave-send-echo-input'
Richard M. Stallman's avatar
Richard M. Stallman committed
461 462 463
  Non-nil means always display `inferior-octave-buffer' after sending a
  command to the inferior Octave process.

464
`octave-send-line-auto-forward'
Richard M. Stallman's avatar
Richard M. Stallman committed
465 466 467
  Non-nil means always go to the next unsent line of Octave code after
  sending a line to the inferior Octave process.

468
`octave-send-echo-input'
Richard M. Stallman's avatar
Richard M. Stallman committed
469 470 471 472 473 474 475
  Non-nil means echo input sent to the inferior Octave process.

Turning on Octave mode runs the hook `octave-mode-hook'.

To begin using this mode for all `.m' files that you edit, add the
following lines to your `.emacs' file:

476
  (add-to-list 'auto-mode-alist '(\"\\\\.m\\\\'\" . octave-mode))
Richard M. Stallman's avatar
Richard M. Stallman committed
477

478
To automatically turn on the abbrev and auto-fill features,
Richard M. Stallman's avatar
Richard M. Stallman committed
479 480 481 482 483
add the following lines to your `.emacs' file as well:

  (add-hook 'octave-mode-hook
	    (lambda ()
	      (abbrev-mode 1)
484
	      (auto-fill-mode 1)))
Richard M. Stallman's avatar
Richard M. Stallman committed
485 486 487 488 489 490 491 492 493 494 495 496 497 498

To submit a problem report, enter \\[octave-submit-bug-report] from \
an Octave mode buffer.
This automatically sets up a mail buffer with version information
already added.  You just need to add a description of the problem,
including a reproducible test case and send the message."
  (interactive)
  (kill-all-local-variables)

  (use-local-map octave-mode-map)
  (setq major-mode 'octave-mode)
  (setq mode-name "Octave")
  (setq local-abbrev-table octave-abbrev-table)
  (set-syntax-table octave-mode-syntax-table)
499

Richard M. Stallman's avatar
Richard M. Stallman committed
500 501 502
  (make-local-variable 'indent-line-function)
  (setq indent-line-function 'octave-indent-line)

503
  (make-local-variable 'comment-start)
Richard M. Stallman's avatar
Richard M. Stallman committed
504 505 506 507
  (setq comment-start octave-comment-start)
  (make-local-variable 'comment-end)
  (setq comment-end "")
  (make-local-variable 'comment-column)
508
  (setq comment-column 32)
Richard M. Stallman's avatar
Richard M. Stallman committed
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
  (make-local-variable 'comment-start-skip)
  (setq comment-start-skip "\\s<+\\s-*")
  (make-local-variable 'comment-indent-function)
  (setq comment-indent-function 'octave-comment-indent)

  (make-local-variable 'parse-sexp-ignore-comments)
  (setq parse-sexp-ignore-comments t)
  (make-local-variable 'paragraph-start)
  (setq paragraph-start (concat "\\s-*$\\|" page-delimiter))
  (make-local-variable 'paragraph-separate)
  (setq paragraph-separate paragraph-start)
  (make-local-variable 'paragraph-ignore-fill-prefix)
  (setq paragraph-ignore-fill-prefix t)
  (make-local-variable 'fill-paragraph-function)
  (setq fill-paragraph-function 'octave-fill-paragraph)
  (make-local-variable 'adaptive-fill-regexp)
  (setq adaptive-fill-regexp nil)
  (make-local-variable 'fill-column)
  (setq fill-column 72)
  (make-local-variable 'normal-auto-fill-function)
  (setq normal-auto-fill-function 'octave-auto-fill)

  (make-local-variable 'font-lock-defaults)
  (setq font-lock-defaults '(octave-font-lock-keywords nil nil))

  (make-local-variable 'imenu-generic-expression)
Dave Love's avatar
Dave Love committed
535 536
  (setq imenu-generic-expression octave-mode-imenu-generic-expression
        imenu-case-fold-search nil)
Richard M. Stallman's avatar
Richard M. Stallman committed
537 538 539

  (octave-add-octave-menu)
  (octave-initialize-completions)
540
  (run-mode-hooks 'octave-mode-hook))
541 542 543 544 545 546

(defun octave-help ()
  "Get help on Octave symbols from the Octave info files.
Look up symbol in the function, operator and variable indices of the info files."
  (let ((info-lookup-mode 'octave-mode))
    (call-interactively 'info-lookup-symbol)))
Richard M. Stallman's avatar
Richard M. Stallman committed
547 548 549 550 551 552 553 554

;;; Miscellaneous useful functions
(defun octave-describe-major-mode ()
  "Describe the current major mode."
  (interactive)
  (describe-function major-mode))

(defsubst octave-in-comment-p ()
555
  "Return t if point is inside an Octave comment."
Richard M. Stallman's avatar
Richard M. Stallman committed
556 557
  (interactive)
  (save-excursion
558
    (nth 4 (parse-partial-sexp (line-beginning-position) (point)))))
Richard M. Stallman's avatar
Richard M. Stallman committed
559 560

(defsubst octave-in-string-p ()
561
  "Return t if point is inside an Octave string."
Richard M. Stallman's avatar
Richard M. Stallman committed
562 563
  (interactive)
  (save-excursion
564
    (nth 3 (parse-partial-sexp (line-beginning-position) (point)))))
Richard M. Stallman's avatar
Richard M. Stallman committed
565 566

(defsubst octave-not-in-string-or-comment-p ()
567
  "Return t if point is not inside an Octave string or comment."
568
  (let ((pps (parse-partial-sexp (line-beginning-position) (point))))
Richard M. Stallman's avatar
Richard M. Stallman committed
569 570 571
    (not (or (nth 3 pps) (nth 4 pps)))))

(defun octave-in-block-p ()
572
  "Return t if point is inside an Octave block.
Richard M. Stallman's avatar
Richard M. Stallman committed
573 574 575 576 577 578 579 580 581 582 583 584 585
The block is taken to start at the first letter of the begin keyword and
to end after the end keyword."
  (let ((pos (point)))
    (save-excursion
      (condition-case nil
	  (progn
	    (skip-syntax-forward "w")
	    (octave-up-block -1)
	    (octave-forward-block)
	    t)
	(error nil))
      (< pos (point)))))

586
(defun octave-looking-at-kw (regexp)
587
  "Like `looking-at', but sets `case-fold-search' nil."
588 589 590
  (let ((case-fold-search nil))
    (looking-at regexp)))

591 592
(defun octave-re-search-forward-kw (regexp count)
  "Like `re-search-forward', but sets `case-fold-search' nil, and moves point."
593
  (let ((case-fold-search nil))
594
    (re-search-forward regexp nil 'move count)))
595

596 597
(defun octave-re-search-backward-kw (regexp count)
  "Like `re-search-backward', but sets `case-fold-search' nil, and moves point."
598
  (let ((case-fold-search nil))
599
    (re-search-backward regexp nil 'move count)))
600

Richard M. Stallman's avatar
Richard M. Stallman committed
601
(defun octave-in-defun-p ()
602
  "Return t if point is inside an Octave function declaration.
Richard M. Stallman's avatar
Richard M. Stallman committed
603 604 605 606
The function is taken to start at the `f' of `function' and to end after
the end keyword."
  (let ((pos (point)))
    (save-excursion
607
      (or (and (octave-looking-at-kw "\\<function\\>")
Richard M. Stallman's avatar
Richard M. Stallman committed
608 609 610 611 612 613 614 615 616
	       (octave-not-in-string-or-comment-p))
	  (and (octave-beginning-of-defun)
	       (condition-case nil
		   (progn
		     (octave-forward-block)
		     t)
		 (error nil))
	       (< pos (point)))))))

617 618 619 620 621 622 623 624 625
(defun octave-maybe-insert-continuation-string ()
  (if (or (octave-in-comment-p)
	  (save-excursion
	    (beginning-of-line)
	    (looking-at octave-continuation-regexp)))
      nil
    (delete-horizontal-space)
    (insert (concat " " octave-continuation-string))))

Richard M. Stallman's avatar
Richard M. Stallman committed
626 627 628 629 630 631 632
;;; Comments
(defun octave-comment-region (beg end &optional arg)
  "Comment or uncomment each line in the region as Octave code.
See `comment-region'."
  (interactive "r\nP")
  (let ((comment-start (char-to-string octave-comment-char)))
    (comment-region beg end arg)))
633

Richard M. Stallman's avatar
Richard M. Stallman committed
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
(defun octave-uncomment-region (beg end &optional arg)
  "Uncomment each line in the region as Octave code."
  (interactive "r\nP")
  (or arg (setq arg 1))
  (octave-comment-region beg end (- arg)))


;;; Indentation
(defun calculate-octave-indent ()
  "Return appropriate indentation for current line as Octave code.
Returns an integer (the column to indent to) unless the line is a
comment line with fixed goal golumn.  In that case, returns a list whose
car is the column to indent to, and whose cdr is the current indentation
level."
  (let ((is-continuation-line
	 (save-excursion
	   (if (zerop (octave-previous-code-line))
	       (looking-at octave-continuation-regexp))))
	(icol 0))
    (save-excursion
      (beginning-of-line)
      ;; If we can move backward out one level of parentheses, take 1
      ;; plus the indentation of that parenthesis.  Otherwise, go back
      ;; to the beginning of the previous code line, and compute the
      ;; offset this line gives.
      (if (condition-case nil
	      (progn
		(up-list -1)
		t)
	    (error nil))
	  (setq icol (+ 1 (current-column)))
	(if (zerop (octave-previous-code-line))
	    (progn
	      (octave-beginning-of-line)
	      (back-to-indentation)
	      (setq icol (current-column))
	      (let ((bot (point))
671
		    (eol (line-end-position)))
Richard M. Stallman's avatar
Richard M. Stallman committed
672 673 674
		(while (< (point) eol)
		  (if (octave-not-in-string-or-comment-p)
		      (cond
675
		       ((octave-looking-at-kw "\\<switch\\>")
676
			(setq icol (+ icol (* 2 octave-block-offset))))
677
		       ((octave-looking-at-kw octave-block-begin-regexp)
Richard M. Stallman's avatar
Richard M. Stallman committed
678
			(setq icol (+ icol octave-block-offset)))
679
		       ((octave-looking-at-kw octave-block-else-regexp)
Richard M. Stallman's avatar
Richard M. Stallman committed
680 681
			(if (= bot (point))
			    (setq icol (+ icol octave-block-offset))))
682
		       ((octave-looking-at-kw octave-block-end-regexp)
Richard M. Stallman's avatar
Richard M. Stallman committed
683
			(if (not (= bot (point)))
684 685
			    (setq icol (- icol
					  (octave-block-end-offset)))))))
Richard M. Stallman's avatar
Richard M. Stallman committed
686 687 688 689 690 691
		  (forward-char)))
	      (if is-continuation-line
		  (setq icol (+ icol octave-continuation-offset)))))))
    (save-excursion
      (back-to-indentation)
      (cond
692
       ((and (octave-looking-at-kw octave-block-else-regexp)
Richard M. Stallman's avatar
Richard M. Stallman committed
693 694
	     (octave-not-in-string-or-comment-p))
	(setq icol (- icol octave-block-offset)))
695
       ((and (octave-looking-at-kw octave-block-end-regexp)
696 697
	     (octave-not-in-string-or-comment-p))
	(setq icol (- icol (octave-block-end-offset))))
698 699
       ((or (looking-at "\\s<\\s<\\s<\\S<")
	    (octave-before-magic-comment-p))
Richard M. Stallman's avatar
Richard M. Stallman committed
700 701 702 703 704
	(setq icol (list 0 icol)))
       ((looking-at "\\s<\\S<")
	(setq icol (list comment-column icol)))))
    icol))

705 706 707 708 709 710
(defun octave-block-end-offset ()
  (save-excursion
    (octave-backward-up-block 1)
    (* octave-block-offset
       (if (string-match (match-string 0) "switch") 2 1))))

711 712 713 714 715
(defun octave-before-magic-comment-p ()
  (save-excursion
    (beginning-of-line)
    (and (bobp) (looking-at "\\s-*#!"))))

Richard M. Stallman's avatar
Richard M. Stallman committed
716
(defun octave-comment-indent ()
717 718
  (if (or (looking-at "\\s<\\s<\\s<")
	  (octave-before-magic-comment-p))
Richard M. Stallman's avatar
Richard M. Stallman committed
719 720 721 722
      0
    (if (looking-at "\\s<\\s<")
	(calculate-octave-indent)
      (skip-syntax-backward " ")
723
      (max (if (bolp) 0 (+ 1 (current-column)))
Richard M. Stallman's avatar
Richard M. Stallman committed
724 725 726 727 728
	   comment-column))))

(defun octave-indent-for-comment ()
  "Maybe insert and indent an Octave comment.
If there is no comment already on this line, create a code-level comment
Stefan Monnier's avatar
Stefan Monnier committed
729
\(started by two comment characters) if the line is empty, or an in-line
730
comment (started by one comment character) otherwise.
Richard M. Stallman's avatar
Richard M. Stallman committed
731 732
Point is left after the start of the comment which is properly aligned."
  (interactive)
733 734 735 736
  (beginning-of-line)
  (if (looking-at "^\\s-*$")
      (insert octave-block-comment-start)
    (indent-for-comment))
Richard M. Stallman's avatar
Richard M. Stallman committed
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
  (indent-according-to-mode))

(defun octave-indent-line (&optional arg)
  "Indent current line as Octave code.
With optional ARG, use this as offset unless this line is a comment with
fixed goal column."
  (interactive)
  (or arg (setq arg 0))
  (let ((icol (calculate-octave-indent))
	(relpos (- (current-column) (current-indentation))))
    (if (listp icol)
	(setq icol (car icol))
      (setq icol (+ icol arg)))
    (if (< icol 0)
	(error "Unmatched end keyword")
      (indent-line-to icol)
      (if (> relpos 0)
	  (move-to-column (+ icol relpos))))))

(defun octave-indent-new-comment-line ()
  "Break Octave line at point, continuing comment if within one.
If within code, insert `octave-continuation-string' before breaking the
759 760
line.  If within a string, signal an error.
The new line is properly indented."
Richard M. Stallman's avatar
Richard M. Stallman committed
761 762 763 764 765 766 767 768 769 770 771 772
  (interactive)
  (delete-horizontal-space)
  (cond
   ((octave-in-comment-p)
    (indent-new-comment-line))
   ((octave-in-string-p)
    (error "Cannot split a code line inside a string"))
   (t
    (insert (concat " " octave-continuation-string))
    (octave-reindent-then-newline-and-indent))))

(defun octave-indent-defun ()
773
  "Properly indent the Octave function which contains point."
Richard M. Stallman's avatar
Richard M. Stallman committed
774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
  (interactive)
  (save-excursion
    (octave-mark-defun)
    (message "Indenting function...")
    (indent-region (point) (mark) nil))
  (message "Indenting function...done."))


;;; Motion
(defun octave-next-code-line (&optional arg)
  "Move ARG lines of Octave code forward (backward if ARG is negative).
Skips past all empty and comment lines.  Default for ARG is 1.

On success, return 0.  Otherwise, go as far as possible and return -1."
  (interactive "p")
  (or arg (setq arg 1))
  (beginning-of-line)
  (let ((n 0)
	(inc (if (> arg 0) 1 -1)))
    (while (and (/= arg 0) (= n 0))
      (setq n (forward-line inc))
      (while (and (= n 0)
		  (looking-at "\\s-*\\($\\|\\s<\\)"))
	(setq n (forward-line inc)))
      (setq arg (- arg inc)))
    n))
800

Richard M. Stallman's avatar
Richard M. Stallman committed
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
(defun octave-previous-code-line (&optional arg)
  "Move ARG lines of Octave code backward (forward if ARG is negative).
Skips past all empty and comment lines.  Default for ARG is 1.

On success, return 0.  Otherwise, go as far as possible and return -1."
  (interactive "p")
  (or arg (setq arg 1))
  (octave-next-code-line (- arg)))

(defun octave-beginning-of-line ()
  "Move point to beginning of current Octave line.
If on an empty or comment line, go to the beginning of that line.
Otherwise, move backward to the beginning of the first Octave code line
which is not inside a continuation statement, i.e., which does not
follow a code line ending in `...' or `\\', or is inside an open
parenthesis list."
  (interactive)
  (beginning-of-line)
  (if (not (looking-at "\\s-*\\($\\|\\s<\\)"))
      (while (or (condition-case nil
		     (progn
		       (up-list -1)
		       (beginning-of-line)
		       t)
		   (error nil))
		 (and (or (looking-at "\\s-*\\($\\|\\s<\\)")
			  (save-excursion
			    (if (zerop (octave-previous-code-line))
				(looking-at octave-continuation-regexp))))
		      (zerop (forward-line -1)))))))

(defun octave-end-of-line ()
  "Move point to end of current Octave line.
If on an empty or comment line, go to the end of that line.
Otherwise, move forward to the end of the first Octave code line which
does not end in `...' or `\\' or is inside an open parenthesis list."
  (interactive)
  (end-of-line)
  (if (save-excursion
	(beginning-of-line)
	(looking-at "\\s-*\\($\\|\\s<\\)"))
      ()
    (while (or (condition-case nil
		   (progn
		     (up-list 1)
		     (end-of-line)
		     t)
		 (error nil))
	       (and (save-excursion
		      (beginning-of-line)
		      (or (looking-at "\\s-*\\($\\|\\s<\\)")
			  (looking-at octave-continuation-regexp)))
		    (zerop (forward-line 1)))))
    (end-of-line)))
855

856 857
(defun octave-scan-blocks (count depth)
  "Scan from point by COUNT Octave begin-end blocks.
Richard M. Stallman's avatar
Richard M. Stallman committed
858 859 860 861 862 863 864 865 866 867 868 869 870
Returns the character number of the position thus found.

If DEPTH is nonzero, block depth begins counting from that value.
Only places where the depth in blocks becomes zero are candidates for
stopping; COUNT such places are counted.

If the beginning or end of the buffer is reached and the depth is wrong,
an error is signaled."
  (let ((min-depth (if (> depth 0) 0 depth))
	(inc (if (> count 0) 1 -1)))
    (save-excursion
      (while (/= count 0)
	(catch 'foo
871
	  (while (or (octave-re-search-forward-kw
872
		      octave-block-begin-or-end-regexp inc)
Richard M. Stallman's avatar
Richard M. Stallman committed
873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
		     (if (/= depth 0)
			 (error "Unbalanced block")))
	    (if (octave-not-in-string-or-comment-p)
		(progn
		  (cond
		   ((match-end 1)
		    (setq depth (+ depth inc)))
		   ((match-end 2)
		    (setq depth (- depth inc))))
		  (if (< depth min-depth)
		      (error "Containing expression ends prematurely"))
		  (if (= depth 0)
		      (throw 'foo nil))))))
	(setq count (- count inc)))
      (point))))

(defun octave-forward-block (&optional arg)
  "Move forward across one balanced Octave begin-end block.
With argument, do it that many times.
Negative arg -N means move backward across N blocks."
  (interactive "p")
  (or arg (setq arg 1))
895
  (goto-char (or (octave-scan-blocks arg 0) (buffer-end arg))))
Richard M. Stallman's avatar
Richard M. Stallman committed
896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912

(defun octave-backward-block (&optional arg)
  "Move backward across one balanced Octave begin-end block.
With argument, do it that many times.
Negative arg -N means move forward across N blocks."
  (interactive "p")
  (or arg (setq arg 1))
  (octave-forward-block (- arg)))

(defun octave-down-block (arg)
  "Move forward down one begin-end block level of Octave code.
With argument, do this that many times.
A negative argument means move backward but still go down a level.
In Lisp programs, an argument is required."
  (interactive "p")
  (let ((inc (if (> arg 0) 1 -1)))
    (while (/= arg 0)
913
      (goto-char (or (octave-scan-blocks inc -1)
Richard M. Stallman's avatar
Richard M. Stallman committed
914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932
		     (buffer-end arg)))
      (setq arg (- arg inc)))))

(defun octave-backward-up-block (arg)
  "Move backward out of one begin-end block level of Octave code.
With argument, do this that many times.
A negative argument means move forward but still to a less deep spot.
In Lisp programs, an argument is required."
  (interactive "p")
  (octave-up-block (- arg)))

(defun octave-up-block (arg)
  "Move forward out of one begin-end block level of Octave code.
With argument, do this that many times.
A negative argument means move backward but still to a less deep spot.
In Lisp programs, an argument is required."
  (interactive "p")
  (let ((inc (if (> arg 0) 1 -1)))
    (while (/= arg 0)
933
      (goto-char (or (octave-scan-blocks inc 1)
Richard M. Stallman's avatar
Richard M. Stallman committed
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
		     (buffer-end arg)))
      (setq arg (- arg inc)))))

(defun octave-mark-block ()
  "Put point at the beginning of this Octave block, mark at the end.
The block marked is the one that contains point or follows point."
  (interactive)
  (let ((pos (point)))
    (if (or (and (octave-in-block-p)
		 (skip-syntax-forward "w"))
	    (condition-case nil
		(progn
		  (octave-down-block 1)
		  (octave-in-block-p))
	      (error nil)))
	(progn
	  (octave-up-block -1)
	  (push-mark (point))
	  (octave-forward-block)
	  (exchange-point-and-mark))
      (goto-char pos)
      (message "No block to mark found"))))

(defun octave-close-block ()
  "Close the current Octave block on a separate line.
An error is signaled if no block to close is found."
  (interactive)
  (let (bb-keyword)
    (condition-case nil
	(progn
	  (save-excursion
	    (octave-backward-up-block 1)
	    (setq bb-keyword (buffer-substring-no-properties
			      (match-beginning 1) (match-end 1))))
	  (if (save-excursion
		(beginning-of-line)
		(looking-at "^\\s-*$"))
	      (indent-according-to-mode)
	    (octave-reindent-then-newline-and-indent))
	  (insert (car (reverse
			(assoc bb-keyword
			       octave-block-match-alist))))
	  (octave-reindent-then-newline-and-indent)
	  t)
      (error (message "No block to close found")))))

(defun octave-blink-matching-block-open ()
  "Blink the matching Octave begin block keyword.
If point is right after an Octave else or end type block keyword, move
cursor momentarily to the corresponding begin keyword.
Signal an error if the keywords are incompatible."
  (interactive)
  (let (bb-keyword bb-arg eb-keyword pos eol)
    (if (and (octave-not-in-string-or-comment-p)
	     (looking-at "\\>")
	     (save-excursion
	       (skip-syntax-backward "w")
991
	       (octave-looking-at-kw octave-block-else-or-end-regexp)))
Richard M. Stallman's avatar
Richard M. Stallman committed
992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
	(save-excursion
	  (cond
	   ((match-end 1)
	    (setq eb-keyword
		  (buffer-substring-no-properties
		   (match-beginning 1) (match-end 1)))
	    (octave-backward-up-block 1))
	   ((match-end 2)
	    (setq eb-keyword
		  (buffer-substring-no-properties
		   (match-beginning 2) (match-end 2)))
	    (octave-backward-block)))
	  (setq pos (match-end 0)
		bb-keyword
		(buffer-substring-no-properties
		 (match-beginning 0) pos)
		pos (+ pos 1)
1009
		eol (line-end-position)
Richard M. Stallman's avatar
Richard M. Stallman committed
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
		bb-arg
		(save-excursion
		  (save-restriction
		    (goto-char pos)
		    (while (and (skip-syntax-forward "^<" eol)
				(octave-in-string-p)
				(not (forward-char 1))))
		    (skip-syntax-backward " ")
		    (buffer-substring-no-properties pos (point)))))
	  (if (member eb-keyword
		      (cdr (assoc bb-keyword octave-block-match-alist)))
	      (progn
		(message "Matches `%s %s'" bb-keyword bb-arg)
		(if (pos-visible-in-window-p)
		    (sit-for blink-matching-delay)))
	    (error "Block keywords `%s' and `%s' do not match"
		   bb-keyword eb-keyword))))))

(defun octave-beginning-of-defun (&optional arg)
  "Move backward to the beginning of an Octave function.
With positive ARG, do it that many times.  Negative argument -N means
move forward to Nth following beginning of a function.
Returns t unless search stops at the beginning or end of the buffer."
  (interactive "p")
  (let* ((arg (or arg 1))
	 (inc (if (> arg 0) 1 -1))
	 (found))
    (and (not (eobp))
1038
	 (not (and (> arg 0) (octave-looking-at-kw "\\<function\\>")))
Richard M. Stallman's avatar
Richard M. Stallman committed
1039 1040 1041
	 (skip-syntax-forward "w"))
    (while (and (/= arg 0)
		(setq found
1042
		      (octave-re-search-backward-kw "\\<function\\>" inc)))
Richard M. Stallman's avatar
Richard M. Stallman committed
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
      (if (octave-not-in-string-or-comment-p)
	  (setq arg (- arg inc))))
    (if found
	(progn
	  (and (< inc 0) (goto-char (match-beginning 0)))
	  t))))

(defun octave-end-of-defun (&optional arg)
  "Move forward to the end of an Octave function.
With positive ARG, do it that many times.  Negative argument -N means
move back to Nth preceding end of a function.

An end of a function occurs right after the end keyword matching the
`function' keyword that starts the function."
  (interactive "p")
  (or arg (setq arg 1))
  (and (< arg 0) (skip-syntax-backward "w"))
1060
  (and (> arg 0) (skip-syntax-forward "w"))
Richard M. Stallman's avatar
Richard M. Stallman committed
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
  (if (octave-in-defun-p)
      (setq arg (- arg 1)))
  (if (= arg 0) (setq arg -1))
  (if (octave-beginning-of-defun (- arg))
      (octave-forward-block)))

(defun octave-mark-defun ()
  "Put point at the beginning of this Octave function, mark at its end.
The function marked is the one containing point or following point."
  (interactive)
  (let ((pos (point)))
    (if (or (octave-in-defun-p)
	    (and (octave-beginning-of-defun -1)
		 (octave-in-defun-p)))
	(progn
	  (skip-syntax-forward "w")
	  (octave-beginning-of-defun)
	  (push-mark (point))
	  (octave-end-of-defun)
	  (exchange-point-and-mark))
      (goto-char pos)
      (message "No function to mark found"))))
1083

Richard M. Stallman's avatar
Richard M. Stallman committed
1084 1085 1086

;;; Filling
(defun octave-auto-fill ()
1087 1088 1089 1090 1091 1092
  "Perform auto-fill in Octave mode.
Returns nil if no feasible place to break the line could be found, and t
otherwise."
  (let (fc give-up)
    (if (or (null (setq fc (current-fill-column)))
	    (save-excursion
1093
	      (beginning-of-line)
1094
	      (and auto-fill-inhibit-regexp
1095
		   (octave-looking-at-kw auto-fill-inhibit-regexp))))
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
	nil				; Can't do anything
      (if (and (not (octave-in-comment-p))
	       (> (current-column) fc))
	  (setq fc (- fc (+ (length octave-continuation-string) 1))))
      (while (and (not give-up) (> (current-column) fc))
	(let* ((opoint (point))
	       (fpoint
		(save-excursion
		  (move-to-column (+ fc 1))
		  (skip-chars-backward "^ \t\n")
		  ;; If we're at the beginning of the line, break after
		  ;; the first word
		  (if (bolp)
		      (re-search-forward "[ \t]" opoint t))
		  ;; If we're in a comment line, don't break after the
		  ;; comment chars
		  (if (save-excursion
			(skip-syntax-backward " <")
			(bolp))
1115
		      (re-search-forward "[ \t]" (line-end-position)
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
					 'move))
		  ;; If we're not in a comment line and just ahead the
		  ;; continuation string, don't break here.
		  (if (and (not (octave-in-comment-p))
			   (looking-at
			    (concat "\\s-*"
				    (regexp-quote
				     octave-continuation-string)
				    "\\s-*$")))
		      (end-of-line))
		  (skip-chars-backward " \t")
		  (point))))
	  (if (save-excursion
		(goto-char fpoint)
		(not (or (bolp) (eolp))))
	      (let ((prev-column (current-column)))
		(if (save-excursion
		      (skip-chars-backward " \t")
		      (= (point) fpoint))
		    (progn
		      (octave-maybe-insert-continuation-string)
		      (indent-new-comment-line t))
		  (save-excursion
		    (goto-char fpoint)
		    (octave-maybe-insert-continuation-string)
		    (indent-new-comment-line t)))
		(if (>= (current-column) prev-column)
		    (setq give-up t)))
	    (setq give-up t))))
      (not give-up))))
Richard M. Stallman's avatar
Richard M. Stallman committed
1146 1147 1148

(defun octave-fill-paragraph (&optional arg)
 "Fill paragraph of Octave code, handling Octave comments."
1149 1150
 ;; FIXME: now that the default fill-paragraph takes care of similar issues,
 ;; this seems obsolete.  --Stef
Richard M. Stallman's avatar
Richard M. Stallman committed
1151
 (interactive "P")
1152
 (save-excursion
Richard M. Stallman's avatar
Richard M. Stallman committed
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
   (let ((end (progn (forward-paragraph) (point)))
	 (beg (progn
		(forward-paragraph -1)
		(skip-chars-forward " \t\n")
		(beginning-of-line)
		(point)))
	 (cfc (current-fill-column))
	 (ind (calculate-octave-indent))
	 comment-prefix)
     (save-restriction
       (goto-char beg)
       (narrow-to-region beg end)
       (if (listp ind) (setq ind (nth 1 ind)))
       (while (not (eobp))
	 (condition-case nil
	     (octave-indent-line ind)
	   (error nil))
	 (if (and (> ind 0)
		  (not
		   (save-excursion
		     (beginning-of-line)
		     (looking-at "^\\s-*\\($\\|\\s<+\\)"))))
	     (setq ind 0))
	 (move-to-column cfc)
	 ;; First check whether we need to combine non-empty comment lines
	 (if (and (< (current-column) cfc)
		  (octave-in-comment-p)
		  (not (save-excursion
			 (beginning-of-line)
			 (looking-at "^\\s-*\\s<+\\s-*$"))))
	     ;; This is a nonempty comment line which does not extend
Juanma Barranquero's avatar
Juanma Barranquero committed
1184
	     ;; past the fill column.  If it is followed by a nonempty
Richard M. Stallman's avatar
Richard M. Stallman committed
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
	     ;; comment line with the same comment prefix, try to
	     ;; combine them, and repeat this until either we reach the
	     ;; fill-column or there is nothing more to combine.
	     (progn
	       ;; Get the comment prefix
	       (save-excursion
		 (beginning-of-line)
		 (while (and (re-search-forward "\\s<+")
			     (not (octave-in-comment-p))))
		 (setq comment-prefix (match-string 0)))
	       ;; And keep combining ...
	       (while (and (< (current-column) cfc)
			   (save-excursion
			     (forward-line 1)
			     (and (looking-at
				   (concat "^\\s-*"
					   comment-prefix
					   "\\S<"))
				  (not (looking-at
					(concat "^\\s-*"
						comment-prefix
						"\\s-*$"))))))
		 (delete-char 1)
		 (re-search-forward comment-prefix)
		 (delete-region (match-beginning 0) (match-end 0))
		 (fixup-whitespace)
		 (move-to-column cfc))))
1212 1213
	 ;; We might also try to combine continued code lines>  Perhaps
	 ;; some other time ...
Richard M. Stallman's avatar
Richard M. Stallman committed
1214 1215 1216 1217 1218 1219
	 (skip-chars-forward "^ \t\n")
	 (delete-horizontal-space)
	 (if (or (< (current-column) cfc)
		 (and (= (current-column) cfc) (eolp)))
	     (forward-line 1)
	   (if (not (eolp)) (insert " "))
1220 1221
	   (or (octave-auto-fill)
	       (forward-line 1)))))
Richard M. Stallman's avatar
Richard M. Stallman committed
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
     t)))


;;; Completions
(defun octave-initialize-completions ()
  "Create an alist for Octave completions."
  (if octave-completion-alist
      ()
    (setq octave-completion-alist
	  (mapcar '(lambda (var) (cons var var))
		  (append octave-reserved-words
			  octave-text-functions
			  octave-variables)))))

(defun octave-complete-symbol ()
  "Perform completion on Octave symbol preceding point.
Compare that symbol against Octave's reserved words and builtin
variables."
  ;; This code taken from lisp-complete-symbol
  (interactive)
  (let* ((end (point))
	 (beg (save-excursion (backward-sexp 1) (point)))
	 (string (buffer-substring-no-properties beg end))
	 (completion (try-completion string octave-completion-alist)))
    (cond ((eq completion t))		; ???
	  ((null completion)
	   (message "Can't find completion for \"%s\"" string)
	   (ding))
	  ((not (string= string completion))
           (delete-region beg end)
           (insert completion))
	  (t
	   (let ((list (all-completions string octave-completion-alist))
		 (conf (current-window-configuration)))
	     ;; Taken from comint.el
1257
	     (message "Making completion list...")
Richard M. Stallman's avatar
Richard M. Stallman committed
1258
	     (with-output-to-temp-buffer "*Completions*"
1259
	       (display-completion-list list string))
Richard M. Stallman's avatar
Richard M. Stallman committed
1260 1261
	     (message "Hit space to flush")
	     (let (key first)
1262
	       (if (with-current-buffer (get-buffer "*Completions*")
Richard M. Stallman's avatar
Richard M. Stallman committed
1263 1264 1265 1266 1267 1268 1269 1270
		     (setq key (read-key-sequence nil)
			   first (aref key 0))
		     (and (consp first) (consp (event-start first))
			  (eq (window-buffer (posn-window (event-start
							   first)))
			      (get-buffer "*Completions*"))
			  (eq (key-binding key) 'mouse-choose-completion)))
		   (progn
1271 1272 1273
		     (if (fboundp 'mouse-choose-completion)
			 (mouse-choose-completion first)
		       (choose-completion first)) ; Emacs >= 23.2