· 10 years ago · Mar 10, 2016, 06:48 AM
1;;; matlab.el --- major mode for MATLAB(R) dot-m files
2;;
3;; Author: Matt Wette <mwette@alumni.caltech.edu>,
4;; Eric M. Ludlam <eludlam@mathworks.com>
5;; Maintainer: Eric M. Ludlam <eludlam@mathworks.com>
6;; Created: 04 Jan 91
7;; Keywords: MATLAB(R)
8;; Version:
9
10(defconst matlab-mode-version "3.3.1"
11 "Current version of MATLAB(R) mode.")
12
13;;
14;; Copyright (C) 2004-2010 The Mathworks, Inc
15;; Copyright (C) 1997-2004 Eric M. Ludlam: The MathWorks, Inc
16;; Copyright (C) 1991-1997 Matthew R. Wette
17;;
18;; This program is free software; you can redistribute it and/or modify
19;; it under the terms of the GNU General Public License as published by
20;; the Free Software Foundation; either version 2, or (at your option)
21;; any later version.
22;;
23;; This program is distributed in the hope that it will be useful,
24;; but WITHOUT ANY WARRANTY; without even the implied warranty of
25;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26;; GNU General Public License for more details.
27;;
28;; You should have received a copy of the GNU General Public License
29;; along with GNU Emacs; see the file COPYING. If not, write to
30;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
31;;
32;;; Commentary:
33;;
34;; This major mode for GNU Emacs provides support for editing MATLAB(R) dot-m
35;; files. It automatically indents for block structures (including nested
36;; functions), line continuations (e.g., ...), and comments.
37;;
38;; Additional features include auto-fill including auto-additions of
39;; ellipsis for commands, and even strings. Block/end construct
40;; highlighting as you edit. Primitive code-verification and
41;; identification. Templates and other code editing functions.
42;; Advanced symbol completion. Code highlighting via font-lock.
43;; There are many navigation commands that let you move across blocks
44;; of code at different levels.
45;;
46;; Lastly, there is support for running MATLAB(R) in an Emacs buffer,
47;; with full shell history and debugger support (when used with the db
48;; commands.) The shell can be used as an online help while editing
49;; code, providing help on functions, variables, or running arbitrary
50;; blocks of code from the buffer you are editing.
51
52;;; Code:
53
54(require 'easymenu)
55(require 'tempo)
56(require 'derived)
57
58;; compatibility
59(if (string-match "X[Ee]macs" emacs-version)
60 (progn
61 (defalias 'matlab-make-overlay 'make-extent)
62 (defalias 'matlab-overlay-put 'set-extent-property)
63 (defalias 'matlab-overlay-get 'extent-property)
64 (defalias 'matlab-delete-overlay 'delete-extent)
65 (defalias 'matlab-overlay-start 'extent-start-position)
66 (defalias 'matlab-overlay-end 'extent-end-position)
67 (defalias 'matlab-previous-overlay-change 'previous-extent-change)
68 (defalias 'matlab-next-overlay-change 'next-extent-change)
69 (defalias 'matlab-overlays-at
70 (lambda (pos) (extent-list nil pos pos)))
71 (defalias 'matlab-cancel-timer 'delete-itimer)
72 (defun matlab-run-with-idle-timer (secs repeat function &rest args)
73 (condition-case nil
74 (apply 'start-itimer
75 "matlab" function secs
76 (if repeat secs nil) t
77 t (car args))
78 (error
79 ;; If the above doesn't work, then try this old version of
80 ;; start itimer.
81 (start-itimer "matlab" function secs (if repeat secs nil)))))
82 )
83 (defalias 'matlab-make-overlay 'make-overlay)
84 (defalias 'matlab-overlay-put 'overlay-put)
85 (defalias 'matlab-overlay-get 'overlay-get)
86 (defalias 'matlab-delete-overlay 'delete-overlay)
87 (defalias 'matlab-overlay-start 'overlay-start)
88 (defalias 'matlab-overlay-end 'overlay-end)
89 (defalias 'matlab-previous-overlay-change 'previous-overlay-change)
90 (defalias 'matlab-next-overlay-change 'next-overlay-change)
91 (defalias 'matlab-overlays-at 'overlays-at)
92 (defalias 'matlab-cancel-timer 'cancel-timer)
93 (defalias 'matlab-run-with-idle-timer 'run-with-idle-timer)
94 )
95
96(cond ((fboundp 'point-at-bol)
97 (defalias 'matlab-point-at-bol 'point-at-bol)
98 (defalias 'matlab-point-at-eol 'point-at-eol))
99 ;; Emacs 20.4
100 ((fboundp 'line-beginning-position)
101 (defalias 'matlab-point-at-bol 'line-beginning-position)
102 (defalias 'matlab-point-at-eol 'line-end-position))
103 (t
104 (defmacro matlab-point-at-bol ()
105 (save-excursion (beginning-of-line) (point)))
106 (defmacro matlab-point-at-eol ()
107 (save-excursion (end-of-line) (point)))))
108
109(defmacro matlab-run-in-matlab-mode-only (&rest body)
110 "Execute BODY only if the active buffer is a MATLAB(R) M-file buffer."
111 `(if (eq major-mode 'matlab-mode)
112 (progn
113 ,@body)
114 (error "This command works only in a MATLAB M-file buffer")))
115
116(defun matlab-with-emacs-link ()
117 "Return non-nil if Emacs Link is running and user wants to use it."
118 (and (featurep 'matlab-eei)
119 matlab-use-eei
120 matlab-eei-process))
121
122;;; User-changeable variables =================================================
123
124;; Variables which the user can change
125(defgroup matlab nil
126 "MATLAB(R) mode."
127 :prefix "matlab-"
128 :group 'languages)
129
130(defcustom matlab-indent-level 4
131 "*The basic indentation amount in `matlab-mode'."
132 :group 'matlab
133 :type 'integer)
134
135(defcustom matlab-cont-level 4
136 "*Basic indentation after continuation if no other methods are found."
137 :group 'matlab
138 :type 'integer)
139
140(defcustom matlab-cont-requires-ellipsis t
141 "*Specify if ellipses are required at the end of a line for continuation.
142Future versions of Matlab may not require ellipses ... , so a heuristic
143determining if there is to be continuation is used instead."
144 :group 'matlab
145 :type 'integer)
146
147(defcustom matlab-case-level '(2 . 2)
148 "*How far to indent case/otherwise statements in a switch.
149This can be an integer, which is the distance to indent the CASE and
150OTHERWISE commands, and how far to indent commands appearing in CASE
151and OTHERWISE blocks. It can also be a cons cell which is of form
152 (CASEINDENT . COMMANDINDENT)
153where CASEINDENT is the indentation of the CASE and OTHERWISE
154statements, and COMMANDINDENT is the indentation of commands appearing
155after the CASE or OTHERWISE command.
156
157Note: Currently a bug exists if:
158 CASEINDENT+COMMANDINDENT != `matlab-indent-level'
159so if you customize these variables, follow the above rule, and you
160should be ok."
161 :group 'matlab
162 :type 'sexp)
163
164(defcustom matlab-indent-function-body 'guess
165 "*If non-nil, indent body of function.
166If the global value is nil, do not indent function bodies.
167If the global value is t, always indent function bodies.
168If the global value is 'guess, then the local value will be set to
169either nil or t when the MATLAB mode is started in a buffer based on the
170file's current indentation.
171If the global value is 'MathWorks-Standard, then the local value is not
172changed, and functions are indented based on `matlab-functions-have-end'."
173 :group 'matlab
174 :type '(choice (const :tag "Always" t)
175 (const :tag "Never" nil)
176 (const :tag "Guess" 'guess)
177 (const :tag "MathWorks Standard"
178 'MathWorks-Standard))
179 )
180
181(make-variable-buffer-local 'matlab-indent-function-body)
182
183(defcustom matlab-functions-have-end nil
184 "*If non-nil, functions-have-end minor mode is on by default."
185 :group 'matlab
186 :type 'boolean)
187
188(make-variable-buffer-local 'matlab-functions-have-end)
189
190(defun matlab-toggle-functions-have-end ()
191 (interactive)
192 (matlab-toggle-functions-have-end-minor-mode))
193
194;; The following minor mode is on if and only if the above variable is true;
195(easy-mmode-define-minor-mode matlab-functions-have-end-minor-mode
196 "Toggle functions-have-end minor mode, indicating function/end pairing."
197 nil
198 (condition-case nil ;; avoid parse error on xemacs
199 (eval (read "#(\" function...end\" 0 15 (face (font-lock-keyword-face) fontified t))"))
200 (error " function...end"))
201 nil ; empty mode-map
202 ;; body of matlab-functions-have-end-minor-mode
203 (if matlab-functions-have-end-minor-mode
204 (setq matlab-functions-have-end t)
205 (setq matlab-functions-have-end nil)
206 )
207)
208
209(defun matlab-do-functions-have-end-p ()
210 "Non-nil if the first function in the current buffer terminates with end."
211 (save-excursion
212 (goto-char (point-min))
213 (if (re-search-forward matlab-defun-regex nil t)
214 (let ((matlab-functions-have-end t))
215 (beginning-of-line)
216 (condition-case nil
217 (progn (matlab-forward-sexp) t)
218 (error nil))
219 )
220 nil
221 )
222 ))
223
224(defun matlab-toggle-functions-have-end-minor-mode ()
225 (matlab-functions-have-end-minor-mode)
226 (if (and matlab-functions-have-end-minor-mode (not (eq major-mode 'matlab-mode)))
227 (progn
228 (matlab-functions-have-end-minor-mode -1)
229 (error "functions-have-end minor mode is only for MATLAB Major mode")))
230 (setq matlab-functions-have-end matlab-functions-have-end-minor-mode))
231
232(defun matlab-indent-function-body-p ()
233 "Non-nil if functions bodies are indented.
234See `matlab-indent-function-body' variable."
235 (if (eq matlab-indent-function-body 'MathWorks-Standard)
236 ;; Dec '09
237 ;; The MathWorks standard is the same as if functions have end.
238 matlab-functions-have-end
239 ;; Else, just return the variable.
240 matlab-indent-function-body))
241
242(defcustom matlab-indent-past-arg1-functions
243 "[sg]et\\(_param\\)?\\|waitfor"
244 "*Regex describing functions whose first arg is special.
245This specialness means that all following parameters which appear on
246continued lines should appear indented to line up with the second
247argument, not the first argument."
248 :group 'matlab
249 :type 'string)
250
251(defcustom matlab-arg1-max-indent-length 15
252 "*The maximum length to indent when indenting past arg1.
253If arg1 is exceptionally long, then only this number of characters
254will be indented beyond the open paren starting the parameter list.")
255
256(defcustom matlab-maximum-indents '(;; = is a convenience. Don't go too far
257 (?= . (10 . 4))
258 ;; Fns should provide hard limits
259 (?\( . 50)
260 ;; Matrix/Cell arrays
261 (?\[ . 20)
262 (?\{ . 20))
263 "Alist of maximum indentations when lining up code.
264Each element is of the form (CHAR . INDENT) where char is a character
265the indent engine is using, and INDENT is the maximum indentation
266allowed. Indent could be of the form (MAXIMUM . INDENT), where
267MAXIMUM is the maximum allowed calculated indent, and INDENT is the
268amount to use if MAXIMUM is reached."
269 :group 'matlab
270 :type '(repeat (cons (character :tag "Open List Character")
271 (sexp :tag "Number (max) or cons (max indent)"))))
272
273(defcustom matlab-handle-simulink t
274 "*If true, add in a few simulink customizations.
275This variable's state is mostly useful when set at load time when
276simulink font lock keywords can be removed. This will handle
277additional cases as the need arrises."
278 :group 'matlab
279 :type 'boolean)
280
281(defcustom matlab-auto-fill t
282 "*If true, set variable `auto-fill-function' to our function at startup."
283 :group 'matlab
284 :type 'boolean)
285
286(defcustom matlab-fill-fudge 10
287 "Number of characters around `fill-column' we can fudge filling.
288Basically, there are places that are very convenient to fill at, but
289might not be the closest fill spot, or occur after `fill-column'.
290If they occur within this fudge factor, we will use them.
291Also, if none of the above occur, and we find a symbol to break at,
292but an open paren (group) starts or ends within this fudge factor,
293move there to boost the amount of fill leverage we can get."
294 :group 'matlab
295 :type 'integer)
296
297(defcustom matlab-fill-fudge-hard-maximum 79
298 "The longest line allowed when auto-filling code.
299This overcomes situations where the `fill-column' plus the
300`matlab-fill-fudge' is greater than some hard desired limit."
301 :group 'matlab
302 :type 'integer)
303
304(defcustom matlab-elipsis-string "..."
305 "Text used to perform continuation on code lines.
306This is used to generate and identify continuation lines.")
307
308(defcustom matlab-fill-code t
309 "*If true, `auto-fill-mode' causes code lines to be automatically continued."
310 :group 'matlab
311 :type 'boolean)
312
313(defcustom matlab-fill-count-ellipsis-flag t
314 "*Non-nil means to count the ellipsis when auto filling.
315This effectively shortens the `fill-column' by the length of
316`matlab-elipsis-string'.")
317
318(defcustom matlab-fill-strings-flag t
319 "*Non-nil means that when auto-fill is on, strings are broken across lines.
320If `matlab-fill-count-ellipsis-flag' is non nil, this shortens the
321`fill-column' by the length of `matlab-elipsis-string'.")
322
323(defcustom matlab-comment-column 40
324 "*The goal comment column in `matlab-mode' buffers."
325 :group 'matlab
326 :type 'integer)
327
328(defcustom matlab-comment-anti-indent 0
329 "*Amount of anti-indentation to use for comments in relation to code."
330 :group 'matlab
331 :type 'integer)
332
333(defcustom matlab-comment-line-s "% "
334 "*String to start comment on line by itself."
335 :group 'matlab
336 :type 'string)
337
338(defcustom matlab-comment-on-line-s "% "
339 "*String to start comment on line with code."
340 :group 'matlab
341 :type 'string)
342
343(defcustom matlab-comment-region-s "% $$$ "
344 "*String inserted by \\[matlab-comment-region] at start of each line in \
345region."
346 :group 'matlab
347 :type 'string)
348
349(defcustom matlab-verify-on-save-flag t
350 "*Non-nil means to verify M whenever we save a file."
351 :group 'matlab
352 :type 'boolean)
353
354(defcustom matlab-mode-verify-fix-functions
355 '(matlab-mode-vf-functionname)
356 "List of function symbols which perform a verification and fix to M code.
357Each function gets no arguments, and returns nothing. They can move
358point, but it will be restored for them."
359 :group 'matlab
360 :type '(repeat (choice :tag "Function: "
361 '(matlab-mode-vf-functionname
362 matlab-mode-vf-block-matches-forward
363 matlab-mode-vf-block-matches-backward
364 matlab-mode-vf-quiesce-buffer
365 ))))
366
367(defcustom matlab-block-verify-max-buffer-size 50000
368 "*Largest buffer size allowed for block verification during save."
369 :group 'matlab
370 :type 'integer)
371
372;; It is time to disable this.
373(defcustom matlab-vers-on-startup nil
374 "*If non-nil, show the version number on startup."
375 :group 'matlab
376 :type 'boolean)
377
378(defcustom matlab-highlight-block-match-flag t
379 "*Non-nil means to highlight the matching if/end/whatever.
380The highlighting only occurs when the cursor is on a block start or end
381keyword."
382 :group 'matlab
383 :type 'boolean)
384
385(defcustom matlab-show-periodic-code-details-flag nil
386 "*Non-nil means to show code details in the minibuffer.
387This will only work if `matlab-highlight-block-match-flag' is non-nil."
388 :group 'matlab
389 :type 'boolean)
390
391(defcustom matlab-use-eei t
392 "*Use Emacs Link for save-and-go and run-region."
393 :group 'matlab
394 :type 'boolean)
395
396(defcustom matlab-mode-hook nil
397 "*List of functions to call on entry to MATLAB mode."
398 :group 'matlab
399 :type 'hook)
400
401(defcustom matlab-completion-technique 'complete
402 "*How the `matlab-complete-symbol' interfaces with the user.
403Valid values are:
404
405'increment - which means that new strings are tried with each
406 successive call until all methods are exhausted.
407 (Similar to `hippie-expand'.)
408'complete - Which means that if there is no single completion, then
409 all possibilities are displayed in a completion buffer."
410 :group 'matlab
411 :type '(radio (const :tag "Incremental completion (hippie-expand)."
412 increment)
413 (const :tag "Show completion buffer."
414 complete)))
415
416(defcustom matlab-show-mlint-warnings nil
417 "*If non-nil, show mlint warnings."
418 :group 'matlab
419 :type 'boolean)
420
421(make-variable-buffer-local 'matlab-show-mlint-warnings)
422
423(defcustom matlab-highlight-cross-function-variables nil
424 "*If non-nil, highlight cross-function variables."
425 :group 'matlab
426 :type 'boolean)
427
428(make-variable-buffer-local 'matlab-highlight-cross-function-variables)
429
430(defcustom matlab-return-add-semicolon nil
431 "*If non nil, check to see a semicolon is needed when RET is pressed."
432 :group 'matlab
433 :type 'boolean)
434
435(make-variable-buffer-local 'matlab-return-add-semicolon)
436
437;; Load in the region we use for highlighting stuff.
438(if (and (featurep 'custom) (fboundp 'custom-declare-variable))
439
440 (let ((l-region-face (if (facep 'region) 'region 'zmacs-region)))
441 ;; If we have custom, we can make our own special face like this
442 (defface matlab-region-face
443 (list
444 (list t
445 (list :background (face-background l-region-face)
446 :foreground (face-foreground l-region-face))))
447 "*Face used to highlight a matlab region."
448 :group 'matlab))
449
450 ;; If we do not, then we can fake it by copying 'region.
451 (cond ((facep 'region)
452 (copy-face 'region 'matlab-region-face))
453 (t
454 (copy-face 'zmacs-region 'matlab-region-face))))
455
456(defvar matlab-unterminated-string-face 'matlab-unterminated-string-face
457 "Self reference for unterminated string face.")
458
459(defvar matlab-simulink-keyword-face 'matlab-simulink-keyword-face
460 "Self reference for simulink keywords.")
461
462(defvar matlab-nested-function-keyword-face 'matlab-nested-function-keyword-face
463 "Self reference for nested function/end keywords.")
464
465(defvar matlab-cross-function-variable-face 'matlab-cross-function-variable-face
466 "Self reference for cross-function variables.")
467
468(defvar matlab-cellbreak-face 'matlab-cellbreak-face
469 "Self reference for cellbreaks.")
470
471(defun matlab-font-lock-adjustments ()
472 "Make adjustments for font lock.
473If font lock is not loaded, lay in wait."
474 (if (and (featurep 'custom) (fboundp 'custom-declare-variable))
475
476 (progn
477 (defface matlab-unterminated-string-face
478 (list
479 (list t
480 (list :background (face-background font-lock-string-face)
481 :foreground (face-foreground font-lock-string-face)
482 :underline t)))
483 "*Face used to highlight unterminated strings."
484 :group 'matlab)
485 (defface matlab-simulink-keyword-face
486 (list
487 (list t
488 (list :background (face-background font-lock-type-face)
489 :foreground (face-foreground font-lock-type-face)
490 :underline t)))
491 "*Face used to highlight simulink specific functions."
492 :group 'matlab)
493 (defface matlab-nested-function-keyword-face
494 (list
495 (list t
496 (list :slant 'italic)))
497 "*Face to use for cross-function variables.")
498 (defface matlab-cross-function-variable-face
499 (list
500 (list t
501 (list :weight 'bold
502 :slant 'italic)))
503 "*Face to use for cross-function variables."
504 :group 'matlab)
505 (defface matlab-cellbreak-face
506 (list
507 (list t
508 (list :background (face-background font-lock-comment-face)
509 :foreground (face-foreground font-lock-comment-face)
510 :overline t
511 :bold t)))
512 "*Face to use for cellbreak %% lines.")
513 )
514
515 ;; Now, lets make the unterminated string face
516 (cond ((facep 'font-lock-string-face)
517 (copy-face 'font-lock-string-face
518 'matlab-unterminated-string-face))
519 (t
520 (make-face 'matlab-unterminated-string-face)))
521 (set-face-underline-p 'matlab-unterminated-string-face t)
522
523 ;; Now make some simulink faces
524 (cond ((facep 'font-lock-type-face)
525 (copy-face 'font-lock-type-face 'matlab-simulink-keyword-face))
526 (t
527 (make-face 'matlab-simulink-keyword-face)))
528 (set-face-underline-p 'matlab-simulink-keyword-face t)
529
530 ;; Now make some nested function/end keyword faces
531 (cond ((facep 'font-lock-type-face)
532 (copy-face 'font-lock-type-face 'matlab-nested-function-keyword-face))
533 (t
534 (make-face 'matlab-nested-function-keyword-face)))
535
536 ;; Now make some cross-function variable faces
537 (cond ((facep 'font-lock-type-face)
538 (copy-face 'font-lock-type-face 'matlab-cross-function-variable-face))
539 (t
540 (make-face 'matlab-cross-function-variable-face)))
541 (set-face-bold-p 'matlab-cross-function-variable-face t)
542
543 ;; Now make some cellbreak variable faces
544 (cond ((facep 'font-comment-face)
545 (copy-face 'font-lock-comment-face 'matlab-cellbreak-face))
546 (t
547 (make-face 'matlab-cellbreak-face)))
548 (set-face-bold-p 'matlab-cellbreak-face t)
549 (condition-case nil
550 (set-face-attribute 'matlab-cellbreak-face nil :overline t)
551 (error nil))
552 )
553 (remove-hook 'font-lock-mode-hook 'matlab-font-lock-adjustments))
554
555;; Make the adjustments for font lock after it's loaded.
556;; I found that eval-after-load was unreliable.
557(if (featurep 'font-lock)
558 (matlab-font-lock-adjustments)
559 (add-hook 'font-lock-mode-hook 'matlab-font-lock-adjustments))
560
561
562;;; MATLAB mode variables =====================================================
563
564(defvar matlab-tempo-tags nil
565 "List of templates used in MATLAB mode.")
566
567;; syntax table
568(defvar matlab-mode-syntax-table
569 (let ((st (make-syntax-table (standard-syntax-table))))
570 (modify-syntax-entry ?_ "_" st)
571 (modify-syntax-entry ?% "<" st)
572 (modify-syntax-entry ?\n ">" st)
573 (modify-syntax-entry ?\\ "." st)
574 (modify-syntax-entry ?\t " " st)
575 (modify-syntax-entry ?+ "." st)
576 (modify-syntax-entry ?- "." st)
577 (modify-syntax-entry ?* "." st)
578 (modify-syntax-entry ?' "." st)
579 (modify-syntax-entry ?/ "." st)
580 (modify-syntax-entry ?= "." st)
581 (modify-syntax-entry ?< "." st)
582 (modify-syntax-entry ?> "." st)
583 (modify-syntax-entry ?& "." st)
584 (modify-syntax-entry ?| "." st)
585 st)
586 "The syntax table used in `matlab-mode' buffers.")
587
588(defvar matlab-mode-special-syntax-table
589 (let ((st (copy-syntax-table matlab-mode-syntax-table)))
590 ;; Make _ a part of words so we can skip them better
591 (modify-syntax-entry ?_ "w" st)
592 st)
593 "The syntax table used when navigating blocks.")
594
595;; abbrev table
596(defvar matlab-mode-abbrev-table nil
597 "The abbrev table used in `matlab-mode' buffers.")
598
599(define-abbrev-table 'matlab-mode-abbrev-table ())
600
601;;; Keybindings ===============================================================
602
603(defvar matlab-help-map
604 (let ((km (make-sparse-keymap)))
605 (define-key km "r" 'matlab-shell-run-command)
606 (define-key km "f" 'matlab-shell-describe-command)
607 (define-key km "a" 'matlab-shell-apropos)
608 (define-key km "v" 'matlab-shell-describe-variable)
609 (define-key km "t" 'matlab-shell-topic-browser)
610 km)
611 "The help key map for `matlab-mode' and `matlab-shell-mode'.")
612
613(defvar matlab-insert-map
614 (let ((km (make-sparse-keymap)))
615 (define-key km "c" 'matlab-insert-next-case)
616 (define-key km "e" 'matlab-insert-end-block)
617 (define-key km "i" 'tempo-template-matlab-if)
618 (define-key km "I" 'tempo-template-matlab-if-else)
619 (define-key km "f" 'tempo-template-matlab-for)
620 (define-key km "s" 'tempo-template-matlab-switch)
621 (define-key km "t" 'tempo-template-matlab-try)
622 (define-key km "w" 'tempo-template-matlab-while)
623 (define-key km "F" 'tempo-template-matlab-function)
624 (define-key km "'" 'matlab-stringify-region)
625 ;; Not really inserts, but auto coding stuff
626 (define-key km "\C-s" 'matlab-ispell-strings)
627 (define-key km "\C-c" 'matlab-ispell-comments)
628 km)
629 "Keymap used for inserting simple texts based on context.")
630
631;; mode map
632(defvar matlab-mode-map
633 (let ((km (make-sparse-keymap)))
634 (define-key km [return] 'matlab-return)
635 (define-key km "%" 'matlab-electric-comment)
636 (define-key km "\C-c;" 'matlab-comment-region)
637 (define-key km "\C-c:" 'matlab-uncomment-region)
638 (define-key km [(control c) return] 'matlab-comment-return)
639 (define-key km [(control c) (control c)] matlab-insert-map)
640 (define-key km [(control c) (control f)] 'matlab-fill-comment-line)
641 (define-key km [(control c) (control j)] 'matlab-justify-line)
642 (define-key km [(control c) (control q)] 'matlab-fill-region)
643 (define-key km [(control c) (control s)] 'matlab-shell-save-and-go)
644 (define-key km [(control c) (control r)] 'matlab-shell-run-region)
645 (define-key km [(meta control return)] 'matlab-shell-run-cell)
646 (define-key km [(control c) (control t)] 'matlab-show-line-info)
647 (define-key km [(control c) ?. ] 'matlab-find-file-on-path)
648 (define-key km [(control h) (control m)] matlab-help-map)
649 (define-key km [(control j)] 'matlab-linefeed)
650 (define-key km "\M-\r" 'newline)
651 (define-key km [(meta \;)] 'matlab-comment)
652 (define-key km [(meta q)] 'matlab-fill-paragraph)
653 (define-key km [(meta a)] 'matlab-beginning-of-command)
654 (define-key km [(meta e)] 'matlab-end-of-command)
655 (define-key km [(meta j)] 'matlab-comment-line-break-function)
656 (define-key km [(meta s)] 'matlab-show-matlab-shell-buffer)
657 (define-key km "\M-\t" 'matlab-complete-symbol)
658 (define-key km [(meta control f)] 'matlab-forward-sexp)
659 (define-key km [(meta control b)] 'matlab-backward-sexp)
660 (define-key km [(meta control q)] 'matlab-indent-sexp)
661 (define-key km [(meta control a)] 'matlab-beginning-of-defun)
662 (define-key km [(meta control e)] 'matlab-end-of-defun)
663 (if (string-match "XEmacs" emacs-version)
664 (define-key km [(control meta button1)] 'matlab-find-file-click)
665 (define-key km [(control meta mouse-2)] 'matlab-find-file-click))
666 (substitute-key-definition 'comment-region 'matlab-comment-region
667 km) ; global-map ;torkel
668 km)
669 "The keymap used in `matlab-mode'.")
670
671;;; Font locking keywords =====================================================
672
673(defvar matlab-string-start-regexp "\\(^\\|[^]})a-zA-Z0-9_.']\\)"
674 "Regexp used to represent the character before the string char '.
675The ' character has restrictions on what starts a string which is needed
676when attempting to understand the current context.")
677
678;; To quote a quote, put two in a row, thus we need an anchored
679;; first quote. In addition, we don't want to color strings in comments.
680(defvar matlab-string-end-regexp "[^'\n]*\\(''[^'\n]*\\)*'"
681 "Regexp used to represent the character pattern for ending a string.
682The ' character can be used as a transpose, and can transpose transposes.
683Therefore, to end, we must check all that goop.")
684
685(defun matlab-font-lock-string-match-normal (limit)
686 "When font locking strings, call this function for normal strings.
687Argument LIMIT is the maximum distance to scan."
688 (matlab-font-lock-string-match-here
689 (concat matlab-string-start-regexp
690 "\\('" matlab-string-end-regexp "\\)"
691 "\\([^']\\|$\\)")
692 limit))
693
694(defun matlab-font-lock-string-match-unterminated (limit)
695 "When font locking strings, call this function for normal strings.
696Argument LIMIT is the maximum distance to scan."
697 (matlab-font-lock-string-match-here
698 (concat matlab-string-start-regexp "\\('[^'\n]*\\(''[^'\n]*\\)*\\)$")
699 limit))
700
701(defun matlab-font-lock-string-match-here (regex limit)
702 "When font-locking strings, call this function to determine a match.
703Argument REGEX is the expression to scan for. Match 2 must be the string.
704Argument LIMIT is the maximum distance to scan."
705 (let (e)
706 (while (and (re-search-forward regex limit t)
707 (progn
708 ;; This gets us out of a comment after the string.
709 (setq e (match-end 2))
710 (goto-char (match-beginning 2))
711 (prog1
712 (or (matlab-cursor-in-comment)
713 (if (bolp) nil
714 (save-excursion
715 (forward-char -1)
716 (matlab-cursor-in-string))))
717 (goto-char e))))
718 (setq e nil))
719 (if (not e)
720 nil
721 (goto-char e)
722 t)))
723
724(defun matlab-font-lock-comment-match (limit)
725 "When font-locking comments, call this function to determine a match.
726Argument LIMIT is the maximum distance to scan."
727 (let (e)
728 (while (and (re-search-forward "\\(%[^%\n]*\\)" limit t)
729 (progn
730 (setq e (match-end 1))
731 (member (get-text-property (match-beginning 0) 'face)
732 '(font-lock-string-face
733 matlab-unterminated-string-face))))
734 (setq e nil))
735 (if (not e)
736 nil
737 (goto-char e)
738 t)))
739
740(defun matlab-find-unreachable-code (limit)
741 "Find code that is if'd out with if(0) or if(false), and mark it as a comment.
742The if(0) and else/end construct should be highlighted differently.
743Argument LIMIT is the maximum distance to search."
744 (if (and (< (point) limit)
745 (re-search-forward
746 "\\<\\(if\\>\\s-*(?\\s-*\\(0\\|false\\)\\s-*)?$\\)"
747 limit t))
748 (let ((b1 (match-beginning 1))
749 (e1 (match-end 1))
750 (b2 nil) (e2 nil)
751 (b3 nil) (e3 nil))
752 (goto-char b1)
753 (condition-case nil
754 (progn
755 ;; Go forward over the matlab sexp. Include scanning
756 ;; for ELSE since parts of the ELSE block are not
757 ;; `commented out'.
758 (matlab-forward-sexp t)
759 (forward-word -1)
760 ;; Is there an ELSE in this block?
761 (if (looking-at (matlab-block-mid-re))
762 (progn
763 (setq b3 (match-beginning 0)
764 e3 (match-end 0))
765 ;; Now find the REAL end.
766 (matlab-forward-sexp)
767 (forward-word -1)))
768 ;; End of block stuff
769 (if (looking-at (matlab-block-end-re))
770 (progn
771 (setq b2 (match-beginning 0)
772 e2 (match-end 0))
773 ;; make sure something exists...
774 (if (not b3) (setq b3 b2 e3 e2)))
775 (error "Eh?"))
776 ;; Ok, build up some match data.
777 (set-match-data
778 (list b1 e2 ;the real deal.
779 b1 e1 ;if (0)
780 b2 e2 ;end
781 b3 e3 ;else (if applicable.)
782 b1 e3)) ;body commented out.
783 t)
784 (error nil)))))
785
786(defun matlab-font-lock-nested-function-keyword-match (limit)
787 "Find next nested function/end keyword for font-lock.
788Argument LIMIT is the maximum distance to search."
789; Because of the way overlays are setup, the cursor will be sitting
790; on either a "function" or "end" keyword.
791 (catch 'result
792 (let ((pos (point))
793 overlays)
794 (while (< pos limit)
795 (setq overlays (matlab-overlays-at pos))
796 (while overlays
797 (let ((overlay (car overlays)))
798 (when (matlab-overlay-get overlay 'nested-function)
799 (when (= pos (matlab-overlay-start overlay))
800 (goto-char pos)
801 ;; The following line presumably returns true.
802 (throw 'result (re-search-forward "function" (+ pos 8) t)))
803 (let ((end-of-overlay (- (matlab-overlay-end overlay) 3)))
804 (when (<= pos end-of-overlay)
805 (goto-char end-of-overlay)
806 (throw 'result
807 (re-search-forward "end" (+ end-of-overlay 3) t))))))
808 (setq overlays (cdr overlays)))
809 (setq pos (matlab-next-overlay-change pos)))
810 nil ;; no matches, stop
811 )))
812
813(defun matlab-font-lock-cross-function-variables-match (limit)
814 "Find next cross-function variable for font-lock.
815Argument LIMIT is the maximum distance to search."
816 (catch 'result
817 (let ((pos (point))
818 overlays variables)
819 (while (< pos limit)
820 (let ((overlays (matlab-overlays-at pos)))
821 (while overlays
822 (let ((overlay (car overlays)))
823 (setq variables (matlab-overlay-get
824 overlay 'cross-function-variables))
825 (if variables
826 (progn
827 (goto-char pos)
828 (setq pos (min limit (matlab-overlay-end overlay)))
829 (if (re-search-forward variables pos t)
830 (progn
831 (throw 'result t))))))
832 (setq overlays (cdr overlays))))
833 (setq pos (matlab-next-overlay-change pos)))
834 nil ;; no matches, stop
835 )))
836
837(defun matlab-find-block-comments (limit)
838 "Find code that is commented out with %{ until %}.
839Argument LIMIT is the maximum distance to search."
840 (if (and (< (point) limit)
841 (re-search-forward "%{" limit t))
842 (let ((b1 (match-beginning 0))
843 (e1 (match-end 0))
844 (b2 nil) (e2 nil)
845 (b3 nil) (e3 nil))
846 (goto-char b1)
847 (forward-char -1)
848 (when (not (matlab-cursor-in-comment))
849 (setq b2 (re-search-forward "%}" limit t))
850 (when b2
851 (setq b2 (match-beginning 0)
852 e2 (match-end 0))
853 (set-match-data
854 (list b1 e2 ; full match
855 b1 e2 ; the full comment
856 b1 e1 ; the block start
857 b2 e2 ; the block end
858 ))
859 t
860 )))))
861
862(defcustom matlab-keyword-list '("global" "persistent" "for" "parfor" "while"
863 "spmd" "if" "elseif" "else"
864 "endfunction" "return" "break" "continue"
865 "switch" "case" "otherwise" "try"
866 "catch" "tic" "toc"
867 ;; MCOS keywords
868 "classdef" "properties" "methods" "enumeration"
869 )
870 "List of keywords for MATLAB used in highlighting.
871Customizing this variable is only useful if `regexp-opt' is available."
872 :group 'matlab
873 :type '(repeat (string :tag "Keyword: ")))
874
875(defcustom matlab-handle-graphics-list '("figure" "axes" "axis" "line"
876 "surface" "patch" "text" "light"
877 "image" "set" "get" "uicontrol"
878 "uimenu" "uitoolbar"
879 "uitoggletool" "uipushtool"
880 "uicontext" "uicontextmenu"
881 "setfont" "setcolor")
882 "List of handle graphics functions used in highlighting.
883Customizing this variable is only useful if `regexp-opt' is available."
884 :group 'matlab
885 :type '(repeat (string :tag "HG Keyword: ")))
886
887(defcustom matlab-debug-list '("dbstop" "dbclear" "dbcont" "dbdown" "dbmex"
888 "dbstack" "dbstatus" "dbstep" "dbtype" "dbup"
889 "dbquit")
890 "List of debug commands used in highlighting.
891Customizing this variable is only useful if `regexp-opt' is available."
892 :group 'matlab
893 :type '(repeat (string :tag "Debug Keyword: ")))
894
895;; font-lock keywords
896(defvar matlab-font-lock-keywords
897 (list
898 ;; String quote chars are also used as transpose, but only if directly
899 ;; after characters, numbers, underscores, or closing delimiters.
900 '(matlab-font-lock-string-match-normal 2 font-lock-string-face)
901 ;; A string with no termination is not currently highlighted.
902 ;; This will show that the string needs some attention.
903 '(matlab-font-lock-string-match-unterminated
904 2 matlab-unterminated-string-face)
905 ;; Comments must occur after the string, that way we can check to see
906 ;; if the comment start char has occurred inside our string. (EL)
907 '(matlab-font-lock-comment-match 1 font-lock-comment-face)
908 ;; Various pragmas should be in different colors.
909 ;; I think pragmas are always lower case?
910 '("%#\\([a-z]+\\)" (1 'bold prepend))
911 ;; General keywords
912 (list
913 (if (fboundp 'regexp-opt)
914 (concat "\\<\\(" (regexp-opt matlab-keyword-list) "\\)\\>")
915 ;; Original hard-coded value for pre Emacs 20.1
916 "\\<\\(break\\|ca\\(se\\|tch\\)\\|e\\(lse\\(\\|if\\)\\|ndfunction\\)\
917\\|\\(par\\)?for\\|spmd\\|global\\|if\\|otherwise\\|return\\|switch\\|try\\|while\\|tic\\|toc\\)\\>")
918 '(0 font-lock-keyword-face))
919 ;; The end keyword is only a keyword when not used as an array
920 ;; dereferencing part.
921 '("\\(^\\|[;,]\\)[ \t]*\\(end\\)\\b"
922 2 (if (matlab-valid-end-construct-p) font-lock-keyword-face nil))
923 ;; How about unreachable code? MUsT BE AFTER KEYWORDS in order to
924 ;; get double-highlighting.
925 '(matlab-find-unreachable-code
926 (1 'underline prepend) ;if part
927 (2 'underline prepend) ;end part
928 (3 'underline prepend) ;else part (if applicable)
929 (4 font-lock-comment-face prepend) ;commented out part.
930 )
931 ;; block comments need to be commented out too!
932 '(matlab-find-block-comments
933 (1 font-lock-comment-face prepend) ; commented out
934 (2 'underline prepend)
935 (3 'underline prepend) ;the comment parts
936 )
937 ;; Cell mode breaks get special treatment
938 '("^\\s-*\\(%%[^\n]*\n\\)" (1 matlab-cellbreak-face append))
939 ;; Highlight cross function variables
940 '(matlab-font-lock-cross-function-variables-match
941 (1 matlab-cross-function-variable-face prepend))
942 ;; Highlight nested function/end keywords
943 '(matlab-font-lock-nested-function-keyword-match
944 (0 matlab-nested-function-keyword-face prepend))
945 ;; The global keyword defines some variables. Mark them.
946 '("^\\s-*global\\s-+"
947 ("\\(\\w+\\)\\(\\s-*=[^,; \t\n]+\\|[, \t;]+\\|$\\)"
948 nil nil (1 font-lock-variable-name-face)))
949 ;; Handle graphics stuff
950 (list
951 (if (fboundp 'regexp-opt)
952 (concat "\\<\\(" (regexp-opt matlab-handle-graphics-list) "\\)\\>")
953 ;; The original regular expression for pre Emacs 20.1
954 "\\<\\(ax\\(es\\|is\\)\\|figure\\|get\\|image\\|li\\(ght\\|ne\\)\\|\
955patch\\|s\\(et\\(\\|color\\|font\\)\\|urface\\)\\|text\\|\
956ui\\(cont\\(ext\\(\\|menu\\)\\|rol\\)\\|menu\\|\
957\\(toggle\\|push\\)tool\\|toolbar\\)\\)\\>")
958 '(0 font-lock-type-face))
959 )
960 "Expressions to highlight in MATLAB mode.")
961
962(defconst matlab-function-arguments
963 "\\(([^)]*)\\)?\\s-*\\([,;\n%]\\|$\\)")
964
965(defvar matlab-gaudy-font-lock-keywords
966 (append
967 matlab-font-lock-keywords
968 (list
969 ;; defining a function, a (possibly empty) list of assigned variables,
970 ;; function name, and an optional (possibly empty) list of input variables
971 (list (concat "^\\s-*\\(function\\)\\>[ \t\n.]*"
972 "\\(\\[[^]]*\\]\\|\\sw+\\)[ \t\n.]*"
973 "=[ \t\n.]*\\(\\sw+\\)[ \t\n.]*"
974 matlab-function-arguments)
975 '(1 font-lock-keyword-face append)
976 '(2 font-lock-variable-name-face append)
977 '(3 font-lock-function-name-face append))
978 ;; defining a function, a function name, and an optional (possibly
979 ;; empty) list of input variables
980 (list (concat "^\\s-*\\(function\\)[ \t\n.]+"
981 "\\(\\sw+\\)[ \t\n.]*"
982 matlab-function-arguments)
983 '(1 font-lock-keyword-face append)
984 '(2 font-lock-function-name-face append))
985 ;; Anchor on the function keyword, highlight params
986 (list (concat "^\\s-*function\\>[ \t\n.]*"
987 "\\(\\(\\[[^]]*\\]\\|\\sw+\\)[ \t\n.]*=[ \t\n.]*\\)?"
988 "\\sw+\\s-*(")
989 '("\\s-*\\(\\sw+\\)\\s-*[,)]" nil nil
990 (1 font-lock-variable-name-face)))
991 ;; I like variables for FOR loops
992 '("\\<\\(for\\|parfor\\)\\s-+\\(\\sw+\\)\\s-*=\\s-*\
993\\(\\([^\n,;%(]+\\|([^\n%)]+)\\)+\\)"
994 (1 font-lock-keyword-face)
995 (2 font-lock-variable-name-face append)
996 (3 font-lock-reference-face append))
997 ;; Items after a switch statements are cool
998 '("\\<\\(case\\|switch\\)\\s-+\\({[^}\n]+}\\|[^,%\n]+\\)"
999 (1 font-lock-keyword-face) (2 font-lock-reference-face))
1000 ;; How about a few matlab constants such as pi, infinity, and sqrt(-1)?
1001 ;; The ^>> is in case I use this in an interactive mode someday
1002 '("\\<\\(eps\\|pi\\|inf\\|Inf\\|NaN\\|nan\\|ans\\|i\\|j\\|^>>\\)\\>"
1003 1 font-lock-reference-face)
1004 '("\\<[0-9]\\.?\\(i\\|j\\)\\>" 1 font-lock-reference-face)
1005 ;; Define these as variables since this is about as close
1006 ;; as matlab gets to variables
1007 (list (concat "\\<" matlab-indent-past-arg1-functions "\\s-*")
1008 '("(\\s-*\\(\\w+\\)\\s-*\\(,\\|)\\)" nil nil
1009 (1 font-lock-variable-name-face)))
1010 ))
1011 "Expressions to highlight in MATLAB mode.")
1012
1013(defvar matlab-really-gaudy-font-lock-keywords
1014 (append
1015 matlab-gaudy-font-lock-keywords
1016 (list
1017 ;; Since it's a math language, how bout dem symbols?
1018 '("\\([<>~]=?\\|\\.[/*^']\\|==\\|\\<xor\\>\\|[-!^&|*+\\/~:]\\)"
1019 1 font-lock-type-face)
1020 ;; How about references in the HELP text.
1021 (list (concat "^" matlab-comment-line-s "\\s-*"
1022 "\\(\\([A-Z]+\\s-*=\\s-+\\|\\[[^]]+]\\s-*=\\s-+\\|\\)"
1023 "\\([A-Z][0-9A-Z]+\\)\\(([^)\n]+)\\| \\)\\)")
1024 '(1 font-lock-reference-face prepend))
1025 (list (concat "^" matlab-comment-line-s "\\s-*"
1026 "See also\\s-+")
1027 '("\\([A-Z][A-Z0-9]+\\)\\([,.]\\| and\\|$\\) *" nil nil
1028 (1 font-lock-reference-face prepend)))
1029 (list (concat "^" matlab-comment-line-s "\\s-*"
1030 "\\(\\$" "Revision" "[^\n$]+\\$\\)")
1031 '(1 font-lock-reference-face prepend))
1032 ;; continuation ellipsis.
1033 '("[^.]\\(\\.\\.\\.+\\)\\([^\n]*\\)" (1 'underline)
1034 (2 font-lock-comment-face))
1035 ;; How about debugging statements?
1036 ;;'("\\<\\(db\\sw+\\)\\>" 1 'bold)
1037 (list
1038 (if (fboundp 'regexp-opt)
1039 (concat "\\<\\(" (regexp-opt matlab-debug-list) "\\)\\>")
1040 ;; pre-regexp-opt days.
1041 "\\<\\(db\\(c\\(lear\\|ont\\)\\|down\\|mex\\|quit\\|\
1042st\\(a\\(ck\\|tus\\)\\|ep\\|op\\)\\|type\\|up\\)\\)\\>")
1043 '(0 'bold)))
1044 (if matlab-handle-simulink
1045 ;; Simulink functions, but only if the user wants it.
1046 (list (list (concat "\\<\\(\\([sg]et_param\\|sim\\([gs]et\\)?\\|"
1047 "\\(mld\\|ss\\)[A-Z]\\w+\\)\\|"
1048 "\\(new\\|open\\|close\\|save\\|find\\)_system\\|"
1049 "\\(add\\|delete\\|replace\\)_\\(block\\|line\\)\\|"
1050 "simulink\\|bd\\(root\\|close\\)"
1051 "\\)\\>")
1052 1 matlab-simulink-keyword-face))
1053 nil))
1054 "Expressions to highlight in MATLAB mode.")
1055
1056(defvar matlab-shell-font-lock-keywords
1057 (list
1058 ;; How about Errors?
1059 '("^\\(Error in\\|Syntax error in\\)\\s-+==>\\s-+\\(.+\\)$"
1060 (1 font-lock-comment-face) (2 font-lock-string-face))
1061 ;; and line numbers
1062 '("^\\(On line [0-9]+\\)" 1 font-lock-comment-face)
1063 ;; User beep things
1064 '("\\(\\?\\?\\?[^\n]+\\)" 1 font-lock-comment-face)
1065 ;; Useful user commands, but not useful programming constructs
1066 '("\\<\\(demo\\|whatsnew\\|info\\|subscribe\\|help\\|doc\\|lookfor\\|what\
1067\\|whos?\\|cd\\|clear\\|load\\|save\\|helpdesk\\|helpwin\\)\\>"
1068 1 font-lock-keyword-face)
1069 ;; Various notices
1070 '(" M A T L A B " 0 'underline)
1071 '("All Rights Reserved" 0 'italic)
1072 '("\\((c)\\s-+Copyright[^\n]+\\)" 1 font-lock-comment-face)
1073 '("\\(Version\\)\\s-+\\([^\n]+\\)"
1074 (1 font-lock-function-name-face) (2 font-lock-variable-name-face))
1075 )
1076 "Additional keywords used by MATLAB when reporting errors in interactive\
1077mode.")
1078
1079;; Imenu support.
1080(defvar matlab-imenu-generic-expression
1081 '((nil "^\\s-*function\\>[ \t\n.]*\\(\\(\\[[^]]*\\]\\|\\sw+\\)[ \t\n.]*\
1082< =\[ \t\n.]*\\)?\\([a-zA-Z0-9_]+\\)" 3))
1083 "Expressions which find function headings in MATLAB M files.")
1084
1085
1086;;; MATLAB mode entry point ==================================================
1087
1088;;;###autoload
1089(add-to-list 'auto-mode-alist '("\\.m$" . matlab-mode))
1090
1091;;;###autoload
1092(defun matlab-mode ()
1093 "MATLAB(R) mode is a major mode for editing MATLAB dot-m files.
1094\\<matlab-mode-map>
1095Convenient editing commands are:
1096 \\[matlab-comment-region] - Comment/Uncomment out a region of code.
1097 \\[matlab-fill-comment-line] - Fill the current comment line.
1098 \\[matlab-fill-region] - Fill code and comments in region.
1099 \\[matlab-fill-paragraph] - Refill the current command or comment.
1100 \\[matlab-complete-symbol] - Symbol completion of matlab symbols\
1101based on the local syntax.
1102 \\[matlab-indent-sexp] - Indent syntactic block of code.
1103
1104Convenient navigation commands are:
1105 \\[matlab-beginning-of-command] - Move to the beginning of a command.
1106 \\[matlab-end-of-command] - Move to the end of a command.
1107 \\[matlab-beginning-of-defun] - Move to the beginning of a function.
1108 \\[matlab-end-of-defun] - Move do the end of a function.
1109 \\[matlab-forward-sexp] - Move forward over a syntactic block of code.
1110 \\[matlab-backward-sexp] - Move backwards over a syntactic block of code.
1111
1112Convenient template insertion commands:
1113 \\[tempo-template-matlab-function] - Insert a function definition.
1114 \\[tempo-template-matlab-if] - Insert an IF END block.
1115 \\[tempo-template-matlab-for] - Insert a FOR END block.
1116 \\[tempo-template-matlab-switch] - Insert a SWITCH END statement.
1117 \\[matlab-insert-next-case] - Insert the next CASE condition in a SWITCH.
1118 \\[matlab-insert-end-block] - Insert a matched END statement. With \
1119optional ARG, reindent.
1120 \\[matlab-stringify-region] - Convert plaintext in region to a string \
1121with correctly quoted chars.
1122
1123Variables:
1124 `matlab-indent-level' Level to indent blocks.
1125 `matlab-cont-level' Level to indent continuation lines.
1126 `matlab-cont-requires-ellipsis' Does your MATLAB support implied elipsis.
1127 `matlab-case-level' Level to unindent case statements.
1128 `matlab-indent-past-arg1-functions'
1129 Regexp of functions to indent past the first
1130 argument on continuation lines.
1131 `matlab-maximum-indents' List of maximum indents during lineups.
1132 `matlab-comment-column' Goal column for on-line comments.
1133 `fill-column' Column used in auto-fill.
1134 `matlab-indent-function-body' If non-nil, indents body of MATLAB functions.
1135 `matlab-functions-have-end' If non-nil, MATLAB functions terminate with end.
1136 `matlab-return-function' Customize RET handling with this function.
1137 `matlab-auto-fill' Non-nil, do auto-fill at startup.
1138 `matlab-fill-code' Non-nil, auto-fill code.
1139 `matlab-fill-strings' Non-nil, auto-fill strings.
1140 `matlab-verify-on-save-flag' Non-nil, enable code checks on save.
1141 `matlab-highlight-block-match-flag'
1142 Enable matching block begin/end keywords.
1143 `matlab-vers-on-startup' If t, show version on start-up.
1144 `matlab-handle-simulink' If t, enable simulink keyword highlighting.
1145
1146All Key Bindings:
1147\\{matlab-mode-map}"
1148 (interactive)
1149 (kill-all-local-variables)
1150 (use-local-map matlab-mode-map)
1151 (setq major-mode 'matlab-mode)
1152 (setq mode-name "MATLAB")
1153 (if (boundp 'whitespace-modes)
1154 (add-to-list 'whitespace-modes 'matlab-mode))
1155 (setq local-abbrev-table matlab-mode-abbrev-table)
1156 (set-syntax-table matlab-mode-syntax-table)
1157 (setq indent-tabs-mode nil)
1158 (make-local-variable 'indent-line-function)
1159 (setq indent-line-function 'matlab-indent-line)
1160 (make-local-variable 'paragraph-start)
1161 (setq paragraph-start (concat "^$\\|" page-delimiter))
1162 (make-local-variable 'paragraph-separate)
1163 (setq paragraph-separate paragraph-start)
1164 (make-local-variable 'paragraph-ignore-fill-prefix)
1165 (setq paragraph-ignore-fill-prefix t)
1166 (make-local-variable 'comment-start-skip)
1167 (setq comment-start-skip "%\\s-+")
1168 (make-local-variable 'comment-start)
1169 (setq comment-start "%")
1170 (make-local-variable 'page-delimiter)
1171 (setq page-delimiter "^\\(\f\\|%%\\(\\s-\\|\n\\)\\)")
1172 (make-local-variable 'comment-column)
1173 (setq comment-column matlab-comment-column)
1174 (make-local-variable 'comment-indent-function)
1175 (setq comment-indent-function 'matlab-comment-indent)
1176 (make-local-variable 'add-log-current-defun-function)
1177 (setq add-log-current-defun-function 'matlab-current-defun)
1178 (make-local-variable 'fill-column)
1179 (setq fill-column default-fill-column)
1180 (make-local-variable 'auto-fill-function)
1181 (if matlab-auto-fill (setq auto-fill-function 'matlab-auto-fill))
1182 ;; Emacs 20 supports this variable. This lets users turn auto-fill
1183 ;; on and off and still get the right fill function.
1184 (make-local-variable 'normal-auto-fill-function)
1185 (setq normal-auto-fill-function 'matlab-auto-fill)
1186 (make-local-variable 'fill-prefix)
1187 (make-local-variable 'imenu-generic-expression)
1188 (setq imenu-generic-expression matlab-imenu-generic-expression)
1189 ;; Save hook for verifying src. This lets us change the name of
1190 ;; the function in `write-file' and have the change be saved.
1191 ;; It also lets us fix mistakes before a `save-and-go'.
1192 (make-local-variable 'write-contents-hooks)
1193 (add-hook 'write-contents-hooks 'matlab-mode-verify-fix-file-fn)
1194 ;; Tempo tags
1195 (make-local-variable 'tempo-local-tags)
1196 (setq tempo-local-tags (append matlab-tempo-tags tempo-local-tags))
1197 ;; give each file it's own parameter history
1198 (make-local-variable 'matlab-shell-save-and-go-history)
1199 (make-local-variable 'font-lock-defaults)
1200 (setq font-lock-defaults '((matlab-font-lock-keywords
1201 matlab-gaudy-font-lock-keywords
1202 matlab-really-gaudy-font-lock-keywords
1203 )
1204 t ; do not do string/comment highlighting
1205 nil ; keywords are case sensitive.
1206 ;; This puts _ as a word constituent,
1207 ;; simplifying our keywords significantly
1208 ((?_ . "w"))))
1209 (matlab-enable-block-highlighting 1)
1210 (if window-system (matlab-frame-init))
1211
1212 ;; If first function is terminated with an end statement, then functions have
1213 ;; ends.
1214 (if (matlab-do-functions-have-end-p)
1215 (matlab-functions-have-end-minor-mode 1)
1216 (matlab-functions-have-end-minor-mode -1)
1217 )
1218
1219 ;; When matlab-indent-function-body is set to 'MathWorks-Standard,
1220 ;; - we indent all functions that terminate with an end statement
1221 ;; - old style functions (those without end statements) are not
1222 ;; indented.
1223 ;; It is desired that all code be terminate with an end statement.
1224 ;;
1225 ;; When matlab-indent-function-body is set to 'guess,
1226 ;; - look at the first line of code and if indented, keep indentation
1227 ;; otherwise use MathWorks-Standard
1228 ;;
1229 (cond
1230 ((eq matlab-indent-function-body 'MathWorks-Standard)
1231 )
1232
1233 ((eq matlab-indent-function-body 'guess)
1234 (save-excursion
1235 (goto-char (point-max))
1236
1237 (if (re-search-backward matlab-defun-regex nil t)
1238 (let ((beg (point))
1239 end ; filled in later
1240 (cc (current-column))
1241 )
1242 (setq end (if matlab-functions-have-end
1243 (progn (forward-line 0) (point))
1244 (point-max)))
1245 (goto-char beg)
1246 (catch 'done
1247 (while (progn (forward-line 1) (< (point) end))
1248 (if (looking-at "\\s-*\\(%\\|$\\)")
1249 nil ; go on to next line
1250 (looking-at "\\s-*")
1251 (goto-char (match-end 0))
1252 (setq matlab-indent-function-body (> (current-column) cc))
1253 (throw 'done nil))))
1254 )
1255 (setq matlab-indent-function-body 'MathWorks-Standard)
1256 ))
1257 )
1258
1259 (t)
1260 )
1261
1262
1263 (if (or (featurep 'mlint)
1264 matlab-show-mlint-warnings
1265 matlab-highlight-cross-function-variables)
1266 ;; Some users may not feel like getting all the extra stuff
1267 ;; needed for mlint working. Do this only if we can get
1268 ;; mlint loaded ok.
1269 (condition-case nil
1270 (mlint-minor-mode
1271 (if (or matlab-show-mlint-warnings matlab-highlight-cross-function-variables)
1272 1
1273 0))
1274 ;; If there is an error loading the stuff, don't
1275 ;; continue.
1276 (error nil)))
1277 (save-excursion
1278 (goto-char (point-min))
1279 (run-hooks 'matlab-mode-hook))
1280 (if matlab-vers-on-startup (matlab-show-version)))
1281
1282;;; Utilities =================================================================
1283
1284(defun matlab-show-version ()
1285 "Show the version number in the minibuffer."
1286 (interactive)
1287 (message "matlab-mode, version %s" matlab-mode-version))
1288
1289(defun matlab-find-prev-line ()
1290 "Recurse backwards until a code line is found."
1291 (if (= -1 (forward-line -1)) nil
1292 (if (or (matlab-ltype-empty)
1293 (matlab-ltype-comm-ignore))
1294 (matlab-find-prev-line) t)))
1295
1296(defun matlab-prev-line ()
1297 "Go to the previous line of code. Return nil if not found."
1298 (interactive)
1299 (let ((old-point (point)))
1300 (if (matlab-find-prev-line) t (goto-char old-point) nil)))
1301
1302(defun matlab-uniquafy-list (lst)
1303 "Return a list that is a subset of LST where all elements are unique."
1304 (let ((nlst nil))
1305 (while lst
1306 (if (and (car lst) (not (member (car lst) nlst)))
1307 (setq nlst (cons (car lst) nlst)))
1308 (setq lst (cdr lst)))
1309 (nreverse nlst)))
1310
1311; Aki Vehtari <Aki.Vehtari@hut.fi> recommends this: (19.29 required)
1312;(require 'backquote)
1313;(defmacro matlab-navigation-syntax (&rest body)
1314; "Evaluate BODY with the matlab-mode-special-syntax-table"
1315; '(let ((oldsyntax (syntax-table)))
1316; (unwind-protect
1317; (progn
1318; (set-syntax-table matlab-mode-special-syntax-table)
1319; ,@body)
1320; (set-syntax-table oldsyntax))))
1321
1322(defmacro matlab-navigation-syntax (&rest forms)
1323 "Set the current environment for syntax-navigation and execute FORMS."
1324 (list 'let '((oldsyntax (syntax-table))
1325 (case-fold-search nil))
1326 (list 'unwind-protect
1327 (list 'progn
1328 '(set-syntax-table matlab-mode-special-syntax-table)
1329 (cons 'progn forms))
1330 '(set-syntax-table oldsyntax))))
1331
1332(put 'matlab-navigation-syntax 'lisp-indent-function 0)
1333(add-hook 'edebug-setup-hook
1334 (lambda ()
1335 (def-edebug-spec matlab-navigation-syntax def-body)))
1336
1337(defun matlab-up-list (count &optional restrict)
1338 "Move forwards or backwards up a list by COUNT.
1339Optional argument RESTRICT is where to restrict the search."
1340 ;; MATLAB syntax table has no disabling strings or comments.
1341 (let ((dir (if (> 0 count) -1 +1))
1342 (origin (point))
1343 (ms nil))
1344 ;; Make count positive
1345 (setq count (* count dir))
1346 (if (= dir -1)
1347 (while (/= count 0)
1348 ;; Search till we find an unstrung paren object.
1349 (setq ms (re-search-backward "\\s(\\|\\s)" restrict t))
1350 (while (and (save-match-data (matlab-cursor-in-string-or-comment))
1351 (setq ms (re-search-backward "\\s(\\|\\s)" restrict t))))
1352 (if (not ms)
1353 (progn
1354 (goto-char origin)
1355 (error "Scan Error: List missmatch")))
1356 ;; View it's match.
1357 (let ((s (match-string 0)))
1358 (if (string-match "\\s(" s)
1359 (setq count (1- count))
1360 (setq count (1+ count)))))
1361 (error "Not implemented"))
1362 ms))
1363
1364(defun matlab-valid-end-construct-p ()
1365 "Return non-nil if the end after point terminates a block.
1366Return nil if it is being used to dereference an array."
1367 (let ((p (point))
1368 (err1 t))
1369 (condition-case nil
1370 (save-restriction
1371 ;; Restrict navigation only to the current command line
1372 (save-excursion
1373 (matlab-beginning-of-command)
1374 (narrow-to-region (point)
1375 (save-excursion
1376 (goto-char p)
1377 (matlab-point-at-eol))))
1378 ;; This used to add some sort of protection, but I don't know what
1379 ;; the condition was, or why the simple case doesn't handle it.
1380 ;;
1381 ;; The above replacement fixes a case where a continuation in an array
1382 ;; befuddles the indenter.
1383 ;; (progn ;;(matlab-end-of-command (point))
1384 ;; (end-of-line)
1385 ;; (if (> p (point))
1386 ;; (progn
1387 ;; (setq err1 nil)
1388 ;; (error)))
1389 ;; (point))))
1390 (save-excursion
1391 ;; beginning of param list
1392 (matlab-up-list -1)
1393 ;; backup over the parens. If that fails
1394 (condition-case nil
1395 (progn
1396 (forward-sexp 1)
1397 ;; If we get here, the END is inside parens, which is not a
1398 ;; valid location for the END keyword. As such it is being
1399 ;; used to dereference array parameters
1400 nil)
1401 ;; This error means that we have an unterminated paren
1402 ;; block, so this end is currently invalid.
1403 (error nil))))
1404 ;; an error means the list navigation failed, which also means we are
1405 ;; at the top-level
1406 (error err1))))
1407
1408;;; Regexps for MATLAB language ===============================================
1409
1410;; "-pre" means "partial regular expression"
1411;; "-if" and "-no-if" means "[no] Indent Function"
1412
1413(defconst matlab-defun-regex "^\\(\\s-*function\\|classdef\\)[ \t.[]"
1414 "Regular expression defining the beginning of a MATLAB function.")
1415
1416(defconst matlab-mcos-regexp "\\|classdef\\|properties\\|methods\\|enumeration"
1417 "Keywords which mark the beginning of mcos blocks.")
1418
1419(defcustom matlab-block-indent-tic-toc-flag nil
1420 "*Non-nil means that tic,toc should indent like a if,end block.
1421This variable should be set before loading matlab.el"
1422 :group 'matlab
1423 :type 'boolean)
1424
1425(defconst matlab-block-beg-pre-if
1426 (if matlab-block-indent-tic-toc-flag
1427 (concat "function\\|parfor\\|spmd\\|for\\|while\\|if\\|switch\\|try\\|tic"
1428 matlab-mcos-regexp)
1429 (concat "function\\|parfor\\|spmd\\|for\\|while\\|if\\|switch\\|try"
1430 matlab-mcos-regexp))
1431 "Keywords which mark the beginning of an indented block.
1432Includes function.")
1433
1434(defconst matlab-block-beg-pre-no-if
1435 (if matlab-block-indent-tic-toc-flag
1436 (concat "parfor\\|for\\|spmd\\|while\\|if\\|switch\\|try\\|tic"
1437 matlab-mcos-regexp)
1438 (concat "parfor\\|for\\|spmd\\|while\\|if\\|switch\\|try"
1439 matlab-mcos-regexp))
1440 "Keywords which mark the beginning of an indented block.
1441Excludes function.")
1442
1443(defun matlab-block-beg-pre ()
1444 "Partial regular expression to recognize MATLAB block-begin keywords."
1445 (if matlab-functions-have-end
1446 matlab-block-beg-pre-if
1447 matlab-block-beg-pre-no-if))
1448
1449(defconst matlab-block-mid-pre
1450 "elseif\\|else\\|catch"
1451 "Partial regular expression to recognize MATLAB mid-block keywords.")
1452
1453(defconst matlab-block-end-pre-if
1454 (if matlab-block-indent-tic-toc-flag
1455 "end\\(function\\)?\\|function\\|\\(\\sw+\\s-*\\((.*)\\)?\\s-*=\\s-*\\)?toc"
1456 "end\\(function\\)?\\|function")
1457 "Partial regular expression to recognize MATLAB block-end keywords.")
1458
1459(defconst matlab-block-end-pre-no-if
1460 (if matlab-block-indent-tic-toc-flag
1461 "end\\|\\(\\sw+\\s-*\\((.*)\\)?\\s-*=\\s-*\\)?toc"
1462 "end")
1463 "Partial regular expression to recognize MATLAB block-end keywords.")
1464
1465(defun matlab-block-end-pre ()
1466 "Partial regular expression to recognize MATLAB block-end keywords."
1467 (if matlab-functions-have-end
1468 matlab-block-end-pre-if
1469 matlab-block-end-pre-no-if))
1470
1471;; Not used.
1472;;(defconst matlab-other-pre
1473;; "function\\|return"
1474;; "Partial regular express to recognize MATLAB non-block keywords.")
1475
1476(defconst matlab-endless-blocks
1477 "case\\|otherwise"
1478 "Keywords which initialize new blocks, but don't have explicit ends.
1479Thus, they are endless. A new case or otherwise will end a previous
1480endless block, and and end will end this block, plus any outside normal
1481blocks.")
1482
1483(defun matlab-block-re ()
1484 "Regular expression for keywords which begin MATLAB blocks."
1485 (concat "\\(^\\|[;,]\\)\\s-*\\("
1486 (matlab-block-beg-pre) "\\|"
1487 matlab-block-mid-pre "\\|"
1488 (matlab-block-end-pre) "\\|"
1489 matlab-endless-blocks "\\)\\b"))
1490
1491(defun matlab-block-scan-re ()
1492 "Expression used to scan over matching pairs of begin/ends."
1493 (concat "\\(^\\|[;,]\\)\\s-*\\("
1494 (matlab-block-beg-pre) "\\|"
1495 (matlab-block-end-pre) "\\)\\b"))
1496
1497(defun matlab-block-beg-re ()
1498 "Expression used to find the beginning of a block."
1499 (concat "\\(" (matlab-block-beg-pre) "\\)"))
1500
1501(defun matlab-block-mid-re ()
1502 "Expression used to find block center parts (like else)."
1503 (concat "\\(" matlab-block-mid-pre "\\)"))
1504
1505(defun matlab-block-end-re ()
1506 "Expression used to end a block. Usually just `end'."
1507 (concat "\\(" (matlab-block-end-pre) "\\)"))
1508
1509(defun matlab-block-end-no-function-re ()
1510 "Expression representing and end if functions are excluded."
1511 (concat "\\<\\(" matlab-block-end-pre-no-if "\\)\\>"))
1512
1513(defun matlab-endless-blocks-re ()
1514 "Expression of block starters that do not have associated ends."
1515 (concat "\\(" matlab-endless-blocks "\\)"))
1516
1517(defun matlab-match-function-re ()
1518 "Expression to match a function start line.
1519There are no reliable numeric matches in this expression.
1520Know that `match-end' of 0 is the end of the functin name."
1521 ;; old function was too unstable.
1522 ;;"\\(^function\\s-+\\)\\([^=\n]+=[ \t\n.]*\\)?\\(\\sw+\\)"
1523 (concat "\\(^\\s-*function\\b[ \t\n.]*\\)\\(\\(\\[[^]]*\\]\\|\\sw+\\)"
1524 "[ \t\n.]*=[ \t\n.]*\\|\\(\\)\\)\\(\\sw+\\)"))
1525
1526(defconst matlab-cline-start-skip "[ \t]*%[ \t]*"
1527 "*The regular expression for skipping comment start.")
1528
1529;;; Lists for matlab keywords =================================================
1530
1531(defvar matlab-keywords-solo
1532 '("break" "case" "else" "elseif" "end" "for" "parfor" "function" "if" "tic" "toc"
1533 "otherwise" "profile" "switch" "while" "try" "catch" "spmd")
1534 "Keywords that appear on a line by themselves.")
1535(defvar matlab-keywords-return
1536 '("acos" "acosh" "acot" "acoth" "acsch" "asech" "asin" "asinh"
1537 "atan" "atan2" "atanh" "cos" "cosh" "coth" "csc" "csch" "exp"
1538 "log" "log10" "log2" "sec" "sech" "sin" "sinh" "tanh"
1539 "abs" "sign" "sqrt" )
1540 "List of MATLAB keywords that have return arguments.
1541This list still needs lots of help.")
1542(defvar matlab-keywords-boolean
1543 '("all" "any" "exist" "isempty" "isequal" "ishold" "isfinite" "isglobal"
1544 "isinf" "isletter" "islogical" "isnan" "isprime" "isreal" "isspace"
1545 "logical" "isa")
1546 "List of keywords that are typically used as boolean expressions.")
1547
1548(defvar matlab-core-properties
1549 '("ButtonDownFcn" "Children" "Clipping" "CreateFcn" "DeleteFcn"
1550 "BusyAction" "HandleVisibility" "HitTest" "Interruptible"
1551 "Parent" "Selected" "SelectionHighlight" "Tag" "Type"
1552 "UIContextMenu" "UserData" "Visible")
1553 "List of properties belonging to all HG objects.")
1554
1555(defvar matlab-property-lists
1556 '(("root" .
1557 ("CallbackObject" "Language" "CurrentFigure" "Diary" "DiaryFile"
1558 "Echo" "ErrorMessage" "Format" "FormatSpacing" "PointerLocation"
1559 "MonitorPositions"
1560 "PointerWindow" "Profile" "ProfileFile" "ProfileCount"
1561 "ProfileInterval" "RecursionLimit" "ScreenDepth" "ScreenSize"
1562 "ShowHiddenHandles" "TerminalHideGraphCommand" "TerminalOneWindow"
1563 "TerminalDimensions" "TerminalProtocol" "TerminalShowGraphCommand"
1564 "Units" "AutomaticFileUpdates" ))
1565 ("axes" .
1566 ("AmbientLightColor" "Box" "CameraPosition" "CameraPositionMode"
1567 "CameraTarget" "CameraTargetMode" "CameraUpVector"
1568 "CameraUpVectorMode" "CameraViewAngle" "CameraViewAngleMode" "CLim"
1569 "CLimMode" "Color" "CurrentPoint" "ColorOrder" "DataAspectRatio"
1570 "DataAspectRatioMode" "DrawMode" "FontAngle" "FontName" "FontSize"
1571 "FontUnits" "FontWeight" "GridLineStyle" "Layer" "LineStyleOrder"
1572 "LineWidth" "NextPlot" "PlotBoxAspectRatio" "PlotBoxAspectRatioMode"
1573 "Projection" "Position" "TickLength" "TickDir" "TickDirMode" "Title"
1574 "Units" "View" "XColor" "XDir" "XGrid" "XLabel" "XAxisLocation" "XLim"
1575 "XLimMode" "XScale" "XTick" "XTickLabel" "XTickLabelMode" "XTickMode"
1576 "YColor" "YDir" "YGrid" "YLabel" "YAxisLocation" "YLim" "YLimMode"
1577 "YScale" "YTick" "YTickLabel" "YTickLabelMode" "YTickMode" "ZColor"
1578 "ZDir" "ZGrid" "ZLabel" "ZLim" "ZLimMode" "ZScale" "ZTick"
1579 "ZTickLabel" "ZTickLabelMode" "ZTickMode"))
1580 ("figure" .
1581 ("BackingStore" "CloseRequestFcn" "Color" "Colormap"
1582 "CurrentAxes" "CurrentCharacter" "CurrentObject" "CurrentPoint"
1583 "Dithermap" "DithermapMode" "FixedColors" "IntegerHandle"
1584 "InvertHardcopy" "KeyPressFcn" "MenuBar" "MinColormap" "Name"
1585 "NextPlot" "NumberTitle" "PaperUnits" "PaperOrientation"
1586 "PaperPosition" "PaperPositionMode" "PaperSize" "PaperType"
1587 "Pointer" "PointerShapeCData" "PointerShapeHotSpot" "Position"
1588 "Renderer" "RendererMode" "Resize" "ResizeFcn" "SelectionType"
1589 "ShareColors" "Units" "WindowButtonDownFcn"
1590 "WindowButtonMotionFcn" "WindowButtonUpFcn" "WindowStyle"))
1591 ("image" . ("CData" "CDataMapping" "EraseMode" "XData" "YData"))
1592 ("light" . ("Position" "Color" "Style"))
1593 ("line" .
1594 ("Color" "EraseMode" "LineStyle" "LineWidth" "Marker" "LineSmoothing"
1595 "MarkerSize" "MarkerEdgeColor" "MarkerFaceColor" "XData" "YData"
1596 "ZData"))
1597 ("patch" .
1598 ("CData" "CDataMapping" "FaceVertexCData" "EdgeColor" "EraseMode"
1599 "FaceColor" "Faces" "LineStyle" "LineWidth" "Marker" "LineSmoothing"
1600 "MarkerEdgeColor" "MarkerFaceColor" "MarkerSize" "Vertices"
1601 "XData" "YData" "ZData" "FaceLighting" "EdgeLighting"
1602 "BackFaceLighting" "AmbientStrength" "DiffuseStrength"
1603 "SpecularStrength" "SpecularExponent" "SpecularColorReflectance"
1604 "VertexNormals" "NormalMode"))
1605 ("surface" .
1606 ("CData" "CDataMapping" "EdgeColor" "EraseMode" "FaceColor"
1607 "LineStyle" "LineWidth" "Marker" "MarkerEdgeColor" "LineSmoothing"
1608 "MarkerFaceColor" "MarkerSize" "MeshStyle" "XData" "YData"
1609 "ZData" "FaceLighting" "EdgeLighting" "BackFaceLighting"
1610 "AmbientStrength" "DiffuseStrength" "SpecularStrength"
1611 "SpecularExponent" "SpecularColorReflectance" "VertexNormals"
1612 "NormalMode"))
1613 ("text\\|title\\|xlabel\\|ylabel\\|zlabel" .
1614 ("Color" "EraseMode" "Editing" "Extent" "FontAngle" "FontName"
1615 "FontSize" "FontUnits" "FontWeight" "HorizontalAlignment"
1616 "BackgroundColor" "EdgeColor" "Margin"
1617 "Position" "Rotation" "String" "Units" "Interpreter"
1618 "VerticalAlignment"))
1619 ("uicontextmenu" . ("Callback"))
1620 ("uicontrol" .
1621 ("BackgroundColor" "Callback" "CData" "Enable" "Extent"
1622 "FontAngle" "FontName" "FontSize" "FontUnits" "FontWeight"
1623 "ForegroundColor" "HorizontalAlignment" "ListboxTop" "Max" "Min"
1624 "Position" "String" "Style" "SliderStep" "TooltipString" "Units"
1625 "Value"))
1626 ("uimenu" .
1627 ("Accelerator" "Callback" "Checked" "Enable" "ForegroundColor"
1628 "Label" "Position" "Separator"))
1629 ;; Flesh this out more later.
1630 ("uipushtool\\|uitoggletool\\|uitoolbar" .
1631 ("Cdata" "Callback" "Separator" "Visible"))
1632 )
1633 "List of property lists on a per object type basis.")
1634
1635(defvar matlab-unknown-type-commands
1636 "[gs]et\\|findobj\\|waitfor"
1637 "Expression for commands that have unknown types.")
1638
1639(defun matlab-all-known-properties ()
1640 "Return a list of all properties."
1641 (let ((lst matlab-core-properties)
1642 (tl matlab-property-lists))
1643 (while tl
1644 (setq lst (append lst (cdr (car tl)))
1645 tl (cdr tl)))
1646 (matlab-uniquafy-list lst)))
1647
1648(defvar matlab-all-known-properties (matlab-all-known-properties)
1649 "List of all the known properties.")
1650
1651(defmacro matlab-property-function ()
1652 "Regexp of all builtin functions that take property lists."
1653 '(let ((r matlab-unknown-type-commands)
1654 (tl matlab-property-lists))
1655 (while tl
1656 (setq r (concat r "\\|" (car (car tl)))
1657 tl (cdr tl)))
1658 r))
1659
1660;;; Navigation ===============================================================
1661
1662(defvar matlab-scan-on-screen-only nil
1663 "When this is set to non-nil, then forward/backward sexp stops off screen.
1664This is so the block highlighter doesn't gobble up lots of time when
1665a block is not terminated.")
1666
1667(defun matlab-backward-sexp (&optional autoend noerror)
1668 "Go backwards one balanced set of MATLAB expressions.
1669If optional AUTOEND, then pretend we are at an end.
1670If optional NOERROR, then we return t on success, and nil on failure.
1671This assumes that expressions do not cross \"function\" at the left margin."
1672 (interactive "P")
1673 (matlab-navigation-syntax
1674 (if (and (not autoend)
1675 (save-excursion (backward-word 1)
1676 (or (not
1677 (and (looking-at
1678 (matlab-block-end-no-function-re))
1679 (matlab-valid-end-construct-p)))
1680 (matlab-cursor-in-string-or-comment))))
1681 ;; Go backwards one simple expression
1682 (forward-sexp -1)
1683 ;; otherwise go backwards recursively across balanced expressions
1684 ;; backup over our end
1685 (if (not autoend) (forward-word -1))
1686 (let ((done nil) (start (point)) (returnme t) (bound nil))
1687 (when (search-backward "\nfunction" nil t)
1688 (if (progn (forward-char 9) (looking-at "\\b"))
1689 (setq bound (- (point) 8)))
1690 (goto-char start))
1691 (while (and (not done)
1692 (or (not matlab-scan-on-screen-only)
1693 (pos-visible-in-window-p)))
1694 (if (re-search-backward (matlab-block-scan-re) bound t)
1695 (progn
1696 (goto-char (match-beginning 2))
1697 (if (looking-at (matlab-block-end-no-function-re))
1698 (if (or (matlab-cursor-in-string-or-comment)
1699 (not (matlab-valid-end-construct-p)))
1700 nil
1701 ;; we must skip the expression and keep searching
1702 (forward-word 1)
1703 (matlab-backward-sexp))
1704 (if (not (matlab-cursor-in-string-or-comment))
1705 (setq done t))))
1706 (goto-char start)
1707 (if noerror
1708 (setq returnme nil)
1709 (error "Unstarted END construct"))))
1710 returnme))))
1711
1712(defun matlab-forward-sexp (&optional includeelse)
1713 "Go forward one balanced set of MATLAB expressions.
1714Optional argument INCLUDEELSE will stop on ELSE if it matches the starting IF."
1715 (interactive "P")
1716 (let (p) ;; go to here if no error.
1717 (save-excursion ;; don't go anywhere if there is an error
1718 (matlab-navigation-syntax
1719 ;; skip over preceeding whitespace
1720 (skip-chars-forward " \t\n;")
1721 (if (or (not (looking-at (concat "\\("
1722 (matlab-block-beg-pre)
1723 "\\|"
1724 (matlab-block-mid-re)
1725 "\\)\\>")))
1726 (matlab-cursor-in-string-or-comment))
1727 ;; Go forwards one simple expression
1728 (forward-sexp 1)
1729 ;; otherwise go forwards recursively across balanced expressions
1730 (forward-word 1)
1731 (let ((done nil) (s nil)
1732 (expr-scan (if includeelse
1733 (matlab-block-re)
1734 (matlab-block-scan-re)))
1735 (expr-look (matlab-block-beg-pre)))
1736 (while (and (not done)
1737 (setq s (re-search-forward expr-scan nil t))
1738 (or (not matlab-scan-on-screen-only)
1739 (pos-visible-in-window-p)))
1740 (goto-char (match-beginning 2))
1741 (if (looking-at expr-look)
1742 (if (matlab-cursor-in-string-or-comment)
1743 (forward-word 1)
1744 ;; we must skip the expression and keep searching
1745 ;; NEVER EVER call with value of INCLUDEELSE
1746 (matlab-forward-sexp))
1747 (forward-word 1)
1748 (if (and (not (matlab-cursor-in-string-or-comment))
1749 (matlab-valid-end-construct-p))
1750 (setq done t))))
1751 (if (not s)
1752 (error "Unterminated block"))))
1753 (setq p (point)))) ;; really go here
1754 (goto-char p)))
1755
1756(defun matlab-indent-sexp ()
1757 "Indent the syntactic block starting at point."
1758 (interactive)
1759 (indent-region (point) (save-excursion (matlab-forward-sexp) (point)) nil))
1760
1761(defun matlab-beginning-of-enclosing-defun ()
1762 "Move cursor to beginning of enclosing function.
1763If `matlab-functions-have-end', skip over functions with end."
1764 (catch 'done
1765 (let ((start (point))
1766 (beg nil))
1767 (while (re-search-backward matlab-defun-regex nil t)
1768 (setq beg (point))
1769 (condition-case nil
1770 (progn
1771 (matlab-forward-sexp)
1772 (if (> (point) start) (throw 'done beg)))
1773 (error (throw 'done beg)))
1774 (goto-char beg)))
1775 nil))
1776
1777(defun matlab-beginning-of-defun ()
1778 "Go to the beginning of the current function."
1779 (interactive)
1780 (if matlab-functions-have-end
1781 (goto-char (or (matlab-beginning-of-enclosing-defun) (point-min)))
1782 (or (re-search-backward matlab-defun-regex nil t)
1783 (goto-char (point-min)))))
1784
1785(defun matlab-end-of-defun ()
1786 "Go to the end of the current function."
1787 (interactive)
1788 (or (progn
1789 (if (looking-at matlab-defun-regex) (goto-char (match-end 0)))
1790 (if (re-search-forward matlab-defun-regex nil t)
1791 (progn (forward-line -1)
1792 t)))
1793 (goto-char (point-max))))
1794
1795(defun matlab-current-defun ()
1796 "Return the name of the current function."
1797 (save-excursion
1798 (matlab-beginning-of-defun)
1799 (if (looking-at (matlab-match-function-re))
1800 (progn
1801 (goto-char (match-end 0))
1802 (current-word)))))
1803
1804(defun matlab-beginning-of-command ()
1805 "Go to the beginning of an M command.
1806Travels across continuations."
1807 (interactive)
1808 (beginning-of-line)
1809 (let ((p nil)
1810 ;; This restriction is a wild guess where to end reverse
1811 ;; searching for array continuations. The reason is that
1812 ;; matlab up list is very slow, and most people would never
1813 ;; put a blank line in a matrix. Either way, it's worth the
1814 ;; trade off to speed this up for large files.
1815 ;; This list of keywords is NOT meant to be comprehensive.
1816 (r (save-excursion
1817 (re-search-backward
1818 "^\\s-*\\(%\\|if\\|else\\(if\\)\\|while\\|\\(par\\)?for\\|$\\)\\>"
1819 nil t))))
1820 (while (and (or (save-excursion (and (matlab-prev-line)
1821 (matlab-lattr-cont)))
1822 (matlab-ltype-continued-comm)
1823 (setq p (matlab-lattr-array-cont r)))
1824 (save-excursion (beginning-of-line) (not (bobp))))
1825 (if p (goto-char p) (matlab-prev-line))
1826 (setq p nil))
1827 (back-to-indentation)))
1828
1829(defun matlab-end-of-command (&optional beginning)
1830 "Go to the end of an M command.
1831Optional BEGINNING is where the command starts from."
1832 (interactive)
1833 (while (and (or (matlab-lattr-cont)
1834 (save-excursion
1835 (forward-line 1)
1836 (or (matlab-ltype-continued-comm)
1837 (matlab-lattr-array-cont beginning))))
1838 ;; This hack is a short circuit. If a user did not
1839 ;; correctly end a matrix, this will short-circuit
1840 ;; as soon as somethng that would never appear in a matrix
1841 ;; becomes visible.
1842 (not (save-excursion
1843 (beginning-of-line)
1844 (looking-at (matlab-block-scan-re))))
1845 ;; If we hit the end of the buffer unexpectedly, this test
1846 ;; will fail and we'll avoid looping forever. (E.g., this
1847 ;; is triggered if a continuation line is the last one in
1848 ;; the buffer, and the line lacks the final newline.)
1849 (zerop (forward-line 1))))
1850 (end-of-line))
1851
1852
1853;;; Line types and attributes =================================================
1854
1855(defun matlab-ltype-empty () ; blank line
1856 "Return t if current line is empty."
1857 (save-excursion
1858 (beginning-of-line)
1859 (looking-at "^[ \t]*$")))
1860
1861(defun matlab-ltype-comm () ; comment line
1862 "Return t if current line is a MATLAB comment line.
1863Return the symbol 'cellstart if it is a double %%."
1864 (save-excursion
1865 (beginning-of-line)
1866 (cond ((looking-at "[ \t]*%\\([^%]\\|$\\)")
1867 t)
1868 ((looking-at "[ \t]*%%")
1869 'cellstart)
1870 (t nil))))
1871
1872(defun matlab-ltype-comm-ignore () ; comment out a region line
1873 "Return t if current line is a MATLAB comment region line."
1874 (save-excursion
1875 (beginning-of-line)
1876 (looking-at (concat "[ \t]*" matlab-comment-region-s))))
1877
1878(defun matlab-ltype-help-comm ()
1879 "Return t if the current line is part of the MATLAB help comment."
1880 (save-excursion
1881 (if (not (matlab-ltype-comm))
1882 nil
1883 (while (and (matlab-ltype-comm) (not (bobp))
1884 (matlab-prev-line))
1885 (beginning-of-line))
1886 (matlab-ltype-function-definition))))
1887
1888(defun matlab-ltype-endfunction-comm ()
1889 "Return t if the current line is an ENDFUNCTION style comment."
1890 (save-excursion
1891 (if (not (matlab-ltype-comm))
1892 nil
1893 (beginning-of-line)
1894 (if (looking-at "^[ \t]*%[ \t]*endfunction")
1895 t
1896 (while (and (or (matlab-ltype-comm)
1897 (matlab-ltype-empty))
1898 (not (eobp)))
1899 (forward-line 1))
1900 (and (matlab-ltype-function-definition)
1901 (not (save-excursion (matlab-beginning-of-enclosing-defun))))
1902 ))))
1903
1904(defun matlab-ltype-continued-comm ()
1905 "Return column of previous line's comment start, or nil."
1906 (save-excursion
1907 (beginning-of-line)
1908 (let ((commtype (matlab-ltype-comm)))
1909 (if (or (eq commtype 'cellstart) ;; Cells are not continuations from previous comments.
1910 (null commtype)
1911 (bobp))
1912 nil
1913 ;; We use forward-line and not matlab-prev-line because
1914 ;; we want blank lines to terminate this indentation method.
1915 (forward-line -1)
1916 (let ((col (matlab-lattr-comm)))
1917 (if col
1918 (progn
1919 (goto-char col)
1920 (current-column))
1921 nil))))))
1922
1923(defun matlab-ltype-function-definition ()
1924 "Return t if the current line is a function definition."
1925 (save-excursion
1926 (beginning-of-line)
1927 (looking-at matlab-defun-regex)))
1928
1929(defun matlab-ltype-code () ; line of code
1930 "Return t if current line is a MATLAB code line."
1931 (and (not (matlab-ltype-empty)) (not (matlab-ltype-comm))))
1932
1933(defun matlab-lattr-comm () ; line has comment
1934 "Return t if current line contain a comment."
1935 (save-excursion (matlab-comment-on-line)))
1936
1937(defun matlab-lattr-implied-continuation ()
1938 "Return non-nil if this line has implied continuation on the next.
1939This is only useful for new versions of MATLAB where ... is optional."
1940 (when (not (matlab-lattr-comm))
1941 (let ((imp nil))
1942 (save-excursion
1943 (end-of-line)
1944 (skip-chars-backward " \t")
1945 ;; Test for oporator incompleteness.
1946 (setq imp
1947 (/= (point)
1948 ;; Careful, - means range in this expression.
1949 (progn (skip-chars-backward "-+=/*.^&~<>")
1950 (point))))
1951 (if (not imp)
1952 ;; Test for argument list incompleteness
1953 (condition-case nil
1954 (progn
1955 (end-of-line)
1956 (matlab-up-list -1)
1957 (setq imp (looking-at "(")))
1958 (error nil)))
1959 )
1960 imp)))
1961
1962(defun matlab-lattr-cont () ; line has continuation
1963 "Return non-nil if current line ends in ... and optional comment.
1964If `matlab-cont-requires-ellipsis' is nil, then we need to apply
1965a heuristic to determine if this line would use continuation
1966based on what it ends with."
1967 (save-excursion
1968 (beginning-of-line)
1969 (or
1970 ;; Here, if the line ends in ..., then it is what we are supposed to do.
1971 (and (re-search-forward "[^ \t.][ \t]*\\.\\.+[ \t]*\\(%.*\\)?$"
1972 (matlab-point-at-eol) t)
1973 (progn (goto-char (match-beginning 0))
1974 (not (matlab-cursor-in-comment))))
1975 ;; If the line doesn't end in ..., but we have optional ..., then
1976 ;; use this annoying heuristic.
1977 (and (null matlab-cont-requires-ellipsis)
1978 (matlab-lattr-implied-continuation))
1979 )))
1980
1981(defun matlab-lattr-array-cont (&optional restrict)
1982 "Return non-nil if current line is in an array.
1983If the entirety of the array is on this line, return nil.
1984Optional option RESTRICT is the distrance to restrict the search."
1985 (condition-case nil
1986 (save-excursion
1987 (beginning-of-line)
1988 (matlab-up-list -1 restrict)
1989 (and (looking-at "[[{]") (point)))
1990 (error nil)))
1991
1992(defun matlab-lattr-array-end ()
1993 "Return non-nil if the current line closes an array.
1994by close, the first character is the end of an array."
1995 (save-excursion
1996 (back-to-indentation)
1997 (and (looking-at "[]}]") (matlab-lattr-array-cont))))
1998
1999(defun matlab-lattr-block-cont (&optional eol)
2000 "Return a number representing the number of unterminated block constructs.
2001This is any block, such as if or for, that doesn't have an END on this line.
2002Optional EOL indicates a virtual end of line."
2003 (let ((v 0))
2004 (save-excursion
2005 (beginning-of-line)
2006 (save-restriction
2007 (narrow-to-region (point) (or eol (matlab-point-at-eol)))
2008 (matlab-navigation-syntax
2009 (while (re-search-forward (concat "\\<" (matlab-block-beg-re) "\\>")
2010 nil t)
2011 (if (matlab-cursor-in-string-or-comment)
2012 ;; Do nothing
2013 nil
2014 ;; Increment counter, move to end.
2015 (setq v (1+ v))
2016 (let ((p (point)))
2017 (forward-word -1)
2018 (condition-case nil
2019 (progn
2020 (matlab-forward-sexp)
2021 (setq v (1- v)))
2022 (error (goto-char p))))))
2023 v)))))
2024
2025(defun matlab-lattr-middle-block-cont ()
2026 "Return the number of middle block continuations.
2027This should be 1 or nil, and only true if the line starts with one of these
2028special items."
2029 (save-excursion
2030 (back-to-indentation)
2031 (if (looking-at (concat (matlab-block-mid-re) "\\>"))
2032 (if (and (re-search-forward (matlab-block-end-pre)
2033 (matlab-point-at-eol)
2034 t)
2035 (matlab-valid-end-construct-p))
2036 ;; If there is an END, we still need to return non-nil,
2037 ;; but the number value is a net of 0.
2038 0
2039 1)
2040 nil)))
2041
2042(defun matlab-lattr-endless-block-cont ()
2043 "Return the number of middle block continuations.
2044This should be 1 or nil, and only true if the line starts with one of these
2045special items."
2046 (save-excursion
2047 (back-to-indentation)
2048 (if (looking-at (concat (matlab-endless-blocks-re) "\\>"))
2049 1
2050 nil)))
2051
2052(defun matlab-lattr-block-close (&optional start)
2053 "Return the number of closing block constructs.
2054Argument START is where to start searching from."
2055 (let ((v 0))
2056 (save-excursion
2057 (when start (goto-char start))
2058 (save-restriction
2059 (narrow-to-region (save-excursion
2060 (matlab-beginning-of-command)
2061 (point))
2062 (matlab-point-at-eol))
2063 (goto-char (point-max))
2064 (while (and (re-search-backward (concat "\\<" (matlab-block-end-re) "\\>")
2065 nil t)
2066 (not (matlab-cursor-in-string-or-comment))
2067 (matlab-valid-end-construct-p))
2068 (setq v (1+ v))
2069 (let ((startmove (match-end 0))
2070 (nomove (point)))
2071 (condition-case nil
2072 (progn
2073 (matlab-backward-sexp t)
2074 (setq v (1- v)))
2075 (error (goto-char nomove)))
2076 ))
2077 ;; If we can't scoot back, do a cheat-test to see if there
2078 ;; is a matching else or elseif.
2079 (goto-char (point-min))
2080 (back-to-indentation)
2081 (if (looking-at (matlab-block-mid-re))
2082 (setq v (1- v)))
2083 ;; Return nil, or a number
2084 (if (<= v 0) nil v)))))
2085
2086(defun matlab-lattr-local-end ()
2087 "Return t if this line begins with an end construct."
2088 (save-excursion
2089 (back-to-indentation)
2090 (and (looking-at (concat "\\<" (matlab-block-end-re) "\\>"))
2091 (matlab-valid-end-construct-p))))
2092
2093(defun matlab-lattr-semantics (&optional prefix)
2094 "Return the semantics of the current position.
2095Values are nil 'solo, 'value, and 'boolean. Boolean is a subset of
2096value. nil means there is no semantic content (ie, string or comment.)
2097If optional PREFIX, then return 'solo if that is the only thing on the
2098line."
2099 (cond ;((matlab-cursor-in-string-or-comment)
2100 ;nil)
2101 ((or (matlab-ltype-empty)
2102 (and prefix (save-excursion
2103 (beginning-of-line)
2104 (looking-at (concat "\\s-*" prefix "\\s-*$")))))
2105 'solo)
2106 ((save-excursion
2107 (matlab-beginning-of-command)
2108 (looking-at "\\s-*\\(if\\|elseif\\|while\\)\\>"))
2109 'boolean)
2110 ((save-excursion
2111 (matlab-beginning-of-command)
2112 (looking-at (concat "\\s-*\\(" (matlab-property-function)
2113 "\\)\\>")))
2114 'property)
2115 (t
2116 'value)))
2117
2118(defun matlab-function-called-at-point ()
2119 "Return a string representing the function called nearby point."
2120 (save-excursion
2121 (beginning-of-line)
2122 (cond ((looking-at "\\s-*\\([a-zA-Z]\\w+\\)[^=][^=]")
2123 (match-string 1))
2124 ((and (re-search-forward "=" (matlab-point-at-eol) t)
2125 (looking-at "\\s-*\\([a-zA-Z]\\w+\\)\\s-*[^=]"))
2126 (match-string 1))
2127 (t nil))))
2128
2129(defun matlab-cursor-in-string-or-comment ()
2130 "Return t if the cursor is in a valid MATLAB comment or string."
2131 ;; comment and string depend on each other. Here is one test
2132 ;; that does both.
2133 (save-restriction
2134 (narrow-to-region (matlab-point-at-bol) (matlab-point-at-eol))
2135 (let ((p (1+ (point)))
2136 (returnme nil)
2137 (sregex (concat matlab-string-start-regexp "'")))
2138 (save-excursion
2139 (goto-char (point-min))
2140 (while (and (re-search-forward
2141 (concat "'\\|%\\|" (regexp-quote matlab-elipsis-string))
2142 nil t)
2143 (<= (point) p))
2144 (if (or (= ?% (preceding-char))
2145 (= ?. (preceding-char)))
2146 ;; Here we are in a comment for the rest of it.
2147 (progn
2148 (goto-char p)
2149 (setq returnme t))
2150 ;; Here, we could be a string start, or transpose...
2151 (if (or (= (current-column) 1)
2152 (save-excursion (forward-char -2)
2153 (looking-at sregex)))
2154 ;; a valid string start, find the end
2155 (let ((f (re-search-forward matlab-string-end-regexp nil t)))
2156 (if f
2157 (setq returnme (> (point) p))
2158 (setq returnme t)))
2159 ;; Ooops, a transpose, keep going.
2160 ))))
2161 returnme)))
2162
2163(defun matlab-cursor-in-comment ()
2164 "Return t if the cursor is in a valid MATLAB comment."
2165 (save-match-data
2166 (save-restriction
2167 (narrow-to-region (matlab-point-at-bol) (matlab-point-at-eol))
2168 (save-excursion
2169 (let ((prev-match nil))
2170 (while (and (re-search-backward
2171 (concat "%\\|" (regexp-quote matlab-elipsis-string) "+")
2172 nil t)
2173 (not (matlab-cursor-in-string)))
2174 (setq prev-match (point)))
2175 (if (and prev-match (matlab-cursor-in-string))
2176 (goto-char prev-match))
2177 (and (looking-at (concat "%\\|"
2178 (regexp-quote matlab-elipsis-string)))
2179 (not (matlab-cursor-in-string))))))))
2180
2181(defun matlab-cursor-in-string (&optional incomplete)
2182 "Return t if the cursor is in a valid MATLAB string.
2183If the optional argument INCOMPLETE is non-nil, then return t if we
2184are in what could be a an incomplete string."
2185 (let ((m (match-data))
2186 (returnme nil))
2187 (save-restriction
2188 (narrow-to-region (matlab-point-at-bol) (matlab-point-at-eol))
2189 (let ((p (1+ (point)))
2190
2191 (sregex (concat matlab-string-start-regexp "'"))
2192 (instring nil))
2193 (save-excursion
2194 ;; Comment hunters need strings to not call the comment
2195 ;; identifiers. Thus, this routines must be savvy of comments
2196 ;; without recursing to them.
2197 (goto-char (point-min))
2198 (while (or (and instring (looking-at "'"))
2199 (and (re-search-forward
2200 (concat "'\\|%\\|"
2201 (regexp-quote matlab-elipsis-string))
2202 nil t)
2203 (<= (point) p)
2204 ;; Short circuit to fix this.
2205 (progn (setq instring nil) t)))
2206 ;; The next line emulates re-search-foward
2207 (if instring (goto-char (match-end 0)))
2208 (if (or (= ?% (preceding-char))
2209 (= ?. (preceding-char)))
2210 ;; Here we are in a comment for the rest of it.
2211 ;; thus returnme is a force-false.
2212 (goto-char p)
2213 ;; Here, we could be in a string start, or transpose...
2214 (if (or (= (current-column) 1)
2215 instring
2216 (save-excursion (forward-char -2)
2217 (looking-at sregex)))
2218 ;; a valid string start, find the end
2219 (let ((f (re-search-forward matlab-string-end-regexp nil t)))
2220 (if (and (not f) incomplete)
2221 (setq returnme t)
2222 (setq returnme (> (point) p))
2223 (setq instring t)))
2224 ;; Ooops, a transpose, keep going.
2225 ))))))
2226 (set-match-data m)
2227 returnme))
2228
2229
2230(defun matlab-comment-on-line ()
2231 "Place the cursor on the beginning of a valid comment on this line.
2232If there isn't one, then return nil, point otherwise."
2233 (interactive)
2234 (let ((eol (matlab-point-at-eol))
2235 (p (point))
2236 (signal-error-on-buffer-boundary nil))
2237 (beginning-of-line)
2238 (while (and (re-search-forward "%" eol t)
2239 (save-excursion (forward-char -1) (matlab-cursor-in-string t))))
2240 (if (not (bolp)) (forward-char -1))
2241 (if (and (looking-at "%") (not (matlab-cursor-in-string t)))
2242 (point)
2243 (goto-char p)
2244 nil)))
2245
2246;;; Indent functions ==========================================================
2247
2248(defun matlab-indent-line ()
2249 "Indent a line in `matlab-mode'."
2250 (interactive)
2251 (let ((i (matlab-calc-indent))
2252 (c (current-column)))
2253 (save-excursion
2254 (back-to-indentation)
2255 (if (= i (current-column))
2256 nil
2257 (beginning-of-line)
2258 (delete-horizontal-space)
2259 (indent-to i))
2260 ;; If line contains a comment, format it.
2261 (if () (if (matlab-lattr-comm) (matlab-comment))))
2262 (if (<= c i) (move-to-column i))))
2263
2264(defun matlab-calc-indent ()
2265 "Return the appropriate indentation for this line as an integer."
2266 (interactive)
2267 ;; The first step is to find the current indentation.
2268 ;; This is defined to be zero if all previous lines are empty.
2269 (let* ((ci (save-excursion (if (not (matlab-prev-line))
2270 0
2271 (matlab-next-line-indentation))))
2272 (sem (matlab-calculate-indentation ci)))
2273 ;; simplistic
2274 (nth 1 sem)))
2275
2276(defconst matlab-functions-have-end-should-be-true
2277 "This end closes a function definition.\nDo you want functions to have ends? "
2278 "Prompt the user about whether to change matlab-functions-have-end")
2279
2280(defun matlab-calculate-indentation (current-indentation)
2281 "Calculate out the indentation of the current line.
2282Return a list of descriptions for this line. Return format is:
2283 '(TYPE DEPTHNUMBER)
2284where TYPE is one of (comment, code, function, blockstart, blockmid,
2285blockendless, blockend) DEPTHNUMBER is how many characters to indent
2286this line.
2287 Argument CURRENT-INDENTATION is what the previous line thinks
2288this line's indentation should be. See `matlab-next-line-indentation'."
2289 (matlab-navigation-syntax
2290 (matlab-calculate-indentation-1 current-indentation)))
2291
2292(defun matlab-calculate-indentation-1 (current-indentation)
2293 "Do the indentation work of `matlab-calculate-indentation'.
2294Argument CURRENT-INDENTATION is what the previous line recommends for indentation."
2295 (let ((ci current-indentation)
2296 (tmp nil))
2297 (cond
2298 ;; COMMENTS
2299 ((matlab-ltype-comm)
2300 (cond
2301 ;; HELP COMMENT and COMMENT REGION
2302 ((or (matlab-ltype-help-comm)
2303 (matlab-ltype-comm-ignore))
2304 (list 'comment-help
2305 (save-excursion
2306 (matlab-beginning-of-defun)
2307 (current-indentation))))
2308 ;; COMMENT Continued From Previous Line
2309 ((setq tmp (matlab-ltype-continued-comm))
2310 (list 'comment tmp))
2311 ;; END FUNCTION COMMENT
2312 ((matlab-ltype-endfunction-comm)
2313 (list 'comment-endfunction 0))
2314 (t
2315 (list 'comment (+ ci matlab-comment-anti-indent)))))
2316 ;; FUNCTION DEFINITION
2317 ((matlab-ltype-function-definition)
2318 (if matlab-functions-have-end
2319 ;; A function line has intrinsic indentation iff function bodies are
2320 ;; not indented and the function line is nested within another function.
2321 (if (and (not (matlab-indent-function-body-p))
2322 (save-excursion
2323 (beginning-of-line)
2324 (matlab-beginning-of-enclosing-defun)))
2325 (setq ci (+ ci matlab-indent-level))
2326 ;; If no intrinsic indentation, do not change from ci.
2327 )
2328 ;; If functions are not nested, functions go to left margin.
2329 (setq ci 0))
2330 (list 'function ci))
2331 ;; END keyword
2332 ((matlab-lattr-local-end)
2333 (let ((end-of-function
2334 (let ((matlab-functions-have-end t))
2335 (save-excursion
2336 (beginning-of-line)
2337 (matlab-backward-sexp t) ;; may throw "unstarted block" error
2338 (matlab-ltype-function-definition)))))
2339 (if end-of-function
2340 (if (or matlab-functions-have-end
2341 (if (yes-or-no-p matlab-functions-have-end-should-be-true)
2342 ;; TODO - ask user to reindent the fcn now?
2343 (setq matlab-functions-have-end t)
2344 (error "Unmatched end")))
2345 (if (matlab-indent-function-body-p)
2346 (setq ci (- ci matlab-indent-level))))
2347 ;; Next, see if this line starts with an end, and whether the
2348 ;; end is matched, and whether the line is blank up to the match.
2349 ;; If so, return the indentation of the match.
2350 (catch 'indent
2351 (save-excursion
2352 (when (progn (beginning-of-line)
2353 (and (looking-at "[ \t]*end\\b")
2354 (matlab-backward-sexp t t)))
2355 (let ((match (point)))
2356 (beginning-of-line)
2357 (looking-at "[ \t]*")
2358 (when (= match (match-end 0))
2359 (setq ci (- match (match-beginning 0)))
2360 (throw 'indent nil)))))
2361 ;; End of special case for end and match after "^[ \t]*".
2362 (setq ci (+ ci
2363 (* (1- (matlab-lattr-block-cont (point)))
2364 matlab-indent-level))))))
2365 (list 'blockend ci))
2366 ;; ELSE/CATCH keywords
2367 ((matlab-lattr-middle-block-cont)
2368 (let ((m (match-string 1)))
2369 (list 'blockmid
2370 (condition-case nil
2371 (save-excursion
2372 (beginning-of-line)
2373 (matlab-backward-sexp t)
2374 (if (matlab-ltype-function-definition) (error ""))
2375 (current-column))
2376 (error (error "Unmatched %s" m))))))
2377 ;; CASE/OTHERWISE keywords
2378 ((matlab-lattr-endless-block-cont)
2379 (list 'blockendless
2380 (condition-case nil
2381 (save-excursion
2382 (beginning-of-line)
2383 (matlab-backward-sexp t)
2384 (if (not (looking-at "switch\\>")) (error ""))
2385 (+ (current-column)
2386 (if (listp matlab-case-level)
2387 (car matlab-case-level)
2388 matlab-case-level)))
2389 (error (error "Unmatched case/otherwise part")))))
2390 ;; End of a MATRIX
2391 ((matlab-lattr-array-end)
2392 (list 'array-end (save-excursion
2393 (back-to-indentation)
2394 (matlab-up-list -1)
2395 (let* ((fc (following-char))
2396 (mi (assoc fc matlab-maximum-indents))
2397 (max (if mi (if (listp (cdr mi))
2398 (car (cdr mi)) (cdr mi))
2399 nil))
2400 (ind (if mi (if (listp (cdr mi))
2401 (cdr (cdr mi)) (cdr mi))
2402 nil)))
2403 ;; apply the maximum limits.
2404 (if (and ind (> (- (current-column) ci) max))
2405 (1- ind) ; decor
2406 (current-column))))))
2407 ;; Code lines
2408 ((save-excursion
2409 (beginning-of-line)
2410 (back-to-indentation)
2411 (= (point) (progn (matlab-beginning-of-command) (point))))
2412 ;; This means we are at the beginning of a command structure.
2413 ;; Always match up against the previous line.
2414 (list 'code ci))
2415 ;; Lines continued from previous statements.
2416 (t
2417 (list (if (matlab-ltype-empty) 'empty
2418 (if (matlab-lattr-array-cont) 'array-cont 'code))
2419 (condition-case nil
2420 ;; Line up with opening paren/brace/bracket
2421 (let ((boc (save-excursion
2422 (matlab-beginning-of-command)
2423 (point))))
2424 (save-excursion
2425 (beginning-of-line)
2426 (matlab-up-list -1)
2427 (if (> boc (point)) (error nil))
2428 ;; Ok, it MIGHT be that we are in a program
2429 ;; statement, and this particular command is an HG
2430 ;; statement that would look better if the
2431 ;; following lines lined up AFTER the first
2432 ;; argument. Lets look.
2433 (let ((parendepth (current-column)))
2434 (cond ((and (= (following-char) ?\( )
2435 (save-excursion
2436 (matlab-navigation-syntax
2437 (forward-word -1)
2438 (looking-at
2439 matlab-indent-past-arg1-functions)))
2440 (let ((start-paren (point)))
2441 (while
2442 (and
2443 (re-search-forward
2444 "," (matlab-point-at-eol) t)
2445 (save-excursion
2446 (matlab-up-list -1)
2447 (> (point) start-paren))))
2448 (if (and
2449 (= (preceding-char) ?,)
2450 ;; Don't bother if we hit the EOL.
2451 (not (looking-at
2452
2453 "\\s-*\\(\\.\\.\\.\\|$\\|)\\)")))
2454 t
2455 (move-to-column parendepth)
2456 nil)))
2457 (skip-chars-forward " \t")
2458 (if (> (- (current-column) parendepth)
2459 matlab-arg1-max-indent-length)
2460 (+ parendepth matlab-arg1-max-indent-length)
2461 (current-column)))
2462 (t
2463 (let* ((fc (following-char))
2464 (mi (assoc fc matlab-maximum-indents))
2465 (max (if mi
2466 (if (listp (cdr mi))
2467 (car (cdr mi)) (cdr mi))
2468 nil))
2469 (ind (if mi
2470 (if (listp (cdr mi))
2471 (cdr (cdr mi)) (cdr mi))
2472 nil)))
2473 (forward-char 1)
2474 (skip-chars-forward " \t")
2475 ;; If we are at the end of a line and
2476 ;; this open paren is there, then we
2477 ;; DONT want to indent to it. Use the
2478 ;; standard indent.
2479 (if (looking-at "\\.\\.\\.\\|$")
2480 ;; This could happen in another set
2481 ;; of matricies. Find a current
2482 ;; indentation based on the
2483 ;; previous line.
2484 (let ((cci (current-indentation)))
2485 (+ cci matlab-cont-level))
2486 ;; apply the maximum limits.
2487 (if (and ind (> (- (current-column) ci) max))
2488 (+ ci ind)
2489 (current-column)))))))))
2490 (error
2491 ;; Line up to an equals sign.
2492 (save-excursion
2493 (matlab-beginning-of-command)
2494 (while (and (re-search-forward "=" (matlab-point-at-eol) t)
2495 (matlab-cursor-in-string-or-comment)))
2496 (if (/= (preceding-char) ?=)
2497 (+ ci matlab-cont-level)
2498 (skip-chars-forward " \t")
2499 (let ((cc (current-column))
2500 (mi (assoc ?= matlab-maximum-indents)))
2501 (if (looking-at "\\.\\.\\.\\|$")
2502 ;; In this case, the user obviously wants the
2503 ;; indentation to be somewhere else.
2504 (+ ci (cdr (cdr mi)))
2505 ;; If the indent delta is greater than the max,
2506 ;; use the max + currenti
2507 (if (and mi (> (- cc ci) (if (listp (cdr mi))
2508 (car (cdr mi))
2509 (cdr mi))))
2510 (setq cc (+ ci (if (listp (cdr mi))
2511 (cdr (cdr mi))
2512 (cdr mi)))))
2513 cc))))))))
2514 )))
2515
2516(defun matlab-next-line-indentation ()
2517 "Calculate the indentation for lines following this command line.
2518Assume that the following line does not contribute its own indentation
2519\(as it does in the case of nested functions in the following situations):
2520 o function---positive indentation when not indenting function bodies.
2521 o end---negative indentation except when the 'end' matches a function and
2522 not indenting function bodies.
2523See `matlab-calculate-indentation'."
2524 (matlab-navigation-syntax
2525 (let ((startpnt (point-at-eol)))
2526 (save-excursion
2527 (matlab-beginning-of-command)
2528 (let ((cc (or (matlab-lattr-block-close startpnt) 0))
2529 (end (matlab-lattr-local-end))
2530 (bc (matlab-lattr-block-cont startpnt))
2531 (mc (matlab-lattr-middle-block-cont))
2532 (ec (matlab-lattr-endless-block-cont))
2533 (hc (and (matlab-indent-function-body-p) (matlab-ltype-help-comm)))
2534 (rc (and (/= 0 matlab-comment-anti-indent)
2535 (matlab-ltype-comm)
2536 (not (matlab-ltype-help-comm))
2537 (not (matlab-ltype-continued-comm))
2538 (not (matlab-ltype-endfunction-comm))))
2539 (ci (current-indentation)))
2540 ;; When the current point is on a line with a function, the value of bc will
2541 ;; reflect the function in a block count iff if matlab-functions-have-end is
2542 ;; true. However, if matlab-indent-function-body-p is false, there should be
2543 ;; no actual indentation, so bc needs to be decremented by 1. Similarly, if
2544 ;; on a line with an end that closes a function, bc needs to be decremented
2545 ;; by 1 if matlab-functions-have-end is true and matlab-indent-function-body-p
2546 ;; is false. However, just to be safe, indentation is not allowed to go
2547 ;; negative. Thus:
2548 (if matlab-functions-have-end
2549 (if (and
2550 (not (matlab-indent-function-body-p))
2551 (or (matlab-ltype-function-definition)
2552 (and (matlab-lattr-local-end)
2553 (save-excursion
2554 (matlab-backward-sexp t)
2555 (looking-at "function\\b")))))
2556 (if (> bc 0)
2557 (setq bc (1- bc))
2558 (if (>= ci matlab-indent-level)
2559 (setq bc -1))))
2560 (if (and (matlab-indent-function-body-p) (matlab-ltype-function-definition))
2561 (setq bc (1+ bc))))
2562 ;; Remove 1 from the close count if there is an END on the beginning
2563 ;; of this line, since in that case, the unindent has already happened.
2564 (when end (setq cc (1- cc)))
2565 ;; Calculate the suggested indentation.
2566 (+ ci
2567 (* matlab-indent-level bc)
2568 (* matlab-indent-level (or mc 0))
2569 (* matlab-indent-level (- cc))
2570 (* (if (listp matlab-case-level)
2571 (cdr matlab-case-level) matlab-case-level)
2572 (or ec 0))
2573 (if hc matlab-indent-level 0)
2574 (if rc (- 0 matlab-comment-anti-indent) 0)
2575 ))))))
2576
2577;;; The return key ============================================================
2578
2579(defcustom matlab-return-function 'matlab-indent-end-before-ret
2580 "Function to handle return key.
2581Must be one of:
2582 'matlab-plain-ret
2583 'matlab-indent-after-ret
2584 'matlab-indent-end-before-ret
2585 'matlab-indent-before-ret"
2586 :group 'matlab
2587 :type '(choice (function-item matlab-plain-ret)
2588 (function-item matlab-indent-after-ret)
2589 (function-item matlab-indent-end-before-ret)
2590 (function-item matlab-indent-before-ret)))
2591
2592(defun matlab-return ()
2593 "Handle carriage return in `matlab-mode'."
2594 (interactive)
2595 (matlab-semicolon-on-return)
2596 (funcall matlab-return-function))
2597
2598(defun matlab-plain-ret ()
2599 "Vanilla new line."
2600 (interactive)
2601 (newline))
2602
2603(defun matlab-indent-after-ret ()
2604 "Indent after new line."
2605 (interactive)
2606 (newline)
2607 (matlab-indent-line))
2608
2609(defun matlab-indent-end-before-ret ()
2610 "Indent line if block end, start new line, and indent again."
2611 (interactive)
2612 (if (save-excursion
2613 (beginning-of-line)
2614 (looking-at (concat "^\\s-*\\(" (matlab-block-end-re)
2615 "\\|" (matlab-block-mid-re)
2616 "\\|" (matlab-endless-blocks-re)
2617 "\\|function\\)")))
2618 (matlab-indent-line))
2619 (newline)
2620 (matlab-indent-line))
2621
2622(defun matlab-semicolon-on-return ()
2623 "If needed, add a semicolon at point automatically."
2624 (if matlab-return-add-semicolon
2625 (if (and (not (matlab-ltype-empty))
2626 (not (save-excursion
2627 (skip-chars-backward " \t;" (matlab-point-at-bol))
2628 (looking-at "\\s-*;")))
2629 (save-excursion
2630 (let ((p (point)))
2631 (matlab-end-of-command (point))
2632 (eq p (point))))
2633 (save-excursion
2634 (matlab-beginning-of-command)
2635 ;; Note: Compile warning below, but defined later.
2636 (not (looking-at matlab-quiesce-nosemi-regexp))))
2637 (insert ";"))
2638 ))
2639
2640(defun matlab-indent-before-ret ()
2641 "Indent line, start new line, and indent again."
2642 (interactive)
2643 (matlab-indent-line)
2644 (newline)
2645 (matlab-indent-line))
2646
2647(defun matlab-linefeed ()
2648 "Handle line feed in `matlab-mode'.
2649Has effect of `matlab-return' with (not matlab-indent-before-return)."
2650 (interactive)
2651 (matlab-indent-line)
2652 (newline)
2653 (matlab-indent-line))
2654
2655(defun matlab-comment-return ()
2656 "Handle carriage return for MATLAB comment line."
2657 (interactive)
2658 (cond
2659 ((matlab-ltype-comm)
2660 (matlab-set-comm-fill-prefix) (newline) (insert fill-prefix)
2661 (matlab-reset-fill-prefix) (matlab-indent-line))
2662 ((matlab-lattr-comm)
2663 (newline) (indent-to comment-column)
2664 (insert matlab-comment-on-line-s))
2665 (t
2666 (newline) (matlab-comment) (matlab-indent-line))))
2667
2668(defun matlab-comm-from-prev ()
2669 "If the previous line is a comment-line then set up a comment on this line."
2670 (save-excursion
2671 ;; If the previous line is a comment-line then set the fill prefix from
2672 ;; the previous line and fill this line.
2673 (if (and (= 0 (forward-line -1)) (matlab-ltype-comm))
2674 (progn
2675 (matlab-set-comm-fill-prefix)
2676 (forward-line 1) (beginning-of-line)
2677 (delete-horizontal-space)
2678 (if (looking-at "%") (delete-char 1))
2679 (delete-horizontal-space)
2680 (insert fill-prefix)
2681 (matlab-reset-fill-prefix)))))
2682
2683(defun matlab-electric-comment (arg)
2684 "Indent line and insert comment character.
2685Argument ARG specifies how many %s to insert."
2686 (interactive "P")
2687 (self-insert-command (or arg 1))
2688 (when (matlab-ltype-comm)
2689 (matlab-indent-line)
2690 ;; The above seems to put the cursor on the %, not after it.
2691 (skip-chars-forward "%")))
2692
2693
2694;;; Comment management========================================================
2695
2696(defun matlab-comment ()
2697 "Add a comment to the current line."
2698 (interactive)
2699 (cond ((matlab-ltype-empty) ; empty line
2700 (matlab-comm-from-prev)
2701 (if (matlab-lattr-comm)
2702 (skip-chars-forward " \t%")
2703 (insert matlab-comment-line-s)
2704 (matlab-indent-line)))
2705 ((matlab-ltype-comm) ; comment line
2706 (matlab-comm-from-prev)
2707 (skip-chars-forward " \t%"))
2708 ((matlab-lattr-comm) ; code line w/ comment
2709 (beginning-of-line)
2710 (re-search-forward "[^%]%[ \t]")
2711 (forward-char -2)
2712 (if (> (current-column) comment-column) (delete-horizontal-space))
2713 (if (< (current-column) comment-column) (indent-to comment-column))
2714 (skip-chars-forward "% \t"))
2715 (t ; code line w/o comment
2716 (end-of-line)
2717 (re-search-backward "[^ \t\n^]" 0 t)
2718 (forward-char)
2719 (delete-horizontal-space)
2720 (if (< (current-column) comment-column)
2721 (indent-to comment-column)
2722 (insert " "))
2723 (insert matlab-comment-on-line-s))))
2724
2725(defun matlab-comment-line-break-function (&optional soft)
2726 "Break the current line, and if in a comment, continue it.
2727Optional argument SOFT indicates that the newline is soft, and not hard."
2728 (interactive)
2729 (if (not (matlab-cursor-in-comment))
2730 (matlab-return)
2731 ;; Will the below fn work in old emacsen?
2732 (if soft (insert-and-inherit ?\n) (newline 1))
2733 (insert "% ")
2734 (matlab-indent-line)
2735 (end-of-line)))
2736
2737(defun matlab-comment-indent ()
2738 "Indent a comment line in `matlab-mode'."
2739 (matlab-calc-indent))
2740
2741(defun matlab-comment-region (beg-region end-region arg)
2742 "Comments every line in the region.
2743Puts `matlab-comment-region-s' at the beginning of every line in the region.
2744BEG-REGION and END-REGION are arguments which specify the region boundaries.
2745With non-nil ARG, uncomments the region."
2746 (interactive "*r\nP")
2747 (let ((end-region-mark (make-marker)) (save-point (point-marker)))
2748 (set-marker end-region-mark end-region)
2749 (goto-char beg-region)
2750 (beginning-of-line)
2751 (if (not arg) ;comment the region
2752 (progn (insert matlab-comment-region-s)
2753 (while (and (= (forward-line 1) 0)
2754 (< (point) end-region-mark))
2755 (insert matlab-comment-region-s)))
2756 (let ((com (regexp-quote matlab-comment-region-s))) ;uncomment the region
2757 (if (looking-at com)
2758 (delete-region (point) (match-end 0)))
2759 (while (and (= (forward-line 1) 0)
2760 (< (point) end-region-mark))
2761 (if (looking-at com)
2762 (delete-region (point) (match-end 0))))))
2763 (goto-char save-point)
2764 (set-marker end-region-mark nil)
2765 (set-marker save-point nil)))
2766
2767(defun matlab-uncomment-region (beg end)
2768 "Uncomment the current region if it is commented out.
2769Argument BEG and END indicate the region to uncomment."
2770 (interactive "*r")
2771 (matlab-comment-region beg end t))
2772
2773;;; Filling ===================================================================
2774
2775(defun matlab-set-comm-fill-prefix ()
2776 "Set the `fill-prefix' for the current (comment) line."
2777 (interactive)
2778 (if (matlab-lattr-comm)
2779 (setq fill-prefix
2780 (save-excursion
2781 (beginning-of-line)
2782 (let ((e (matlab-point-at-eol))
2783 (pf nil))
2784 (while (and (re-search-forward "%+[ \t]*\\($$$ \\)?" e t)
2785 (matlab-cursor-in-string)))
2786 (setq pf (match-string 0))
2787 (concat (make-string (- (current-column) (length pf)) ? )
2788 pf))))))
2789
2790(defun matlab-set-comm-fill-prefix-post-code ()
2791 "Set the `fill-prefix' for the current post-code comment line."
2792 (interactive)
2793 (matlab-set-comm-fill-prefix))
2794
2795(defun matlab-reset-fill-prefix ()
2796 "Reset the `fill-prefix'."
2797 (setq fill-prefix nil))
2798
2799(defun matlab-find-convenient-line-break ()
2800 "For the current line, position the cursor where we want to break the line.
2801Basically, spaces are best, then operators. Always less than `fill-column'
2802unless we decide we can fudge the numbers. Return nil if this line should
2803not be broken. This function will ONLY work on code."
2804 ;; First of all, if this is a continuation, then the user is
2805 ;; requesting that we don't mess with his stuff.
2806 (if (matlab-lattr-cont)
2807 nil
2808 (save-restriction
2809 (narrow-to-region (matlab-point-at-bol) (matlab-point-at-eol))
2810 ;; get ourselves onto the fill-column.
2811 (move-to-column fill-column)
2812 (let ((pos nil)
2813 (orig (point)))
2814 (or
2815 ;; Next, if we have a trailing comment, use that.
2816 (progn (setq pos (or (matlab-lattr-comm) (matlab-point-at-bol)))
2817 (goto-char pos)
2818 (if (and (> (current-column) (- fill-column matlab-fill-fudge))
2819 (< (current-column) (+ fill-column matlab-fill-fudge)))
2820 t
2821 (goto-char orig)
2822 nil))
2823 ;; Now, lets find the nearest space (after or before fill column)
2824 (let* ((after (save-excursion
2825 (re-search-forward "[ \t]" nil t)))
2826 (before (save-excursion
2827 (re-search-backward "[ \t]" nil t)))
2828 (afterd (- (or after (matlab-point-at-eol)) (point)))
2829 (befored (- (point) (or before (matlab-point-at-bol)))))
2830 ;; Here, if "before" is actually the beginning of our
2831 ;; indentation, then this is most obiously a bad place to
2832 ;; break our lines.
2833 (if before
2834 (save-excursion
2835 (goto-char before)
2836 (if (<= (point) (save-excursion
2837 (back-to-indentation)
2838 (point)))
2839 (setq before nil))))
2840 (cond ((and after
2841 (< afterd matlab-fill-fudge)
2842 (< afterd befored))
2843 (goto-char after)
2844 t)
2845 ((and before
2846 (< befored matlab-fill-fudge)
2847 (< befored afterd))
2848 (goto-char before)
2849 t)
2850 (t (goto-char orig)
2851 nil)))
2852 ;; Now, lets find the nearest backwards
2853 (progn
2854 (re-search-backward "\\(\\s-\\|\\s.\\)+" nil t)
2855 (while (and (looking-at "\\^\\|\\.\\|'")
2856 (re-search-backward "\\(\\s-\\|\\s.\\)+" nil t)))
2857 (if (or (not (looking-at "\\(\\s-\\|\\s.\\)+"))
2858 (<= (point) (save-excursion
2859 (back-to-indentation)
2860 (point))))
2861 (progn
2862 ;; We failed in our mission to find anything, or fell
2863 ;; of the edge of the earth. If we are out of
2864 ;; bounds, lets try again.
2865 (goto-char orig)
2866 (if (re-search-backward "\\s.+" nil t)
2867 t
2868 nil))
2869 ;; Ok, we have a good location to break. Check for column
2870 ;; and ref against nearest list ending to predict a possibly
2871 ;; better break point.
2872 (forward-char 1)
2873 (let ((okpos (current-column))
2874 (startlst (save-excursion
2875 (condition-case nil
2876 (matlab-up-list -1)
2877 (error nil))
2878 (if (save-excursion
2879 (forward-char -1)
2880 (looking-at "\\w"))
2881 (forward-word -1))
2882 (current-column)))
2883 (endlst (save-excursion
2884 (condition-case nil
2885 (matlab-up-list 1)
2886 (error nil))
2887 (current-column))))
2888 ;; When evaluating list fudge factores, breaking on the
2889 ;; edge of a list, or at the beginning of a function
2890 ;; call can be more valuable than breaking on a symbol
2891 ;; of a mid-sized list. As such, allow double-fudge
2892 ;; for lists.
2893 (cond
2894 ;; First, pick the end of a list.
2895 ((and (< endlst matlab-fill-fudge-hard-maximum)
2896 (<= endlst (+ fill-column matlab-fill-fudge))
2897 (or (<= (* matlab-fill-fudge 2) (- endlst okpos))
2898 (<= endlst fill-column))
2899 (save-excursion
2900 (move-to-column endlst)
2901 (not (looking-at "\\^"))))
2902 (move-to-column endlst)
2903 t)
2904 ;; Else, back up over this list and poke around
2905 ((>= (* 2 matlab-fill-fudge) (- okpos startlst))
2906 (move-to-column startlst)
2907 t)
2908 ;; Oh well, just do this symbol.
2909 (t (move-to-column okpos)
2910 t)))))
2911 ;; Well, this just sucks
2912 (progn (goto-char orig)
2913 nil))))))
2914
2915(defun matlab-auto-fill ()
2916 "Do auto filling.
2917Set variable `auto-fill-function' to this symbol to enable MATLAB style auto
2918filling which will automatically insert `...' and the end of a line."
2919 (interactive)
2920 (let ((fill-prefix fill-prefix) ;; safe way of modifying fill-prefix.
2921 (fill-column (- fill-column
2922 (if matlab-fill-count-ellipsis-flag
2923 (save-excursion
2924 (move-to-column fill-column)
2925 (if (not (bobp))
2926 (forward-char -1))
2927 (if (matlab-cursor-in-string 'incomplete)
2928 4 3))
2929 0))))
2930 (if (> (current-column) fill-column)
2931 (cond
2932 ((matlab-ltype-comm-ignore)
2933 nil)
2934 ((or (matlab-ltype-comm)
2935 (and (save-excursion (move-to-column fill-column)
2936 (matlab-cursor-in-comment))
2937 (matlab-lattr-comm)))
2938 ;; If the whole line is a comment, do this.
2939 (matlab-set-comm-fill-prefix) (do-auto-fill)
2940 (matlab-reset-fill-prefix))
2941 ((and (matlab-ltype-code)
2942 (not (matlab-lattr-cont))
2943 matlab-fill-code)
2944 ;; If we are on a code line, we ellipsify before we fill.
2945 (let ((m (make-marker)))
2946 (move-marker m (point))
2947 (set-marker-insertion-type m t)
2948 (if (not (matlab-find-convenient-line-break))
2949 nil
2950 (if (not (save-excursion
2951 (forward-char -1)
2952 (matlab-cursor-in-string 'incomplete)))
2953 (progn
2954 (delete-horizontal-space)
2955 (insert " " matlab-elipsis-string "\n")
2956 (matlab-indent-line))
2957 (if matlab-fill-strings-flag
2958 (let ((pos (point))
2959 (pos2 nil))
2960 (while (and (re-search-backward "'" (point-at-bol) t)
2961 (progn (forward-char -1)
2962 (looking-at "''"))))
2963 (setq pos2 (point))
2964 ;; Check if there is already an opening bracket or if string is continued
2965 (if (or (looking-at "\\[")
2966 (save-excursion (skip-chars-backward " \t")
2967 (forward-char -1)
2968 (looking-at "\\["))
2969 (progn
2970 (beginning-of-line)
2971 (skip-chars-backward (concat " \t\n" matlab-elipsis-string))
2972 (if (> (point) (point-min))
2973 (progn
2974 (forward-char -1)
2975 (looking-at (concat "'\\s-*" matlab-elipsis-string))))))
2976 (goto-char pos)
2977 (goto-char pos2)
2978 (forward-char 1)
2979 (insert "[")
2980 (goto-char pos)
2981 (forward-char 1))
2982 ;(delete-horizontal-space)
2983 (skip-chars-forward " \t")
2984 (insert "' " matlab-elipsis-string "\n")
2985 (matlab-indent-line)
2986 (insert "'")
2987 ;; Re scan forward for the end of the string. Add an end bracket
2988 ;; if there isn't one already. Also add an apostrophe if necessary.
2989 (if (not (looking-at "'\\s-*]"))
2990 (save-excursion
2991 (if (not (re-search-forward "[^']'[^']" (line-end-position) t))
2992 (progn
2993 (end-of-line)
2994 (insert "']")
2995 (move-marker m (- (point) 2)))
2996 (forward-char -2)
2997 (if (not (looking-at "'\\s-*]"))
2998 (progn
2999 (forward-char 1)
3000 (insert "]"))))))
3001 ))))
3002 (goto-char m)))
3003 ))))
3004
3005(defun matlab-join-comment-lines ()
3006 "Join current comment line to the next comment line."
3007 ;; New w/ V2.0: This used to join the previous line, but I could find
3008 ;; no editors that had a "join" that did that. I modified join to have
3009 ;; a behaviour I thought more inline with other editors.
3010 (interactive)
3011 (end-of-line)
3012 (if (looking-at "\n[ \t]*%")
3013 (replace-match " " t t nil)
3014 (error "No following comment to join with")))
3015
3016(defun matlab-fill-region (beg-region end-region &optional justify-flag)
3017 "Fill the region between BEG-REGION and END-REGION.
3018Non-nil JUSTIFY-FLAG means justify comment lines as well."
3019 (interactive "*r\nP")
3020 (let ((end-reg-mk (make-marker)))
3021 (set-marker end-reg-mk end-region)
3022 (goto-char beg-region)
3023 (beginning-of-line)
3024 (while (< (point) end-reg-mk)
3025 ;; This function must also leave the point at the end of the
3026 ;; justified line.
3027 (matlab-fill-paragraph justify-flag)
3028 (forward-line 1)
3029 (beginning-of-line))))
3030
3031(defun matlab-fill-comment-line (&optional justify)
3032 "Fill the current comment line.
3033With optional argument, JUSTIFY the comment as well."
3034 (interactive)
3035 (if (not (matlab-comment-on-line))
3036 (error "No comment to fill"))
3037 (beginning-of-line)
3038 ;; First, find the beginning of this comment...
3039 (while (and (looking-at matlab-cline-start-skip)
3040 (not (bobp)))
3041 (forward-line -1)
3042 (beginning-of-line))
3043 (if (not (looking-at matlab-cline-start-skip))
3044 (forward-line 1))
3045 ;; Now scan to the end of this comment so we have our outer bounds,
3046 ;; and narrow to that region.
3047 (save-restriction
3048 (narrow-to-region (point)
3049 (save-excursion
3050 (while (and (looking-at matlab-cline-start-skip)
3051 (not (save-excursion (end-of-line) (eobp))))
3052 (forward-line 1)
3053 (beginning-of-line))
3054 (if (not (looking-at matlab-cline-start-skip))
3055 (forward-line -1))
3056 (end-of-line)
3057 (point)))
3058 ;; Find the fill prefix...
3059 (matlab-comment-on-line)
3060 (looking-at "%[ \t]*")
3061 (let ((fill-prefix (concat (make-string (current-column) ? )
3062 (match-string 0))))
3063 (fill-region (point-min) (point-max) justify))))
3064
3065(defun matlab-justify-line ()
3066 "Delete space on end of line and justify."
3067 (interactive)
3068 (save-excursion
3069 (end-of-line)
3070 (delete-horizontal-space)
3071 (justify-current-line)))
3072
3073(defun matlab-fill-paragraph (arg)
3074 "When in a comment, fill the current paragraph.
3075Paragraphs are always assumed to be in a comment.
3076ARG is passed to `fill-paragraph' and will justify the text."
3077 (interactive "P")
3078 (cond ((or (matlab-ltype-comm)
3079 (and (matlab-cursor-in-comment)
3080 (not (matlab-lattr-cont))))
3081 ;; We are in a comment, lets fill the paragraph with some
3082 ;; nice regular expressions.
3083 ;; Cell start/end markers of %% also separate paragraphs
3084 (let ((paragraph-separate "%%\\|%[a-zA-Z]\\|%[ \t]*$\\|[ \t]*$")
3085 (paragraph-start "%[a-zA-Z]\\|%[ \t]*$\\|[ \t]*$")
3086 (paragraph-ignore-fill-prefix nil)
3087 (start (save-excursion (matlab-beginning-of-command)
3088 (if (looking-at "%%")
3089 (progn (end-of-line)
3090 (forward-char 1)))
3091 (point)))
3092 (end (save-excursion (matlab-end-of-command)
3093 (point)))
3094 (fill-prefix nil))
3095 (matlab-set-comm-fill-prefix)
3096 (save-restriction
3097 ;; Ben North fixed to handle comment at the end of
3098 ;; a buffer.
3099 (narrow-to-region start (min (point-max) (+ end 1)))
3100 (fill-paragraph arg))))
3101 ((matlab-ltype-code)
3102 ;; Ok, lets get the outer bounds of this command, then
3103 ;; completely refill it using the smart line breaking code.
3104 (save-restriction
3105 (narrow-to-region (save-excursion
3106 (matlab-beginning-of-command)
3107 (beginning-of-line)
3108 (point))
3109 (save-excursion
3110 (matlab-end-of-command)
3111 (point)))
3112 ;; Remove all line breaks
3113 (goto-char (point-min))
3114 (while (and (re-search-forward "$" nil t)
3115 (not (eobp)))
3116 (delete-horizontal-space)
3117 ;; Blow away continuation marks
3118 (if (matlab-lattr-cont)
3119 (progn
3120 (goto-char (match-beginning 0))
3121 (forward-char 1)
3122 (delete-region (point) (matlab-point-at-eol))))
3123 ;; Zap the CR
3124 (if (not (eobp)) (delete-char 1))
3125 ;; Clean up whitespace
3126 (delete-horizontal-space)
3127 ;; Clean up trailing comments
3128 (if (and (looking-at "% *")
3129 (matlab-cursor-in-comment))
3130 (progn
3131 (delete-char 1)
3132 (delete-horizontal-space)))
3133 (insert " "))
3134 ;; Now fill till we are done
3135 (goto-char (point-max))
3136 (while (or (> (current-column) (+ fill-column matlab-fill-fudge))
3137 (> (current-column) matlab-fill-fudge-hard-maximum))
3138 (if (= (point)
3139 (progn
3140 (matlab-auto-fill)
3141 (point)))
3142 (error "Fill algorith failed!"))
3143 (if arg (save-excursion
3144 (forward-line -1)
3145 (matlab-justify-line))))
3146 (if arg (save-excursion
3147 (forward-line -1)
3148 (matlab-justify-line)))))
3149 (t
3150 (message "Paragraph Fill not supported in this context."))))
3151
3152;;; Semantic text insertion and management ====================================
3153
3154(defun matlab-find-recent-variable-list (prefix)
3155 "Return a list of most recent variables starting with PREFIX as a string.
3156Reverse searches for the following are done first:
3157 1) Assignment
3158 2) if|for|while|switch <var>
3159 3) global variables
3160 4) function arguments.
3161All elements are saved in a list, which is then uniqafied.
3162If NEXT is non-nil, then the next element from the saved list is used.
3163If the list is empty, then searches continue backwards through the code."
3164 (matlab-navigation-syntax
3165 (let* ((bounds (save-excursion
3166 (if (re-search-backward "^\\s-*function\\>" nil t)
3167 (match-beginning 0) (point-min))))
3168 (syms
3169 (append
3170 (save-excursion
3171 (let ((lst nil))
3172 (while (and
3173 (re-search-backward
3174 (concat "^\\s-*\\(" prefix "\\w+\\)\\s-*=")
3175 bounds t)
3176 (< (length lst) 10))
3177 (setq lst (cons (match-string 1) lst)))
3178 (nreverse lst)))
3179 (save-excursion
3180 (let ((lst nil))
3181 (while (and (re-search-backward
3182 (concat "\\<\\(" matlab-block-beg-pre-no-if
3183 "\\)\\s-+(?\\s-*\\(" prefix
3184 "\\w+\\)\\>")
3185 bounds t)
3186 (< (length lst) 10))
3187 (setq lst (cons (match-string 2) lst)))
3188 (nreverse lst)))
3189 (save-excursion
3190 (if (re-search-backward "^\\s-*global\\s-+" bounds t)
3191 (let ((lst nil) m e)
3192 (goto-char (match-end 0))
3193 (while (looking-at "\\(\\w+\\)\\([ \t]+\\|$\\)")
3194 (setq m (match-string 1)
3195 e (match-end 0))
3196 (if (equal 0 (string-match prefix m))
3197 (setq lst (cons m lst)))
3198 (goto-char e))
3199 (nreverse lst))))
3200 (save-excursion
3201 (if (and (re-search-backward "^\\s-*function\\>" bounds t)
3202 (re-search-forward "\\<\\(\\w+\\)("
3203 (matlab-point-at-eol) t))
3204 (let ((lst nil) m e)
3205 (while (looking-at "\\(\\w+\\)\\s-*[,)]\\s-*")
3206 (setq m (match-string 1)
3207 e (match-end 0))
3208 (if (equal 0 (string-match prefix m))
3209 (setq lst (cons m lst)))
3210 (goto-char e))
3211 (nreverse lst))))))
3212 (fl nil))
3213 (while syms
3214 (if (car syms) (setq fl (cons (car syms) fl)))
3215 (setq syms (cdr syms)))
3216 (matlab-uniquafy-list (nreverse fl)))))
3217
3218(defvar matlab-most-recent-variable-list nil
3219 "Maintained by `matlab-find-recent-variable'.")
3220
3221(defun matlab-find-recent-variable (prefix &optional next)
3222 "Return the most recently used variable starting with PREFIX as a string.
3223See `matlab-find-recent-variable-list' for details.
3224In NEXT is non-nil, than continue through the list of elements."
3225 (if next
3226 (let ((next (car matlab-most-recent-variable-list)))
3227 (setq matlab-most-recent-variable-list
3228 (cdr matlab-most-recent-variable-list))
3229 next)
3230 (let ((syms (matlab-find-recent-variable-list prefix))
3231 (first nil))
3232 (if (eq matlab-completion-technique 'complete)
3233 syms
3234 (setq first (car syms))
3235 (setq matlab-most-recent-variable-list (cdr syms))
3236 first))))
3237
3238(defun matlab-find-user-functions-list (prefix)
3239 "Return a list of user defined functions that match PREFIX."
3240 (matlab-navigation-syntax
3241 (let ((syms
3242 (append
3243 (save-excursion
3244 (goto-char (point-min))
3245 (let ((lst nil))
3246 (while (re-search-forward "^\\s-*function\\>" nil t)
3247 (if (re-search-forward
3248 (concat "\\(" prefix "\\w+\\)\\s-*\\($\\|(\\)")
3249 (matlab-point-at-eol) t)
3250 (setq lst (cons (match-string 1) lst))))
3251 (nreverse lst)))
3252 (let ((lst nil)
3253 (files (directory-files
3254 default-directory nil
3255 (concat "^" prefix
3256 "[a-zA-Z][a-zA-Z0-9_]+\\.m$"))))
3257 (while files
3258 (setq lst (cons (progn (string-match "\\.m" (car files))
3259 (substring (car files) 0
3260 (match-beginning 0)))
3261 lst)
3262 files (cdr files)))
3263 lst)))
3264 (fl nil))
3265 (while syms
3266 (if (car syms) (setq fl (cons (car syms) fl)))
3267 (setq syms (cdr syms)))
3268 (matlab-uniquafy-list (nreverse fl)))))
3269
3270(defvar matlab-user-function-list nil
3271 "Maintained by `matlab-find-user-functions'.")
3272
3273(defun matlab-find-user-functions (prefix &optional next)
3274 "Return a user function that match PREFIX and return it.
3275If optional argument NEXT is non-nil, then return the next found
3276object."
3277 (if next
3278 (let ((next (car matlab-user-function-list)))
3279 (setq matlab-user-function-list (cdr matlab-user-function-list))
3280 next)
3281 (let ((syms (matlab-find-user-functions-list prefix))
3282 (first nil))
3283 (if (eq matlab-completion-technique 'complete)
3284 syms
3285 (setq first (car syms))
3286 (setq matlab-user-function-list (cdr syms))
3287 first))))
3288
3289(defvar matlab-generic-list-placeholder nil
3290 "Maintained by `matalb-generic-list-expand'.
3291Holds sub-lists of symbols left to be expanded.")
3292
3293(defun matlab-generic-list-expand (list prefix &optional next)
3294 "Return an element from LIST that start with PREFIX.
3295If optional NEXT argument is non nil, then the next element in the
3296list is used. nil is returned if there are not matches."
3297 (if next
3298 (let ((next (car matlab-generic-list-placeholder)))
3299 (setq matlab-generic-list-placeholder
3300 (cdr matlab-generic-list-placeholder))
3301 next)
3302 (let ((re (concat "^" (regexp-quote prefix)))
3303 (first nil)
3304 (fl nil))
3305 (while list
3306 (if (string-match re (car list))
3307 (setq fl (cons (car list) fl)))
3308 (setq list (cdr list)))
3309 (setq fl (nreverse fl))
3310 (if (eq matlab-completion-technique 'complete)
3311 fl
3312 (setq first (car fl))
3313 (setq matlab-generic-list-placeholder (cdr fl))
3314 first))))
3315
3316(defun matlab-solo-completions (prefix &optional next)
3317 "Return PREFIX matching elements for solo symbols.
3318If NEXT then the next patch from the list is used."
3319 (matlab-generic-list-expand matlab-keywords-solo prefix next))
3320
3321(defun matlab-value-completions (prefix &optional next)
3322 "Return PREFIX matching elements for value symbols.
3323If NEXT then the next patch from the list is used."
3324 (matlab-generic-list-expand matlab-keywords-return prefix next))
3325
3326(defun matlab-boolean-completions (prefix &optional next)
3327 "Return PREFIX matching elements for boolean symbols.
3328If NEXT then the next patch from the list is used."
3329 (matlab-generic-list-expand matlab-keywords-boolean prefix next))
3330
3331(defun matlab-property-completions (prefix &optional next)
3332 "Return PREFIX matching elements for property names in strings.
3333If NEXT then the next property from the list is used."
3334 (let ((f (matlab-function-called-at-point))
3335 (lst matlab-property-lists)
3336 (foundlst nil)
3337 (expandto nil))
3338 ;; Look for this function. If it is a known function then we
3339 ;; can now use a subset of available properties!
3340 (while (and lst (not foundlst))
3341 (if (string= (car (car lst)) f)
3342 (setq foundlst (cdr (car lst))))
3343 (setq lst (cdr lst)))
3344 (if foundlst
3345 (setq foundlst (append foundlst matlab-core-properties))
3346 (setq foundlst matlab-all-known-properties))
3347 (setq expandto (matlab-generic-list-expand foundlst prefix next))
3348 ;; This looks to see if we have a singular completion. If so,
3349 ;; then return it, and also append the "'" to the end.
3350 (cond ((and (listp expandto) (= (length expandto) 1))
3351 (setq expandto (list (concat (car expandto) "'"))))
3352 ((stringp expandto)
3353 (setq expandto (concat expandto "'"))))
3354 expandto))
3355
3356(defvar matlab-last-prefix nil
3357 "Maintained by `matlab-complete-symbol'.
3358The prefix used for the first completion command.")
3359(defvar matlab-last-semantic nil
3360 "Maintained by `matlab-complete-symbol'.
3361The last type of semantic used while completing things.")
3362(defvar matlab-completion-search-state nil
3363 "List of searching things we will be doing.")
3364
3365(defun matlab-complete-symbol (&optional arg)
3366 "Complete a partially typed symbol in a MATLAB mode buffer.
3367If the previously entered command was also `matlab-complete-symbol'
3368then undo the last completion, and find a new one.
3369 The types of symbols tried are based on the semantics of the current
3370cursor position. There are two types of symbols. For example, if the
3371cursor is in an if statement, boolean style functions and symbols are
3372tried first. If the line is blank, then flow control, or high level
3373functions are tried first.
3374 The completion technique is controlled with `matlab-completion-technique'
3375It defaults to incremental completion described above. If a
3376completion list is preferred, then change this to 'complete. If you
3377just want a completion list once, then use the universal argument ARG
3378to change it temporarily."
3379 (interactive "P")
3380 (matlab-navigation-syntax
3381 (let* ((prefix (if (and (not (eq last-command 'matlab-complete-symbol))
3382 (member (preceding-char) '(? ?\t ?\n ?, ?\( ?\[ ?\')))
3383 ""
3384 (buffer-substring-no-properties
3385 (save-excursion (forward-word -1) (point))
3386 (point))))
3387 (sem (matlab-lattr-semantics prefix))
3388 (matlab-completion-technique
3389 (if arg (cond ((eq matlab-completion-technique 'complete)
3390 'increment)
3391 (t 'complete))
3392 matlab-completion-technique)))
3393 (if (not (eq last-command 'matlab-complete-symbol))
3394 (setq matlab-last-prefix prefix
3395 matlab-last-semantic sem
3396 matlab-completion-search-state
3397 (cond ((eq sem 'solo)
3398 '(matlab-solo-completions
3399 matlab-find-user-functions
3400 matlab-find-recent-variable))
3401 ((eq sem 'boolean)
3402 '(matlab-find-recent-variable
3403 matlab-boolean-completions
3404 matlab-find-user-functions
3405 matlab-value-completions))
3406 ((eq sem 'value)
3407 '(matlab-find-recent-variable
3408 matlab-find-user-functions
3409 matlab-value-completions
3410 matlab-boolean-completions))
3411 ((eq sem 'property)
3412 '(matlab-property-completions
3413 matlab-find-user-functions
3414 matlab-find-recent-variable
3415 matlab-value-completions))
3416 (t '(matlab-find-recent-variable
3417 matlab-find-user-functions
3418 matlab-value-completions
3419 matlab-boolean-completions)))))
3420 (cond
3421 ((eq matlab-completion-technique 'increment)
3422 (let ((r nil) (donext (eq last-command 'matlab-complete-symbol)))
3423 (while (and (not r) matlab-completion-search-state)
3424 (message "Expand with %S" (car matlab-completion-search-state))
3425 (setq r (funcall (car matlab-completion-search-state)
3426 matlab-last-prefix donext))
3427 (if (not r) (setq matlab-completion-search-state
3428 (cdr matlab-completion-search-state)
3429 donext nil)))
3430 (delete-region (point) (progn (forward-char (- (length prefix)))
3431 (point)))
3432 (if r
3433 (insert r)
3434 (insert matlab-last-prefix)
3435 (message "No completions."))))
3436 ((eq matlab-completion-technique 'complete)
3437 (let ((allsyms (apply 'append
3438 (mapcar (lambda (f) (funcall f prefix))
3439 matlab-completion-search-state))))
3440 (cond ((null allsyms)
3441 (message "No completions.")
3442 (ding))
3443 ((= (length allsyms) 1)
3444 (delete-region (point) (progn
3445 (forward-char (- (length prefix)))
3446 (point)))
3447 (insert (car allsyms)))
3448 ((= (length allsyms) 0)
3449 (message "No completions."))
3450 (t
3451 (let* ((al (mapcar (lambda (a) (list a)) allsyms))
3452 (c (try-completion prefix al)))
3453 ;; This completion stuff lets us expand as much as is
3454 ;; available to us. When the completion is the prefix
3455 ;; then we want to display all the strings we've
3456 ;; encountered.
3457 (if (and (stringp c) (not (string= prefix c)))
3458 (progn
3459 (delete-region
3460 (point)
3461 (progn (forward-char (- (length prefix)))
3462 (point)))
3463 (insert c))
3464 ;; `display-completion-list' does all the complex
3465 ;; ui work for us.
3466 (with-output-to-temp-buffer "*Completions*"
3467 (display-completion-list
3468 (matlab-uniquafy-list allsyms)))))))))))))
3469
3470(defun matlab-insert-end-block (&optional reindent)
3471 "Insert and END block based on the current syntax.
3472Optional argument REINDENT indicates if the specified block should be re-indented."
3473 (interactive "P")
3474 (if (not (matlab-ltype-empty)) (progn (end-of-line) (insert "\n")))
3475 (let ((valid t) (begin nil))
3476 (save-excursion
3477 (condition-case nil
3478 (progn
3479 (matlab-backward-sexp t)
3480 (setq begin (point)
3481 valid (buffer-substring-no-properties
3482 (point) (save-excursion
3483 (re-search-forward "[\n,;.]" nil t)
3484 (point)))))
3485 (error (setq valid nil))))
3486 (if (not valid)
3487 (error "No block to end")
3488 (insert "end")
3489 (if (stringp valid) (insert " % " valid))
3490 (matlab-indent-line)
3491 (if reindent (indent-region begin (point) nil)))))
3492
3493(tempo-define-template
3494 "matlab-for"
3495 '("for " p "=" p "," > n>
3496 r> &
3497 "end" > %)
3498 "for"
3499 "Insert a MATLAB for statement"
3500 'matlab-tempo-tags
3501 )
3502
3503(tempo-define-template
3504 "matlab-while"
3505 '("while (" p ")," > n>
3506 r> &
3507 "end" > %)
3508 "while"
3509 "Insert a MATLAB while statement"
3510 'matlab-tempo-tags
3511 )
3512
3513(tempo-define-template
3514 "matlab-if"
3515 '("if " p > n
3516 r>
3517 "end" > n)
3518 "if"
3519 "Insert a MATLAB if statement"
3520 'matlab-tempo-tags
3521 )
3522
3523(tempo-define-template
3524 "matlab-if-else"
3525 '("if " p > n
3526 r>
3527 "else" > n
3528 "end" > n)
3529 "if"
3530 "Insert a MATLAB if statement"
3531 'matlab-tempo-tags
3532 )
3533
3534(tempo-define-template
3535 "matlab-try"
3536 '("try " > n
3537 r>
3538 "catch" > n
3539 p > n
3540 "end" > n)
3541 "try"
3542 "Insert a MATLAB try catch statement"
3543 'matlab-tempo-tags
3544 )
3545
3546(tempo-define-template
3547 "matlab-switch"
3548 '("switch " p > n
3549 "otherwise" > n
3550 r>
3551 "end" > n)
3552 "switch"
3553 "Insert a MATLAB switch statement with region in the otherwise clause."
3554 'matlab-tempo-tags)
3555
3556(defun matlab-insert-next-case ()
3557 "Insert a case statement inside this switch statement."
3558 (interactive)
3559 ;; First, make sure we are where we think we are.
3560 (let ((valid t))
3561 (save-excursion
3562 (condition-case nil
3563 (progn
3564 (matlab-backward-sexp t)
3565 (setq valid (looking-at "switch")))
3566 (error (setq valid nil))))
3567 (if (not valid)
3568 (error "Not in a switch statement")))
3569 (if (not (matlab-ltype-empty)) (progn (end-of-line) (insert "\n")))
3570 (indent-to 0)
3571 (insert "case ")
3572 (matlab-indent-line))
3573
3574(tempo-define-template
3575 "matlab-function"
3576 '("function "
3577 (P "output argument(s): " output t)
3578 ;; Insert brackets only if there is more than one output argument
3579 (if (string-match "," (tempo-lookup-named 'output))
3580 '(l "[" (s output) "]")
3581 '(l (s output)))
3582 ;; Insert equal sign only if there is output argument(s)
3583 (if (= 0 (length (tempo-lookup-named 'output))) nil
3584 " = ")
3585 ;; The name of a function, as defined in the first line, should
3586 ;; be the same as the name of the file without .m extension
3587 (if (= 1 (count-lines 1 (point)))
3588 (tempo-save-named
3589 'fname
3590 (file-name-nondirectory (file-name-sans-extension
3591 (buffer-file-name))))
3592 '(l (P "function name: " fname t)))
3593 (tempo-lookup-named 'fname)
3594 "(" (P "input argument(s): ") ")" n
3595 "% " (upcase (tempo-lookup-named 'fname)) " - " (P "H1 line: ") n
3596 "% " p n
3597 (if matlab-functions-have-end
3598 '(l "end" n)))
3599 "function"
3600 "Insert a MATLAB function statement"
3601 'matlab-tempo-tags
3602 )
3603
3604(defun matlab-stringify-region (begin end)
3605 "Put MATLAB 's around region, and quote all quotes in the string.
3606Stringification allows you to type in normal MATLAB code, mark it, and
3607then turn it into a MATLAB string that will output exactly what's in
3608the region. BEGIN and END mark the region to be stringified."
3609 (interactive "r")
3610 (save-excursion
3611 (goto-char begin)
3612 (if (re-search-forward "\n" end t)
3613 (error
3614 "You may only stringify regions that encompass less than one line"))
3615 (let ((m (make-marker)))
3616 (move-marker m end)
3617 (goto-char begin)
3618 (insert "'")
3619 (while (re-search-forward "'" m t)
3620 (insert "'"))
3621 (goto-char m)
3622 (insert "'"))))
3623
3624(defun matlab-ispell-strings-region (begin end)
3625 "Spell check valid strings in region with Ispell.
3626Argument BEGIN and END mark the region boundary."
3627 (interactive "r")
3628 (require 'ispell)
3629 (save-excursion
3630 (goto-char begin)
3631 ;; Here we use the font lock function for finding strings.
3632 ;; Its cheap, fast, and accurate.
3633 (while (and (matlab-font-lock-string-match-normal end)
3634 (ispell-region (match-beginning 2) (match-end 2))))))
3635
3636(defun matlab-ispell-strings ()
3637 "Spell check valid strings in the current buffer with Ispell.
3638Calls `matlab-ispell-strings-region'"
3639 (interactive)
3640 (matlab-ispell-strings-region (point-min) (point-max)))
3641
3642(defun matlab-ispell-comments (&optional arg)
3643 "Spell check comments in the current buffer with Ispell.
3644Optional ARG means to only check the current comment."
3645 (interactive "P")
3646 (let ((beg (point-min))
3647 (end (point-max)))
3648 (if (and arg (matlab-ltype-comm))
3649 (setq beg (save-excursion (matlab-beginning-of-command) (point))
3650 end (save-excursion (matlab-end-of-command) (point))))
3651 (save-excursion
3652 (goto-char beg)
3653 (beginning-of-line)
3654 (while (and (matlab-font-lock-comment-match end)
3655 (ispell-region (match-beginning 1) (match-end 1)))))))
3656
3657(defun matlab-generate-latex ()
3658 "Convert a MATLAB M file into a Latex document for printing.
3659Author: Uwe Brauer oub@eucmos.sim.ucm.es
3660Created: 14 Feb 2002"
3661 (interactive "*")
3662 (save-restriction
3663 (save-excursion
3664 (goto-char (point-min))
3665 (insert "\\documentclass[12pt]{report}\n
3666\\usepackage{listings}
3667\\lstloadlanguages{Matlab}
3668\\lstset{language=Matlab,keywordstyle=\\bfseries,labelstep=1,escapechar=\\#}
3669\\begin{document}
3670\\begin{lstlisting}{}")
3671 (newline)
3672 (goto-char (point-max))
3673 (insert "\n\\end{lstlisting}\n\\end{document}")
3674 (widen)))
3675 (font-lock-mode nil)
3676 (LaTeX-mode)
3677 (font-lock-mode nil))
3678
3679
3680;;; Block highlighting ========================================================
3681
3682(defvar matlab-block-highlighter-timer nil
3683 "The timer representing the block highlighter.")
3684
3685(defun matlab-enable-block-highlighting (&optional arg)
3686 "Start or stop the block highlighter.
3687Optional ARG is 1 to force enable, and -1 to disable.
3688If ARG is nil, then highlighting is toggled."
3689 (interactive "P")
3690 (if (not (fboundp 'matlab-run-with-idle-timer))
3691 (setq matlab-highlight-block-match-flag nil))
3692 ;; Only do it if it's enabled.
3693 (if (not matlab-highlight-block-match-flag)
3694 nil
3695 ;; Use post command idle hook as a local hook to dissuade too much
3696 ;; cpu time while doing other things.
3697 ;;(make-local-hook 'post-command-hook)
3698 (if (not arg)
3699 (setq arg
3700 (if (member 'matlab-start-block-highlight-timer
3701 post-command-hook)
3702 -1 1)))
3703 (if (> arg 0)
3704 (add-hook 'post-command-hook 'matlab-start-block-highlight-timer)
3705 (remove-hook 'post-command-hook 'matlab-start-block-highlight-timer))))
3706
3707(defvar matlab-block-highlight-overlay nil
3708 "The last highlighted overlay.")
3709(make-variable-buffer-local 'matlab-block-highlight-overlay)
3710
3711(defvar matlab-block-highlight-timer nil
3712 "Last started timer.")
3713(make-variable-buffer-local 'matlab-block-highlight-timer)
3714
3715(defun matlab-start-block-highlight-timer ()
3716 "Set up a one-shot timer if we are in MATLAB mode."
3717 (if (eq major-mode 'matlab-mode)
3718 (progn
3719 (if matlab-block-highlight-overlay
3720 (unwind-protect
3721 (matlab-delete-overlay matlab-block-highlight-overlay)
3722 (setq matlab-block-highlight-overlay nil)))
3723 (if matlab-block-highlight-timer
3724 (unwind-protect
3725 (matlab-cancel-timer matlab-block-highlight-timer)
3726 (setq matlab-block-highlight-timer nil)))
3727 (setq matlab-block-highlight-timer
3728 (matlab-run-with-idle-timer
3729 1 nil 'matlab-highlight-block-match
3730 (current-buffer))))))
3731
3732(defun matlab-highlight-block-match (&optional buff-when-launched)
3733 "Highlight a matching block if available.
3734BUFF-WHEN-LAUNCHED is the buffer that was active when the timer was set."
3735 (setq matlab-block-highlight-timer nil)
3736 (if (null buff-when-launched)
3737 ;; We were passed a null. This indicates an old version of XEmacs
3738 ;; so just turn the feature off
3739 (setq matlab-highlight-block-match-flag nil)
3740 ;; Only do neat stuff in the same buffer as the one we were
3741 ;; initialized from.
3742 (when (and buff-when-launched
3743 (eq buff-when-launched (current-buffer)))
3744 (let ((inhibit-quit nil) ;turn on G-g
3745 (matlab-scan-on-screen-only t))
3746 (if matlab-show-periodic-code-details-flag
3747 (matlab-show-line-info))
3748 (if (not (matlab-cursor-in-string-or-comment))
3749 (save-excursion
3750 (if (or (bolp)
3751 (looking-at "\\s-")
3752 (save-excursion (forward-char -1) (looking-at "\\s-")))
3753 nil
3754 (forward-word -1))
3755 (if (and (looking-at (concat (matlab-block-beg-re) "\\>"))
3756 (not (looking-at "function")))
3757 (progn
3758 ;; We scan forward...
3759 (matlab-forward-sexp)
3760 (backward-word 1)
3761 (if (not (looking-at matlab-block-end-pre-if))
3762 nil ;(message "Unterminated block, or end off screen.")
3763 (setq matlab-block-highlight-overlay
3764 (matlab-make-overlay (point)
3765 (progn (forward-word 1)
3766 (point))
3767 (current-buffer)))
3768 (matlab-overlay-put matlab-block-highlight-overlay
3769 'face 'matlab-region-face)))
3770 (if (and (looking-at (concat (matlab-block-end-pre) "\\>"))
3771 (not (looking-at "function"))
3772 (matlab-valid-end-construct-p))
3773 (progn
3774 ;; We scan backward
3775 (forward-word 1)
3776 (condition-case nil
3777 (progn
3778 (matlab-backward-sexp)
3779 (if (not (looking-at (matlab-block-beg-re)))
3780 nil ;(message "Unstarted block at cursor.")
3781 (setq matlab-block-highlight-overlay
3782 (matlab-make-overlay (point)
3783 (progn (forward-word 1)
3784 (point))
3785 (current-buffer)))
3786 (matlab-overlay-put matlab-block-highlight-overlay
3787 'face 'matlab-region-face)))
3788 (error (message "Unstarted block at cursor."))))
3789 ;; do nothing
3790 ))))))))
3791
3792
3793;;; M Block Folding with hideshow =============================================
3794
3795(defun matlab-hideshow-forward-sexp-func (arg)
3796 "Move forward one sexp for hideshow.
3797Argument ARG specifies the number of blocks to move forward."
3798 (beginning-of-line)
3799 (matlab-forward-sexp arg)
3800 )
3801
3802(defun matlab-hideshow-adjust-beg-func (arg)
3803 "Adjust the beginning of a hideshow block.
3804Argument ARG to make it happy."
3805 (end-of-line)
3806 (point)
3807 )
3808
3809;; Use this to enable hideshow in MATLAB.
3810;; It has not been tested by me enough.
3811
3812;; REMOVE PUSHNEW FROM THIS LINE
3813;;(pushnew (list 'matlab-mode
3814;; (matlab-block-beg-pre)
3815;; (matlab-block-end-pre)
3816;; "%"
3817;; 'matlab-hideshow-forward-sexp-func
3818;; 'matlab-hideshow-adjust-beg-func
3819;; )
3820;; hs-special-modes-alist :test 'equal)
3821
3822
3823;;; M Code verification & Auto-fix ============================================
3824
3825(defun matlab-mode-verify-fix-file-fn ()
3826 "Verify the current buffer from `write-contents-hooks'."
3827 (if matlab-verify-on-save-flag
3828 (matlab-mode-verify-fix-file (> (point-max)
3829 matlab-block-verify-max-buffer-size)))
3830 ;; Always return nil.
3831 nil)
3832
3833(defun matlab-mode-verify-fix-file (&optional fast)
3834 "Verify the current buffer satisfies all M things that might be useful.
3835We will merely loop across a list of verifiers/fixers in
3836`matlab-mode-verify-fix-functions'.
3837If optional FAST is non-nil, do not perform usually lengthy checks."
3838 (interactive)
3839 (let ((p (point))
3840 (l matlab-mode-verify-fix-functions))
3841 (while l
3842 (funcall (car l) fast)
3843 (setq l (cdr l)))
3844 (goto-char p))
3845 (if (interactive-p)
3846 (message "Done.")))
3847
3848(defun matlab-toggle-show-mlint-warnings ()
3849 "Toggle `matlab-show-mlint-warnings'."
3850 (interactive)
3851 (setq matlab-show-mlint-warnings (not matlab-show-mlint-warnings))
3852 (if matlab-highlight-cross-function-variables
3853 (if matlab-show-mlint-warnings
3854 (mlint-buffer) ; became true, recompute mlint info
3855 (mlint-clear-warnings))) ; became false, just remove hilighting
3856 ;; change mlint mode altogether
3857 (mlint-minor-mode
3858 (if (or matlab-highlight-cross-function-variables
3859 matlab-show-mlint-warnings)
3860 1 -1)))
3861
3862(defun matlab-toggle-highlight-cross-function-variables ()
3863 "Toggle `matlab-highlight-cross-function-variables'."
3864 (interactive)
3865 (setq matlab-highlight-cross-function-variables
3866 (not matlab-highlight-cross-function-variables))
3867 (if matlab-show-mlint-warnings
3868 (if matlab-highlight-cross-function-variables
3869 (mlint-buffer) ; became true, recompute mlint info
3870 ; became false, just remove hilighting ...
3871 (mlint-clear-cross-function-variable-highlighting)))
3872 (mlint-minor-mode
3873 (if (or matlab-highlight-cross-function-variables
3874 matlab-show-mlint-warnings)
3875 1 -1))) ; change mlint mode altogether
3876
3877;;
3878;; Add more auto verify/fix functions here!
3879;;
3880(defun matlab-mode-vf-functionname (&optional fast)
3881 "Verify/Fix the function name of this file.
3882Optional argument FAST is ignored."
3883 (matlab-navigation-syntax
3884 (goto-char (point-min))
3885 (while (and (or (matlab-ltype-empty) (matlab-ltype-comm))
3886 (/= (matlab-point-at-eol) (point-max)))
3887 (forward-line 1))
3888 (let ((func nil)
3889 (bn (file-name-sans-extension
3890 (file-name-nondirectory (buffer-file-name)))))
3891 (if (looking-at (matlab-match-function-re))
3892 ;; The expression above creates too many numeric matches
3893 ;; to apply a known one to our function. We cheat by knowing that
3894 ;; match-end 0 is at the end of the function name. We can then go
3895 ;; backwards, and get the extents we need. Navigation syntax
3896 ;; lets us know that backward-word really covers the word.
3897 (let ((end (match-end 0))
3898 (begin (progn (goto-char (match-end 0))
3899 (forward-word -1)
3900 (point))))
3901 (setq func (buffer-substring begin end))
3902 (if (not (string= func bn))
3903 (if (not (matlab-mode-highlight-ask
3904 begin end
3905 "Function and file names are different. Fix?"))
3906 nil
3907 (goto-char begin)
3908 (delete-region begin end)
3909 (insert bn))))))))
3910
3911(defun matlab-mode-vf-block-matches-forward (&optional fast)
3912 "Verify/Fix unterminated (or un-ended) blocks.
3913This only checks block regions like if/end.
3914Optional argument FAST causes this check to be skipped."
3915 (goto-char (point-min))
3916 (let ((go t)
3917 (expr (concat "\\<\\(" (matlab-block-beg-pre) "\\)\\>")))
3918 (matlab-navigation-syntax
3919 (while (and (not fast) go (re-search-forward expr nil t))
3920 (forward-word -1) ;back over the special word
3921 (let ((s (point)))
3922 (condition-case nil
3923 (if (and (not (matlab-cursor-in-string-or-comment))
3924 (not (looking-at "function")))
3925 (progn
3926 (matlab-forward-sexp)
3927 (forward-word -1)
3928 (if (not (looking-at
3929 (concat matlab-block-end-pre-no-if "\\>")))
3930 (setq go nil)))
3931 (forward-word 1))
3932 (error (setq go nil)))
3933 (if (and (not go) (goto-char s)
3934 (not (matlab-mode-highlight-ask
3935 (point) (save-excursion (forward-word 1) (point))
3936 "Unterminated block. Continue anyway?")))
3937 (error "Unterminated Block found!")))
3938 (message "Block-check: %d%%" (/ (/ (* 100 (point)) (point-max)) 2))))))
3939
3940(defun matlab-mode-vf-block-matches-backward (&optional fast)
3941 "Verify/fix unstarted (or dangling end) blocks.
3942Optional argument FAST causes this check to be skipped."
3943 (goto-char (point-max))
3944 (let ((go t) (expr (concat "\\<\\(" (matlab-block-end-no-function-re)
3945 "\\)\\>")))
3946 (matlab-navigation-syntax
3947 (while (and (not fast) go (re-search-backward expr nil t))
3948 (forward-word 1)
3949 (let ((s (point)))
3950 (condition-case nil
3951 (if (and (not (matlab-cursor-in-string-or-comment))
3952 (matlab-valid-end-construct-p))
3953 (matlab-backward-sexp)
3954 (backward-word 1))
3955 (error (setq go nil)))
3956 (if (and (not go) (goto-char s)
3957 (not (matlab-mode-highlight-ask
3958 (point) (save-excursion (backward-word 1) (point))
3959 "Unstarted block. Continue anyway?")))
3960 (error "Unstarted Block found!")))
3961 (message "Block-check: %d%%"
3962 (+ (/ (/ (* 100 (- (point-max) (point))) (point-max)) 2) 50))))))
3963
3964;;; Utility for verify/fix actions if you need to highlight
3965;; a section of the buffer for the user's approval.
3966(defun matlab-mode-highlight-ask (begin end prompt)
3967 "Highlight from BEGIN to END while asking PROMPT as a yes-no question."
3968 (let ((mo (matlab-make-overlay begin end (current-buffer)))
3969 (ans nil))
3970 (condition-case nil
3971 (progn
3972 (matlab-overlay-put mo 'face 'matlab-region-face)
3973 (setq ans (y-or-n-p prompt))
3974 (matlab-delete-overlay mo))
3975 (quit (matlab-delete-overlay mo) (error "Quit")))
3976 ans))
3977
3978;;; Quiesce an M file to remove accidental display of ANS during a run.
3979;; Useful if you have random outputs and you don't know where they are from,
3980;; or before compiling to standalone where some functions now have outputs
3981;; that did not have outputs earlier.
3982;;
3983;; You probably don't want this as a default verify function
3984(defvar matlab-quiesce-nosemi-regexp "\\s-*\\(function\\|parfor\\|for\\|spmd\\|while\\|try\\|catch\\|\
3985switch\\|otherwise\\|case\\|break\\|if\\|else\\|end\\|return\\|disp\\|\
3986$\\|%\\)"
3987 "Regular expression used to detect if a semicolon is needed at the end of a line.")
3988
3989(defun matlab-mode-vf-quiesce-buffer (&optional fast)
3990 "Find all commands that do not end in ;, and add one.
3991This has the effect of removing any extraneous output that may not be
3992desired. Optional argument FAST is not used."
3993 (interactive)
3994 (save-excursion
3995 (push-mark)
3996 (goto-char (point-min))
3997 (let ((msgpos 0) (dir .2))
3998 (while (not (save-excursion (end-of-line) (eobp)))
3999 (message (aref [ "Scanning o...." "Scanning .o..." "Scanning ..o.."
4000 "Scanning ...o." "Scanning ....o" ] (floor msgpos)))
4001 (setq msgpos (+ msgpos dir))
4002 (if (or (> msgpos 5) (< msgpos 0)) (setq dir (- dir)
4003 msgpos (+ (* 2 dir) msgpos)))
4004 (matlab-end-of-command (point))
4005 (if (matlab-cursor-in-comment)
4006 (progn
4007 (matlab-comment-on-line)
4008 (skip-chars-backward " \t")))
4009 (if (and (not (= (preceding-char) ?\;))
4010 (not (matlab-cursor-in-string t))
4011 (not (save-excursion
4012 (beginning-of-line)
4013 (looking-at matlab-quiesce-nosemi-regexp))))
4014 (let ((p (point)))
4015 (skip-chars-backward " \t")
4016 (if (/= p (point))
4017 (progn
4018 (delete-region p (point))
4019 (forward-line -1))
4020 (if (matlab-mode-highlight-ask (point) (+ 1 (point))
4021 "Add Semi colon here? ")
4022 (insert ";")))))
4023 (forward-line 1))))
4024 (message "Scanning .... done"))
4025
4026
4027
4028;;; V19 stuff =================================================================
4029
4030(defvar matlab-mode-menu-keymap nil
4031 "Keymap used in MATLAB mode to provide a menu.")
4032
4033(defun matlab-frame-init ()
4034 "Initialize Emacs menu system."
4035 (interactive)
4036 ;; make a menu keymap
4037 (easy-menu-define
4038 matlab-mode-menu
4039 matlab-mode-map
4040 "MATLAB menu"
4041 '("MATLAB"
4042 ["Start MATLAB" matlab-shell
4043 :active (not (or (matlab-with-emacs-link) (matlab-shell-active-p)))
4044 :visible (not (matlab-shell-active-p)) ]
4045 ["Switch to MATLAB" matlab-shell
4046 :active (and (not (matlab-with-emacs-link)) (matlab-shell-active-p))
4047 :visible (matlab-shell-active-p) ]
4048 ["Save and go" matlab-shell-save-and-go t]
4049 ["Run Region" matlab-shell-run-region t]
4050 ["Run Cell" matlab-shell-run-cell t]
4051 ["Version" matlab-show-version t]
4052 "----"
4053 ["Find M file" matlab-find-file-on-path t]
4054 ["Show M-Lint Warnings" matlab-toggle-show-mlint-warnings
4055 :active (and (locate-library "mlint") (fboundp 'mlint-minor-mode))
4056 :style toggle :selected matlab-show-mlint-warnings
4057 ]
4058 ("Auto Fix"
4059 ["Verify/Fix source" matlab-mode-verify-fix-file t]
4060 ["Spell check strings" matlab-ispell-strings t]
4061 ["Spell check comments" matlab-ispell-comments t]
4062 ["Quiesce source" matlab-mode-vf-quiesce-buffer t]
4063 )
4064 ("Navigate"
4065 ["Beginning of Command" matlab-beginning-of-command t]
4066 ["End of Command" matlab-end-of-command t]
4067 ["Forward Block" matlab-forward-sexp t]
4068 ["Backward Block" matlab-backward-sexp t]
4069 ["Beginning of Function" matlab-beginning-of-defun t]
4070 ["End of Function" matlab-end-of-defun t])
4071 ("Format"
4072 ["Justify Line" matlab-justify-line t]
4073 ["Fill Region" matlab-fill-region t]
4074 ["Fill Comment Paragraph" matlab-fill-paragraph
4075 (save-excursion (matlab-comment-on-line))]
4076 ["Join Comment" matlab-join-comment-lines
4077 (save-excursion (matlab-comment-on-line))]
4078 ["Comment Region" matlab-comment-region t]
4079 ["Uncomment Region" matlab-uncomment-region t]
4080 ["Indent Synactic Block" matlab-indent-sexp])
4081 ("Insert"
4082 ["Complete Symbol" matlab-complete-symbol t]
4083 ["Comment" matlab-comment t]
4084 ["if end" tempo-template-matlab-if t]
4085 ["if else end" tempo-template-matlab-if-else t]
4086 ["for end" tempo-template-matlab-for t]
4087 ["switch otherwise end" tempo-template-matlab-switch t]
4088 ["Next case" matlab-insert-next-case t]
4089 ["try catch end" tempo-template-matlab-try t]
4090 ["while end" tempo-template-matlab-while t]
4091 ["End of block" matlab-insert-end-block t]
4092 ["Function" tempo-template-matlab-function t]
4093 ["Stringify Region" matlab-stringify-region t]
4094 )
4095 ("Customize"
4096; ["Auto Fill Counts Elipsis"
4097; (lambda () (setq matlab-fill-count-ellipsis-flag
4098; (not matlab-fill-count-ellipsis-flag)))
4099; :style toggle :selected 'matlab-fill-count-ellipsis-flag]
4100 ["Indent Function Body"
4101 (setq matlab-indent-function-body (not (matlab-indent-function-body-p)))
4102 :style toggle :selected matlab-indent-function-body]
4103 ["Functions Have end"
4104 matlab-toggle-functions-have-end
4105 :style toggle :selected matlab-functions-have-end]
4106 ["Verify File on Save"
4107 (setq matlab-verify-on-save-flag (not matlab-verify-on-save-flag))
4108 :style toggle :selected matlab-verify-on-save-flag]
4109 ["Auto Fill does Code"
4110 (setq matlab-fill-code (not matlab-fill-code))
4111 :style toggle :selected matlab-fill-code ]
4112 ["Periodic Code Details"
4113 (setq matlab-show-periodic-code-details-flag
4114 (not matlab-show-periodic-code-details-flag))
4115 :style toggle :selected matlab-show-periodic-code-details-flag ]
4116 ["Highlight Matching Blocks"
4117 (matlab-enable-block-highlighting)
4118 :style toggle :selected (member 'matlab-start-block-highlight-timer
4119 post-command-hook) ]
4120 ["Highlight Cross-Function Variables"
4121 matlab-toggle-highlight-cross-function-variables
4122 :active (locate-library "mlint")
4123 :style toggle :selected matlab-highlight-cross-function-variables
4124 ]
4125 ["Add Needed Semicolon on RET"
4126 (setq matlab-return-add-semicolon (not matlab-return-add-semicolon))
4127 :style toggle :selected matlab-return-add-semicolon
4128 ]
4129 ["Customize" (customize-group 'matlab)
4130 (and (featurep 'custom) (fboundp 'custom-declare-variable))
4131 ]
4132 )
4133 "----"
4134 ["Run M Command" matlab-shell-run-command (matlab-shell-active-p)]
4135 ["Describe Command" matlab-shell-describe-command (matlab-shell-active-p)]
4136 ["Describe Variable" matlab-shell-describe-variable (matlab-shell-active-p)]
4137 ["Command Apropos" matlab-shell-apropos (matlab-shell-active-p)]
4138 ["Topic Browser" matlab-shell-topic-browser (matlab-shell-active-p)]
4139 ))
4140 (easy-menu-add matlab-mode-menu matlab-mode-map))
4141
4142;;; MATLAB shell =============================================================
4143
4144(defgroup matlab-shell nil
4145 "MATLAB shell mode."
4146 :prefix "matlab-shell-"
4147 :group 'matlab)
4148
4149(defcustom matlab-shell-command "matlab"
4150 "*The name of the command to be run which will start the MATLAB process."
4151 :group 'matlab-shell
4152 :type 'string)
4153
4154(defcustom matlab-shell-command-switches '("-nodesktop")
4155 "*Command line parameters run with `matlab-shell-command'.
4156Command switches are a list of strings. Each entry is one switch."
4157 :group 'matlab-shell
4158 :type '(list :tag "Switch: "))
4159
4160(defcustom matlab-shell-echoes t
4161 "*If `matlab-shell-command' echoes input."
4162 :group 'matlab-shell
4163 :type 'boolean)
4164
4165(defvar matlab-shell-running-matlab-version nil
4166 "The version of MATLAB running in the current `matlab-shell' buffer.")
4167(defvar matlab-shell-running-matlab-release nil
4168 "The release of MATLAB running in the curbrent `matlab-shell' buffer.")
4169(defvar matlab-shell-use-emacs-toolbox
4170 ;; matlab may not be on path. (Name change, explicit load, etc)
4171 (let* ((mlfile (locate-library "matlab"))
4172 (dir (expand-file-name "toolbox/emacsinit.m"
4173 (file-name-directory (or mlfile "")))))
4174 (and mlfile (file-exists-p dir)))
4175 "Add the `matlab-shell' MATLAB toolbox to the MATLAB path on startup.")
4176(defvar matlab-shell-emacsclient-command "emacsclient -n"
4177 "The command to use as an external editor for MATLAB.
4178Using emacsclient allows the currently running Emacs to also be the
4179external editor for MATLAB.")
4180
4181(defcustom matlab-shell-history-file "~/.matlab/%s/history.m"
4182 "*Location of the history file.
4183A %s is replaced with the MATLAB version release number, such as R12.
4184This file is read to initialize the comint input ring.")
4185
4186(defcustom matlab-shell-input-ring-size 32
4187 "*Number of history elements to keep."
4188 :group 'matlab-shell
4189 :type 'integer)
4190
4191(defcustom matlab-shell-enable-gud-flag t
4192 "*Non-nil means to use GUD mode when running the MATLAB shell."
4193 :group 'matlab-shell
4194 :type 'boolean)
4195
4196(defcustom matlab-shell-mode-hook nil
4197 "*List of functions to call on entry to MATLAB shell mode."
4198 :group 'matlab-shell
4199 :type 'hook)
4200
4201(defcustom matlab-shell-ask-MATLAB-for-completions t
4202 "When Non-nil, ask MATLAB for a completion list.
4203When nil, just complete file names. (The original behavior.)
4204At this time, MATLAB based completion can be slow if there are
4205a lot of possible answers."
4206 :group 'matlab-shell
4207 :type 'boolean)
4208
4209(defvar matlab-shell-buffer-name "MATLAB"
4210 "Name used to create `matlab-shell' mode buffers.
4211This name will have *'s surrounding it.")
4212
4213(defun matlab-shell-active-p ()
4214 "Return t if the MATLAB shell is active."
4215 (if (get-buffer (concat "*" matlab-shell-buffer-name "*"))
4216 (save-excursion
4217 (set-buffer (concat "*" matlab-shell-buffer-name "*"))
4218 (if (comint-check-proc (current-buffer))
4219 (current-buffer)))))
4220
4221(defvar matlab-shell-mode-map ()
4222 "Keymap used in `matlab-shell-mode'.")
4223
4224(defvar matlab-shell-font-lock-keywords-1
4225 (append matlab-font-lock-keywords matlab-shell-font-lock-keywords)
4226 "Keyword symbol used for font-lock mode.")
4227
4228(defvar matlab-shell-font-lock-keywords-2
4229 (append matlab-shell-font-lock-keywords-1 matlab-gaudy-font-lock-keywords)
4230 "Keyword symbol used for gaudy font-lock symbols.")
4231
4232(defvar matlab-shell-font-lock-keywords-3
4233 (append matlab-shell-font-lock-keywords-2
4234 matlab-really-gaudy-font-lock-keywords)
4235 "Keyword symbol used for really gaudy font-lock symbols.")
4236
4237(defvar matlab-prompt-seen nil
4238 "Track visibility of MATLAB prompt in MATLAB Shell.")
4239
4240(eval-when-compile (require 'gud) (require 'comint) (require 'shell))
4241
4242;;;###autoload
4243(defun matlab-shell ()
4244 "Create a buffer with MATLAB running as a subprocess.
4245
4246MATLAB shell cannot work on the MS Windows platform because MATLAB is not
4247a console application."
4248 (interactive)
4249 ;; MATLAB shell does not work by default on the Windows platform. Only
4250 ;; permit it's operation when the shell command string is different from
4251 ;; the default value. (True when the engine program is running.)
4252 (if (and (or (eq window-system 'pc) (eq window-system 'w32))
4253 (string= matlab-shell-command "matlab"))
4254 (error "MATLAB cannot be run as a inferior process. \
4255Try C-h f matlab-shell RET"))
4256
4257 (require 'shell)
4258 (require 'gud)
4259
4260 ;; Make sure this is safe...
4261 (if (and matlab-shell-enable-gud-flag (fboundp 'gud-def))
4262 ;; We can continue using GUD
4263 nil
4264 (message "Sorry, your emacs cannot use the MATLAB Shell GUD features.")
4265 (setq matlab-shell-enable-gud-flag nil))
4266
4267 (switch-to-buffer (concat "*" matlab-shell-buffer-name "*"))
4268 (if (matlab-shell-active-p)
4269 nil
4270 ;; Clean up crufty state
4271 (kill-all-local-variables)
4272 ;; Build keymap here in case someone never uses comint mode
4273 (if matlab-shell-mode-map
4274 ()
4275 (setq matlab-shell-mode-map
4276 (let ((km (make-sparse-keymap 'matlab-shell-mode-map)))
4277 (if (fboundp 'set-keymap-parent)
4278 (set-keymap-parent km comint-mode-map)
4279 ;; 19.31 doesn't have set-keymap-parent
4280 (setq km (nconc km comint-mode-map)))
4281 (substitute-key-definition 'next-error 'matlab-shell-last-error
4282 km global-map)
4283 (define-key km [(control h) (control m)]
4284 matlab-help-map)
4285 (define-key km "\C-c." 'matlab-find-file-on-path)
4286 (define-key km [(tab)] 'matlab-shell-tab)
4287 (define-key km [(control up)]
4288 'comint-previous-matching-input-from-input)
4289 (define-key km [(control down)]
4290 'comint-next-matching-input-from-input)
4291 (define-key km [up]
4292 'matlab-shell-previous-matching-input-from-input)
4293 (define-key km [down]
4294 'matlab-shell-next-matching-input-from-input)
4295 (define-key km [(control return)] 'comint-kill-input)
4296 (define-key km "\C-?"
4297 'matlab-shell-delete-backwards-no-prompt)
4298 (define-key km [(backspace)]
4299 'matlab-shell-delete-backwards-no-prompt)
4300 km)))
4301 (switch-to-buffer
4302 (apply 'make-comint matlab-shell-buffer-name matlab-shell-command
4303 nil matlab-shell-command-switches))
4304
4305 (setq shell-dirtrackp t)
4306 (comint-mode)
4307
4308 (if matlab-shell-enable-gud-flag
4309 (progn
4310 (gud-mode)
4311 (make-local-variable 'matlab-prompt-seen)
4312 (setq matlab-prompt-seen nil)
4313 (make-local-variable 'gud-marker-filter)
4314 (setq gud-marker-filter 'gud-matlab-marker-filter)
4315 (make-local-variable 'gud-find-file)
4316 (setq gud-find-file 'gud-matlab-find-file)
4317
4318 (set-process-filter (get-buffer-process (current-buffer))
4319 'gud-filter)
4320 (set-process-sentinel (get-buffer-process (current-buffer))
4321 'gud-sentinel)
4322 (gud-set-buffer))
4323 ;; What to do when there is no GUD
4324 ;(set-process-filter (get-buffer-process (current-buffer))
4325 ; 'matlab-shell-process-filter)
4326 )
4327
4328 ;; Comint and GUD both try to set the mode. Now reset it to
4329 ;; matlab mode.
4330 (matlab-shell-mode)))
4331
4332(defcustom matlab-shell-logo
4333 (if (fboundp 'locate-data-file)
4334 ;; Starting from XEmacs 20.4 use locate-data-file
4335 (locate-data-file "matlab.xpm")
4336 (expand-file-name "matlab.xpm" data-directory))
4337 "*The MATLAB logo file."
4338 :group 'matlab-shell
4339 :type '(choice (const :tag "None" nil)
4340 (file :tag "File" "")))
4341
4342
4343(defun matlab-shell-hack-logo (str)
4344 "Replace the text logo with a real logo.
4345STR is passed from the commint filter."
4346 (when (string-match "< M A T L A B >" str)
4347 (save-excursion
4348 (when (re-search-backward "^[ \t]+< M A T L A B (R) >" (point-min) t)
4349 (delete-region (match-beginning 0) (match-end 0))
4350 (insert (make-string 16 ? ))
4351 (set-extent-begin-glyph (make-extent (point) (point))
4352 (make-glyph matlab-shell-logo))))
4353 ;; Remove this function from `comint-output-filter-functions'
4354 (remove-hook 'comint-output-filter-functions
4355 'matlab-shell-hack-logo))
4356
4357 )
4358
4359(defun matlab-shell-version-scrape (str)
4360 "Scrape the MATLAB Version from the MATLAB startup text.
4361Argument STR is the string to examine for version information."
4362 (when (string-match "\\(Version\\)\\s-+\\([.0-9]+\\)\\s-+(\\(R[.0-9]+[ab]?\\))" str)
4363 ;; Extract the release number
4364 (setq matlab-shell-running-matlab-version
4365 (match-string 2 str)
4366 matlab-shell-running-matlab-release
4367 (match-string 3 str))
4368 ;; Now get our history loaded
4369 (setq comint-input-ring-file-name
4370 (format matlab-shell-history-file matlab-shell-running-matlab-release))
4371 (if (fboundp 'comint-read-input-ring)
4372 (comint-read-input-ring t))
4373 ;; Remove the scrape from our list of things to do.
4374 (remove-hook 'comint-output-filter-functions
4375 'matlab-shell-version-scrape)))
4376
4377(defun matlab-shell-mode ()
4378 "Run MATLAB as a subprocess in an Emacs buffer.
4379
4380This mode will allow standard Emacs shell commands/completion to occur
4381with MATLAB running as an inferior process. Additionally, this shell
4382mode is integrated with `matlab-mode', a major mode for editing M
4383code.
4384
4385> From an M file buffer:
4386\\<matlab-mode-map>
4387\\[matlab-shell-save-and-go] - Save the current M file, and run it in a \
4388MATLAB shell.
4389
4390> From Shell mode:
4391\\<matlab-shell-mode-map>
4392\\[matlab-shell-last-error] - find location of last MATLAB runtime error \
4393in the offending M file.
4394
4395> From an M file, or from Shell mode:
4396\\<matlab-mode-map>
4397\\[matlab-shell-run-command] - Run COMMAND and show result in a popup buffer.
4398\\[matlab-shell-describe-variable] - Show variable contents in a popup buffer.
4399\\[matlab-shell-describe-command] - Show online documentation for a command \
4400in a popup buffer.
4401\\[matlab-shell-apropos] - Show output from LOOKFOR command in a popup buffer.
4402\\[matlab-shell-topic-browser] - Topic browser using HELP.
4403
4404> Keymap:
4405\\{matlab-mode-map}"
4406 (setq major-mode 'matlab-shell-mode
4407 mode-name "M-Shell"
4408 comint-prompt-regexp "^\\(K\\|EDU\\)?>> *"
4409 comint-delimiter-argument-list (list [ 59 ]) ; semi colon
4410 comint-dynamic-complete-functions '(comint-replace-by-expanded-history)
4411 comint-process-echoes matlab-shell-echoes
4412 )
4413 ;; matlab-shell variable setup
4414 (make-local-variable 'matlab-shell-last-error-anchor)
4415 (setq matlab-shell-last-error-anchor nil)
4416
4417 ;; Shell Setup
4418 (require 'shell)
4419 (if (fboundp 'shell-directory-tracker)
4420 (add-hook 'comint-input-filter-functions 'shell-directory-tracker nil t)) ;; patch Eli Merriam
4421 ;; Add a spiffy logo if we are running XEmacs
4422 (if (and (string-match "XEmacs" emacs-version)
4423 (stringp matlab-shell-logo)
4424 (file-readable-p matlab-shell-logo))
4425 (add-hook 'comint-output-filter-functions 'matlab-shell-hack-logo))
4426 ;; Add a version scraping logo identification filter.
4427 (add-hook 'comint-output-filter-functions 'matlab-shell-version-scrape)
4428 ;; Add pseudo html-renderer
4429 (add-hook 'comint-output-filter-functions 'matlab-shell-render-html-anchor nil t)
4430 (add-hook 'comint-output-filter-functions 'matlab-shell-render-html-txt-format nil t)
4431 (add-hook 'comint-output-filter-functions 'matlab-shell-render-errors-as-anchor nil t)
4432 ;; Scroll to bottom after running cell/region
4433 (add-hook 'comint-output-filter-functions 'comint-postoutput-scroll-to-bottom)
4434
4435 (make-local-variable 'comment-start)
4436 (setq comment-start "%")
4437 (use-local-map matlab-shell-mode-map)
4438 (set-syntax-table matlab-mode-syntax-table)
4439 (make-local-variable 'font-lock-defaults)
4440 (setq font-lock-defaults '((matlab-shell-font-lock-keywords-1
4441 matlab-shell-font-lock-keywords-2
4442 matlab-shell-font-lock-keywords-3)
4443 t nil ((?_ . "w"))))
4444 (set (make-local-variable 'comint-input-ring-size)
4445 matlab-shell-input-ring-size)
4446 (set (make-local-variable 'comint-input-ring-file-name)
4447 (format matlab-shell-history-file "R12"))
4448 (if (fboundp 'comint-read-input-ring)
4449 (comint-read-input-ring t))
4450 (make-local-variable 'gud-marker-acc)
4451 (easy-menu-define
4452 matlab-shell-menu
4453 matlab-shell-mode-map
4454 "MATLAB shell menu"
4455 '("MATLAB"
4456 ["Goto last error" matlab-shell-last-error t]
4457 "----"
4458 ["Stop On Errors" matlab-shell-dbstop-error t]
4459 ["Don't Stop On Errors" matlab-shell-dbclear-error t]
4460 "----"
4461 ["Run Command" matlab-shell-run-command t]
4462 ["Describe Variable" matlab-shell-describe-variable t]
4463 ["Describe Command" matlab-shell-describe-command t]
4464 ["Lookfor Command" matlab-shell-apropos t]
4465 ["Topic Browser" matlab-shell-topic-browser t]
4466 "----"
4467 ["Demos" matlab-shell-demos t]
4468 ["Close Current Figure" matlab-shell-close-current-figure t]
4469 ["Close Figures" matlab-shell-close-figures t]
4470 "----"
4471 ["Customize" (customize-group 'matlab-shell)
4472 (and (featurep 'custom) (fboundp 'custom-declare-variable))
4473 ]
4474 ["Exit" matlab-shell-exit t]))
4475 (easy-menu-add matlab-shell-menu matlab-shell-mode-map)
4476
4477 (if matlab-shell-enable-gud-flag
4478 (progn
4479 (gud-def gud-break "dbstop at %l in %f" "\C-b" "Set breakpoint at current line.")
4480 (gud-def gud-remove "dbclear at %l in %f" "\C-d" "Remove breakpoint at current line")
4481 (gud-def gud-step "dbstep in" "\C-s" "Step one source line, possibly into a function.")
4482 (gud-def gud-next "dbstep %p" "\C-n" "Step over one source line.")
4483 (gud-def gud-cont "dbcont" "\C-r" "Continue with display.")
4484 (gud-def gud-finish "dbquit" "\C-f" "Finish executing current function.")
4485 (gud-def gud-up "dbup %p" "<" "Up N stack frames (numeric arg).")
4486 (gud-def gud-down "dbdown %p" ">" "Down N stack frames (numeric arg).")
4487 (gud-def gud-print "%e" "\C-p" "Evaluate M expression at point.")
4488 (gud-def gud-status "dbstatus" "\C-a" "Show all break points")
4489 (if (fboundp 'gud-make-debug-menu)
4490 (gud-make-debug-menu))
4491 (if (fboundp 'gud-overload-functions)
4492 (gud-overload-functions
4493 '((gud-massage-args . gud-matlab-massage-args)
4494 (gud-marker-filter . gud-matlab-marker-filter)
4495 (gud-find-file . gud-matlab-find-file))))
4496 ;; XEmacs doesn't seem to have this concept already. Oh well.
4497 (setq gud-marker-acc nil)
4498 ;; XEmacs has problems w/ this variable. Set it here.
4499 (set-marker comint-last-output-start (point-max))
4500 ))
4501 (run-hooks 'matlab-shell-mode-hook)
4502 (matlab-show-version)
4503 )
4504
4505(defvar gud-matlab-marker-regexp-prefix "error:\\|opentoline"
4506 "A prefix to scan for to know if output might be scarfed later.")
4507
4508(defvar matlab-shell-html-map
4509 (let ((km (make-sparse-keymap)))
4510 (if (string-match "XEmacs" emacs-version)
4511 (define-key km [button2] 'matlab-shell-html-click)
4512 (define-key km [mouse-2] 'matlab-shell-html-click))
4513 (define-key km [return] 'matlab-shell-html-go)
4514 km)
4515 "Keymap used on overlays that represent errors.")
4516
4517;; ANCHORS
4518(defvar matlab-anchor-beg "<a href=\"\\(?:matlab: \\)?\\([^\"]+\\)\">"
4519 "Beginning of html anchor.")
4520
4521(defvar matlab-anchor-end "</a>"
4522 "End of html anchor.")
4523
4524(defun matlab-shell-render-html-anchor (str)
4525 "Render html anchors inserted into the MATLAB shell buffer.
4526Argument STR is the text for the anchor."
4527 (if (string-match matlab-anchor-end str)
4528 (save-excursion
4529 (while (re-search-backward matlab-anchor-beg
4530 ;; Arbitrary back-buffer. We don't
4531 ;; usually get text in such huge chunks
4532 (max (point-min) (- (point-max) 8192))
4533 t)
4534 (let* ((anchor-beg-start (match-beginning 0))
4535 (anchor-beg-finish (match-end 0))
4536 (anchor-text (match-string 1))
4537 (anchor-end-finish (search-forward matlab-anchor-end))
4538 (anchor-end-start (match-beginning 0))
4539 (o (matlab-make-overlay anchor-beg-finish anchor-end-start)))
4540 (matlab-overlay-put o 'mouse-face 'highlight)
4541 (matlab-overlay-put o 'face 'underline)
4542 (matlab-overlay-put o 'matlab-url anchor-text)
4543 (matlab-overlay-put o 'keymap matlab-shell-html-map)
4544 (matlab-overlay-put o 'help-echo anchor-text)
4545 (delete-region anchor-end-start anchor-end-finish)
4546 (delete-region anchor-beg-start anchor-beg-finish)
4547 ))))
4548 )
4549
4550;; TEXT FORMATTING
4551(defvar matlab-txt-format-beg "<\\(strong\\|u\\)>"
4552 "Beginning of html text formatting signal in HTML.")
4553
4554(defvar matlab-txt-format-end "</%s>"
4555 "End of some html text formatter.
4556Includes a %s to match the kind of text format start regexp.")
4557
4558(defun matlab-shell-render-html-txt-format (str)
4559 "Render html text format inserted into the MATLAB shell buffer.
4560Argument STR is the text for the text formater."
4561 (if (string-match "</\\w+>" str)
4562 (save-excursion
4563 (while (re-search-backward matlab-txt-format-beg
4564 ;; Arbitrary back-buffer. We don't
4565 ;; usually get text in such huge chunks
4566 (max (point-min) (- (point-max) 8192))
4567 t)
4568 (let* ((txt-format-beg-start (match-beginning 0))
4569 (txt-format-beg-finish (match-end 0))
4570 (txt-format-text (match-string 1))
4571 (txt-format-end-finish
4572 ;; The finish combines the text from the start to get an
4573 ;; exact match.
4574 (search-forward (format matlab-txt-format-end txt-format-text)))
4575 (txt-format-end-start (match-beginning 0))
4576 (o (matlab-make-overlay txt-format-beg-finish txt-format-end-start)))
4577 (cond ((string= txt-format-text "strong")
4578 (upcase-region txt-format-beg-finish txt-format-end-start)
4579 (matlab-overlay-put o 'face 'bold))
4580 ((string= txt-format-text "u")
4581 (matlab-overlay-put o 'face 'underline))
4582 (t
4583 ;; If we don't match, delete the overlay instead.
4584 (matlab-delete-overlay o)
4585 (setq o nil)
4586 ))
4587 (when o
4588 (delete-region txt-format-end-start txt-format-end-finish)
4589 (delete-region txt-format-beg-start txt-format-beg-finish))
4590 ))))
4591 )
4592
4593;; The regular expression covers the following form:
4594;; Errors: Error in ==> <function name>
4595;; On line # ==> <command_name>
4596;; Errors: Error using ==> <function name> at <#>
4597;; Syntax: Syntax error in ==> <filename>
4598;; On line # ==> <sample-text>
4599;; Warning: In <filename> at line # <stuff>
4600(defvar gud-matlab-error-regexp
4601 (concat "\\(Error \\(?:in\\|using\\) ==>\\|Syntax error in ==>\\|In\\) "
4602 "\\([-@.a-zA-Z_0-9/ \\\\:]+\\)\\(?:>[^ ]+\\)?.*[\n ]\\(?:On\\|at\\)\\(?: line\\)? "
4603 "\\([0-9]+\\) ?")
4604 "Regular expression finding where an error occurred.")
4605
4606(defvar matlab-shell-last-error-anchor nil
4607 "Last point where an error anchor was set.")
4608(defvar matlab-shell-last-anchor-as-frame nil
4609 ;; NOTE: this isn't being used yet.
4610 "The last error anchor saved, represented as a debugger frame.")
4611
4612(defun matlab-shell-render-errors-as-anchor (str)
4613 "Detect non-url errors, and treat them as if they were url anchors.
4614Argument STR is the text that might have errors in it."
4615 (save-excursion
4616 ;; We have found an error stack to investigate.
4617 (let ((first nil)
4618 (overlaystack nil))
4619 (while (re-search-backward gud-matlab-error-regexp
4620 (if matlab-shell-last-error-anchor
4621 (min matlab-shell-last-error-anchor (point))
4622 (point))
4623 t)
4624 (let* ((err-start (match-beginning 0))
4625 (err-end (match-end 0))
4626 (err-text (match-string 0))
4627 (err-file (match-string 2))
4628 (err-line (match-string 3))
4629 (o (matlab-make-overlay err-start err-end))
4630 (url (concat "opentoline('" err-file "'," err-line ",0)"))
4631 )
4632 (matlab-overlay-put o 'mouse-face 'highlight)
4633 (matlab-overlay-put o 'face 'underline)
4634 ;; The url will recycle opentoline code.
4635 (matlab-overlay-put o 'matlab-url url)
4636 (matlab-overlay-put o 'keymap matlab-shell-html-map)
4637 (matlab-overlay-put o 'help-echo (concat "Jump to error at " err-file "."))
4638 (setq first url)
4639 (push o overlaystack)
4640 ;; Save as a frame
4641 (setq matlab-shell-last-anchor-as-frame
4642 (cons err-file err-line))
4643 ))
4644 ;; Keep track of the very first error in this error stack.
4645 ;; It will represent the "place to go" for "go-to-last-error".
4646 (dolist (O overlaystack)
4647 (matlab-overlay-put O 'first-in-error-stack first))
4648 ;; Once we've found something, don't scan it again.
4649 (setq matlab-shell-last-error-anchor (point-marker)))))
4650
4651(defvar gud-matlab-marker-regexp-1 "^K>>"
4652 "Regular expression for finding a file line-number.")
4653
4654(defvar gud-matlab-marker-regexp-2
4655 (concat "^> In \\(" matlab-anchor-beg
4656 "\\|\\)\\([-.a-zA-Z0-9_>/@]+\\) \\((\\w+) \\|\\)at line \\([0-9]+\\)[ \n]+")
4657 "Regular expression for finding a file line-number.
4658Please note: The leading > character represents the current stack frame, so if
4659there are several frames, this makes sure we pick the right one to popup.")
4660
4661(defun gud-matlab-massage-args (file args)
4662 "Argument massager for starting matlab file.
4663I don't think I have to do anything, but I'm not sure.
4664FILE is ignored, and ARGS is returned."
4665 args)
4666
4667(defun gud-matlab-marker-filter (string)
4668 "Filters STRING for the Unified Debugger based on MATLAB output."
4669 (if matlab-prompt-seen
4670 nil
4671 (when (string-match ">> " string)
4672 (if matlab-shell-use-emacs-toolbox
4673 ;; Use our local toolbox directory.
4674 (process-send-string
4675 (get-buffer-process gud-comint-buffer)
4676 (format "addpath('%s','-begin'); rehash; emacsinit('%s');\n"
4677 (expand-file-name "toolbox"
4678 (file-name-directory
4679 (locate-library "matlab")))
4680 matlab-shell-emacsclient-command))
4681 ;; User doesn't want to use our fancy toolbox directory
4682 (process-send-string
4683 (get-buffer-process gud-comint-buffer)
4684 "if usejava('jvm'), \
4685com.mathworks.services.Prefs.setBooleanPref('EditorGraphicalDebugging', false); \
4686end\n"
4687 ))
4688 ;; Mark that we've seen at least one prompt.
4689 (setq matlab-prompt-seen t)
4690 ))
4691 (let ((garbage (concat "\\(" (regexp-quote "\C-g") "\\|"
4692 (regexp-quote "\033[H0") "\\|"
4693 (regexp-quote "\033[H\033[2J") "\\|"
4694 (regexp-quote "\033H\033[2J") "\\)")))
4695 (while (string-match garbage string)
4696 (if (= (aref string (match-beginning 0)) ?\C-g)
4697 (beep t))
4698 (setq string (replace-match "" t t string))))
4699
4700 (setq gud-marker-acc (concat gud-marker-acc string))
4701 (let ((output "") (frame nil))
4702
4703 (when (not frame)
4704 (when (string-match gud-matlab-marker-regexp-1 gud-marker-acc)
4705 (when (not frame)
4706 ;; If there is a debug prompt, and no frame currently set,
4707 ;; go find one.
4708 (let ((url gud-marker-acc)
4709 ef el)
4710 (cond
4711 ((string-match "^error:\\(.*\\),\\([0-9]+\\),\\([0-9]+\\)$" url)
4712 (setq ef (substring url (match-beginning 1) (match-end 1))
4713 el (substring url (match-beginning 2) (match-end 2)))
4714 )
4715 ((string-match "opentoline('\\([^']+\\)',\\([0-9]+\\),\\([0-9]+\\))" url)
4716 (setq ef (substring url (match-beginning 1) (match-end 1))
4717 el (substring url (match-beginning 2) (match-end 2)))
4718 )
4719 ;; If we have the prompt, but no match (as above),
4720 ;; perhaps it is already dumped out into the buffer. In
4721 ;; that case, look back through the buffer.
4722
4723 )
4724 (when ef
4725 (setq frame (cons ef (string-to-number el)))))))
4726 )
4727 ;; This if makes sure that the entirety of an error output is brought in
4728 ;; so that matlab-shell-mode doesn't try to display a file that only partially
4729 ;; exists in the buffer. Thus, if MATLAB output:
4730 ;; error: /home/me/my/mo/mello.m,10,12
4731 ;; All of that is in the buffer, and it goes to mello.m, not just
4732 ;; the first half of that file name.
4733 ;; The below used to match against the prompt, not \n, but then text that
4734 ;; had error: in it for some other reason wouldn't display at all.
4735 (if (and matlab-prompt-seen ;; Don't collect during boot
4736 (not frame) ;; don't collect debug stuff
4737 (let ((start (string-match gud-matlab-marker-regexp-prefix gud-marker-acc)))
4738 (and start
4739 (not (string-match "\n" gud-marker-acc start))
4740 ;;(not (string-match "^K?>>\\|\\?\\?\\?\\s-Error while evaluating" gud-marker-acc start))
4741 )))
4742 ;; We could be collecting something. Wait for a while.
4743 nil
4744 ;; Finish off this part of the output. None of our special stuff
4745 ;; ends with a \n, so display those as they show up...
4746 (while (string-match "^[^\n]*\n" gud-marker-acc)
4747 (setq output (concat output (substring gud-marker-acc 0 (match-end 0)))
4748 gud-marker-acc (substring gud-marker-acc (match-end 0))))
4749
4750 (setq output (concat output gud-marker-acc)
4751 gud-marker-acc "")
4752 ;; Check our output for a prompt, and existence of a frame.
4753 ;; If t his is true, throw out the debug arrow stuff.
4754 (if (and (string-match "^>> $" output)
4755 gud-last-last-frame)
4756 (progn
4757 (setq overlay-arrow-position nil
4758 gud-last-last-frame nil
4759 gud-overlay-arrow-position nil)
4760 (sit-for 0)
4761 )))
4762
4763 (if frame (setq gud-last-frame frame))
4764
4765 ;;(message "[%s] [%s]" output gud-marker-acc)
4766
4767 output))
4768
4769(defun gud-matlab-find-file (f)
4770 "Find file F when debugging frames in MATLAB."
4771 (save-excursion
4772 (let* ((realfname (if (string-match "\\.\\(p\\)$" f)
4773 (progn
4774 (aset f (match-beginning 1) ?m)
4775 f)
4776 f))
4777 (buf (find-file-noselect realfname)))
4778 (set-buffer buf)
4779 (if (fboundp 'gud-make-debug-menu)
4780 (gud-make-debug-menu))
4781 buf)))
4782
4783(defun matlab-shell-next-matching-input-from-input (n)
4784 "Get the Nth next matching input from for the command line."
4785 (interactive "p")
4786 (matlab-shell-previous-matching-input-from-input (- n)))
4787
4788(defun matlab-shell-previous-matching-input-from-input (n)
4789 "Get the Nth previous matching input from for the command line."
4790 (interactive "p")
4791 (end-of-line) ;; patch: Mark Histed
4792 (if (comint-after-pmark-p)
4793 (if (memq last-command '(matlab-shell-previous-matching-input-from-input
4794 matlab-shell-next-matching-input-from-input))
4795 ;; This hack keeps the cycling working well.
4796 (let ((last-command 'comint-previous-matching-input-from-input))
4797 (comint-next-matching-input-from-input (- n)))
4798 ;; first time.
4799 (comint-next-matching-input-from-input (- n)))
4800
4801 ;; If somewhere else, just move around.
4802 (previous-line n)))
4803
4804(defun matlab-shell-delete-backwards-no-prompt (&optional arg)
4805 "Delete one char backwards without destroying the matlab prompt.
4806Optional argument ARG describes the number of chars to delete."
4807 (interactive "P")
4808 (let ((promptend (save-excursion
4809 (beginning-of-line)
4810 (if (looking-at "K?>> ")
4811 (match-end 0)
4812 (point))))
4813 (numchars (if (integerp arg) (- arg) -1)))
4814 (if (<= promptend (+ (point) numchars))
4815 (delete-char numchars)
4816 (error "Beginning of line"))))
4817
4818(defun matlab-shell-completion-list (str)
4819 "Get a list of completions from MATLAB.
4820STR is a substring to complete."
4821 (save-excursion
4822 (let* ((msbn (matlab-shell-buffer-barf-not-running))
4823 (cmd (concat "matlabMCRprocess = com.mathworks.jmi.MatlabMCR;"
4824 "matlabMCRprocess.mtFindAllTabCompletions('"
4825 str "'), clear('matlabMCRprocess');"))
4826 (comint-scroll-show-maximum-output nil)
4827 output
4828 (completions nil))
4829 (set-buffer msbn)
4830 (if (not (matlab-on-prompt-p))
4831 (error "MATLAB shell must be non-busy to do that"))
4832 (setq output (matlab-shell-collect-command-output cmd))
4833 ;; Debug
4834 (string-match "ans =" output)
4835 (setq output (substring output (match-end 0)))
4836 ;; Parse the output string.
4837 (while (string-match "'" output)
4838 ;; Hack off the preceeding quote
4839 (setq output (substring output (match-end 0)))
4840 (string-match "'" output)
4841 ;; we are making a completion list, so that is a list of lists.
4842 (setq completions (cons (list (substring output 0 (match-beginning 0)))
4843 completions)
4844 output (substring output (match-end 0))))
4845 ;; Return them
4846 (nreverse completions))))
4847
4848(defun matlab-shell-which-fcn (fcn)
4849 "Get the location of FCN's M file.
4850Returns an alist: ( LOCATION . BUILTINFLAG )
4851LOCATION is a string indicating where it is, and BUILTINFLAG is
4852non-nil if FCN is a builtin."
4853 (save-excursion
4854 (let* ((msbn (matlab-shell-buffer-barf-not-running))
4855 (cmd (concat "which " fcn))
4856 (comint-scroll-show-maximum-output nil)
4857 output
4858 builtin
4859 )
4860 (set-buffer msbn)
4861 (if (not (matlab-on-prompt-p))
4862 (error "MATLAB shell must be non-busy to do that"))
4863 (setq output (matlab-shell-collect-command-output cmd))
4864 ;; BUILT-IN
4865 (cond
4866 ((string-match "built-in (\\([^)]+\\))" output)
4867 (cons (concat (substring output (match-beginning 1) (match-end 1))
4868 ".m")
4869 t))
4870 ;; Error
4871 ((string-match "not found" output)
4872 nil)
4873 ;; JUST AN M FILE
4874 (t
4875 (string-match "$" output)
4876 (cons (substring output 0 (match-beginning 0)) nil))))))
4877
4878(defun matlab-shell-matlabroot ()
4879 "Get the location of of this shell's root.
4880Returns a string path to the root of the executing MATLAB."
4881 (save-excursion
4882 (let* ((msbn (matlab-shell-buffer-barf-not-running))
4883 (cmd "disp(matlabroot)")
4884 (comint-scroll-show-maximum-output nil)
4885 output
4886 builtin
4887 )
4888 (set-buffer msbn)
4889
4890 (if (and (boundp 'matlab-shell-matlabroot-run)
4891 matlab-shell-matlabroot-run)
4892 matlab-shell-matlabroot-run
4893 ;; If we haven't cache'd it, calculate it now.
4894
4895 (if (not (matlab-on-prompt-p))
4896 (error "MATLAB shell must be non-busy to do that"))
4897 (setq output (matlab-shell-collect-command-output cmd))
4898
4899 (string-match "$" output)
4900 (substring output 0 (match-beginning 0))))))
4901
4902(defvar matlab-shell-window-exists-for-display-completion-flag nil
4903 "Non-nil means there was an 'other-window' available when `display-completion-list' is called.")
4904
4905(defun matlab-shell-tab ()
4906 "Send [TAB] to the currently running matlab process and retrieve completion."
4907 (interactive)
4908 (if (not matlab-shell-ask-MATLAB-for-completions)
4909 (call-interactively 'comint-dynamic-complete-filename)
4910 (if (not (matlab-on-prompt-p))
4911 (error "Completions not available"))
4912 (if nil
4913 ;; For older versions of MATLAB that don't have TAB
4914 ;; completion.
4915 (call-interactively 'comint-dynamic-complete-filename)
4916 ;; Save the old command
4917 (goto-char (point-max))
4918 (let ((inhibit-field-text-motion t))
4919 (beginning-of-line))
4920 (re-search-forward comint-prompt-regexp)
4921 (let* ((lastcmd (buffer-substring (point) (matlab-point-at-eol)))
4922 (tempcmd lastcmd)
4923 (completions nil)
4924 (limitpos nil))
4925 ;; search for character which limits completion, and limit command to it
4926 (setq limitpos
4927 (if (string-match ".*\\([( /[.,;=']\\)" lastcmd)
4928 (1+ (match-beginning 1))
4929 0))
4930 (setq lastcmd (substring lastcmd limitpos))
4931 ;; Whack the old command so we can insert it back later.
4932 (delete-region (+ (point) limitpos) (matlab-point-at-eol))
4933 ;; double every single quote
4934 (while (string-match "[^']\\('\\)\\($\\|[^']\\)" tempcmd)
4935 (setq tempcmd (replace-match "''" t t tempcmd 1)))
4936 ;; collect the list
4937 (setq completions (matlab-shell-completion-list tempcmd))
4938 (goto-char (point-max))
4939 (if (eq (length completions) 1)
4940 ;; If there is only one, then there is an obvious thing to do.
4941 (progn
4942 (insert (car (car completions)))
4943 ;; kill completions buffer if still visible
4944 (matlab-shell-tab-hide-completions))
4945 (let ((try (try-completion lastcmd completions)))
4946 ;; Insert in a good completion.
4947 (cond ((or (eq try nil) (eq try t)
4948 (and (stringp try)
4949 (string= try lastcmd)))
4950 (insert lastcmd)
4951 ;; Before displaying the completions buffer, check to see if
4952 ;; the completions window is already displayed, or if there is
4953 ;; a next window to display. This determines how to remove the
4954 ;; completions later.
4955 (if (get-buffer-window "*Completions*")
4956 nil ;; Recycle old value of the display flag.
4957 ;; Else, reset this variable.
4958 (setq matlab-shell-window-exists-for-display-completion-flag
4959 ;; Else, it isn't displayed, save an action.
4960 (if (eq (next-window) (selected-window))
4961 ;; If there is no other window, the post action is
4962 ;; to delete.
4963 'delete
4964 ;; If there is a window to display, the post
4965 ;; action is to bury.
4966 'bury)))
4967 (with-output-to-temp-buffer "*Completions*"
4968 (display-completion-list (mapcar 'car completions) lastcmd)))
4969 ((stringp try)
4970 (insert try)
4971 (matlab-shell-tab-hide-completions))
4972 (t
4973 (insert lastcmd))))
4974 )))))
4975
4976(defun matlab-shell-tab-hide-completions ()
4977 "Hide any completion windows for `matlab-shell-tab'."
4978 (cond ((eq matlab-shell-window-exists-for-display-completion-flag 'delete)
4979 (when (get-buffer "*Completions*")
4980 (delete-windows-on "*Completions*")))
4981 ((eq matlab-shell-window-exists-for-display-completion-flag 'bury)
4982 (let ((orig (selected-window))
4983 (bw nil))
4984 (while (setq bw (get-buffer-window "*Completions*"))
4985 (select-window bw)
4986 (bury-buffer))
4987 (select-window orig)))
4988 )
4989 ;; Reset state.
4990 (setq matlab-shell-window-exists-for-display-completion-flag nil))
4991
4992
4993;;; MATLAB mode Shell commands ================================================
4994
4995(defun matlab-show-matlab-shell-buffer ()
4996 "Switch to the buffer containing the matlab process."
4997 (interactive)
4998 (let ((msbn (concat "*" matlab-shell-buffer-name "*")))
4999 (if (get-buffer msbn)
5000 (switch-to-buffer-other-window msbn)
5001 (message "There is not an active MATLAB process."))))
5002
5003(defvar matlab-shell-save-and-go-history '("()")
5004 "Keep track of parameters passed to the MATLAB shell.")
5005
5006(defun matlab-shell-add-to-input-history (string)
5007 "Add STRING to the input-ring and run `comint-input-filter-functions' on it.
5008Similar to `comint-send-input'."
5009 (if (and (funcall comint-input-filter string)
5010 (or (null comint-input-ignoredups)
5011 (not (ring-p comint-input-ring))
5012 (ring-empty-p comint-input-ring)
5013 (not (string-equal (ring-ref comint-input-ring 0) string))))
5014 (ring-insert comint-input-ring string))
5015 (run-hook-with-args 'comint-input-filter-functions
5016 (concat string "\n"))
5017 (if (boundp 'comint-save-input-ring-index);only bound in GNU emacs
5018 (setq comint-save-input-ring-index comint-input-ring-index))
5019 (setq comint-input-ring-index nil))
5020
5021(defun matlab-shell-save-and-go ()
5022 "Save this M file, and evaluate it in a MATLAB shell."
5023 (interactive)
5024 (if (not (eq major-mode 'matlab-mode))
5025 (error "Save and go is only useful in a MATLAB buffer!"))
5026 (if (not (buffer-file-name (current-buffer)))
5027 (call-interactively 'write-file))
5028 (let ((fn-name (file-name-sans-extension
5029 (file-name-nondirectory (buffer-file-name))))
5030 (msbn (concat "*" matlab-shell-buffer-name "*"))
5031 (param ""))
5032 (save-buffer)
5033 ;; Do we need parameters?
5034 (if (save-excursion
5035 (goto-char (point-min))
5036 (end-of-line)
5037 (forward-sexp -1)
5038 (looking-at "([a-zA-Z]"))
5039 (setq param (read-string "Parameters: "
5040 (car matlab-shell-save-and-go-history)
5041 'matlab-shell-save-and-go-history)))
5042 (if (matlab-with-emacs-link)
5043 ;; Execute the current file in MATLAB
5044 (matlab-eei-run)
5045
5046 ;; No buffer? Make it!
5047 (if (not (get-buffer msbn)) (matlab-shell))
5048 ;; Ok, now fun the function in the matlab shell
5049 (if (get-buffer-window msbn t)
5050 (select-window (get-buffer-window msbn t))
5051 (switch-to-buffer (concat "*" matlab-shell-buffer-name "*")))
5052
5053 (let ((cmd (concat fn-name " " param)))
5054 (matlab-shell-add-to-input-history cmd)
5055 (matlab-shell-send-string (concat cmd "\n"))))))
5056
5057(defun matlab-shell-run-region (beg end &optional noshow)
5058 "Run region from BEG to END and display result in MATLAB shell.
5059If NOSHOW is non-nil, replace newlines with commas to suppress output.
5060This command requires an active MATLAB shell."
5061 (interactive "r")
5062 (if (> beg end) (let (mid) (setq mid beg beg end end mid)))
5063
5064 (let ((command
5065 (let ((str (concat (buffer-substring beg end) "\n")))
5066 ;; Remove comments
5067 (with-temp-buffer
5068 (insert str)
5069 (goto-char (point-min))
5070 (while (search-forward "%" nil t)
5071 (when (not (matlab-cursor-in-string))
5072 (delete-region (1- (point)) (matlab-point-at-eol))))
5073 (setq str (buffer-substring-no-properties (point-min) (point-max))))
5074 (while (string-match "\n\\s-*\n" str)
5075 (setq str (concat (substring str 0 (match-beginning 0))
5076 "\n"
5077 (substring str (match-end 0)))))
5078 (when noshow
5079 ;; Remove continuations
5080 (while (string-match
5081 (concat "\\s-*"
5082 (regexp-quote matlab-elipsis-string)
5083 "\\s-*\n")
5084 str)
5085 (setq str (replace-match " " t t str)))
5086 (while (string-match "\n" str)
5087 (setq str (replace-match ", " t t str)))
5088 (setq str (concat str "\n")))
5089 str))
5090 (msbn nil)
5091 (lastcmd)
5092 (inhibit-field-text-motion t))
5093 (if (matlab-with-emacs-link)
5094 ;; Run the region w/ Emacs Link
5095 (matlab-eei-eval-region beg end)
5096
5097 (save-excursion
5098 (setq msbn (matlab-shell-buffer-barf-not-running))
5099 (set-buffer msbn)
5100 (if (not (matlab-on-prompt-p))
5101 (error "MATLAB shell must be non-busy to do that"))
5102 ;; Save the old command
5103 (beginning-of-line)
5104 (re-search-forward comint-prompt-regexp)
5105 (setq lastcmd (buffer-substring (point) (matlab-point-at-eol)))
5106 (delete-region (point) (matlab-point-at-eol))
5107 ;; We are done error checking, run the command.
5108 (matlab-shell-send-string command)
5109 (insert lastcmd))
5110 (set-buffer msbn)
5111 (goto-char (point-max))
5112 (display-buffer msbn nil "visible"))
5113 ))
5114
5115(defun matlab-shell-run-cell ()
5116 "Run the cell the cursor is in."
5117 (interactive)
5118 (let ((start (save-excursion (forward-page -1)
5119 (if (looking-at "function")
5120 (error "You are not in a cell. Try `matlab-shell-save-and-go' instead"))
5121 (when (matlab-ltype-comm)
5122 ;; Skip over starting comment from the current cell.
5123 (matlab-end-of-command 1)
5124 (end-of-line)
5125 (forward-char 1))
5126 (point)))
5127 (end (save-excursion (forward-page 1)
5128 (when (matlab-ltype-comm)
5129 (beginning-of-line)
5130 (forward-char -1))
5131 (point))))
5132 (matlab-shell-run-region start end t)))
5133
5134(defun matlab-shell-run-region-or-line ()
5135 "Run region from BEG to END and display result in MATLAB shell.
5136pIf region is not active run the current line.
5137This command requires an active MATLAB shell."
5138 (interactive)
5139 (if (and transient-mark-mode mark-active)
5140 (matlab-shell-run-region (mark) (point))
5141 (matlab-shell-run-region (matlab-point-at-bol) (matlab-point-at-eol))))
5142
5143
5144;;; MATLAB Shell Commands =====================================================
5145
5146(defun matlab-read-word-at-point ()
5147 "Get the word closest to point, but do not change position.
5148Has a preference for looking backward when not directly on a symbol.
5149Snatched and hacked from dired-x.el"
5150 (let ((word-chars "a-zA-Z0-9_")
5151 (bol (matlab-point-at-bol))
5152 (eol (matlab-point-at-eol))
5153 start)
5154 (save-excursion
5155 ;; First see if just past a word.
5156 (if (looking-at (concat "[" word-chars "]"))
5157 nil
5158 (skip-chars-backward (concat "^" word-chars "{}()\[\]") bol)
5159 (if (not (bobp)) (backward-char 1)))
5160 (if (numberp (string-match (concat "[" word-chars "]")
5161 (char-to-string (following-char))))
5162 (progn
5163 (skip-chars-backward word-chars bol)
5164 (setq start (point))
5165 (skip-chars-forward word-chars eol))
5166 (setq start (point))) ; If no found, return empty string
5167 (buffer-substring start (point)))))
5168
5169(defun matlab-read-line-at-point ()
5170 "Get the line under point, if command line."
5171 (if (eq major-mode 'matlab-shell-mode)
5172 (save-excursion
5173 (let ((inhibit-field-text-motion t))
5174 (beginning-of-line)
5175 (if (not (looking-at (concat comint-prompt-regexp)))
5176 ""
5177 (search-forward-regexp comint-prompt-regexp)
5178 (buffer-substring (point) (matlab-point-at-eol)))))
5179 (save-excursion
5180 ;; In matlab buffer, find all the text for a command.
5181 ;; so back over until there is no more continuation.
5182 (while (save-excursion (forward-line -1) (matlab-lattr-cont))
5183 (forward-line -1))
5184 ;; Go forward till there is no continuation
5185 (beginning-of-line)
5186 (let ((start (point)))
5187 (while (matlab-lattr-cont) (forward-line 1))
5188 (end-of-line)
5189 (buffer-substring start (point))))))
5190
5191(defun matlab-non-empty-lines-in-string (str)
5192 "Return number of non-empty lines in STR."
5193 (let ((count 0)
5194 (start 0))
5195 (while (string-match "^.+$" str start)
5196 (setq count (1+ count)
5197 start (match-end 0)))
5198 count))
5199
5200(defun matlab-output-to-temp-buffer (buffer output)
5201 "Print output to temp buffer, or a message if empty string.
5202BUFFER is the buffer to output to, and OUTPUT is the text to insert."
5203 (let ((lines-found (matlab-non-empty-lines-in-string output)))
5204 (cond ((= lines-found 0)
5205 (message "(MATLAB command completed with no output)"))
5206 ((= lines-found 1)
5207 (string-match "^.+$" output)
5208 (message (substring output (match-beginning 0)(match-end 0))))
5209 (t (with-output-to-temp-buffer buffer (princ output))
5210 (save-excursion
5211 (set-buffer buffer)
5212 (matlab-shell-help-mode))))))
5213
5214(defun matlab-shell-run-command (command)
5215 "Run COMMAND and display result in a buffer.
5216This command requires an active MATLAB shell."
5217 (interactive (list (read-from-minibuffer
5218 "MATLAB command line: "
5219 (cons (matlab-read-line-at-point) 0))))
5220 (let ((doc (matlab-shell-collect-command-output command)))
5221 (matlab-output-to-temp-buffer "*MATLAB Help*" doc)))
5222
5223(defun matlab-shell-describe-variable (variable)
5224 "Get the contents of VARIABLE and display them in a buffer.
5225This uses the WHOS (MATLAB 5) command to find viable commands.
5226This command requires an active MATLAB shell."
5227 (interactive (list (read-from-minibuffer
5228 "MATLAB variable: "
5229 (cons (matlab-read-word-at-point) 0))))
5230 (let ((doc (matlab-shell-collect-command-output (concat "whos " variable))))
5231 (matlab-output-to-temp-buffer "*MATLAB Help*" doc)))
5232
5233(defun matlab-shell-describe-command (command)
5234 "Describe COMMAND textually by fetching it's doc from the MATLAB shell.
5235This uses the lookfor command to find viable commands.
5236This command requires an active MATLAB shell."
5237 (interactive
5238 (let ((fn (matlab-function-called-at-point))
5239 val)
5240 (setq val (read-string (if fn
5241 (format "Describe function (default %s): " fn)
5242 "Describe function: ")))
5243 (if (string= val "") (list fn) (list val))))
5244 (let ((doc (matlab-shell-collect-command-output (concat "help " command))))
5245 (matlab-output-to-temp-buffer "*MATLAB Help*" doc)))
5246
5247(defun matlab-shell-apropos (matlabregex)
5248 "Look for any active commands in MATLAB matching MATLABREGEX.
5249This uses the lookfor command to find viable commands."
5250 (interactive (list (read-from-minibuffer
5251 "MATLAB command subexpression: "
5252 (cons (matlab-read-word-at-point) 0))))
5253 (let ((ap (matlab-shell-collect-command-output
5254 (concat "lookfor " matlabregex))))
5255 (matlab-output-to-temp-buffer "*MATLAB Apropos*" ap)))
5256
5257(defun matlab-on-prompt-p ()
5258 "Return t if we MATLAB can accept input."
5259 (save-excursion
5260 (let ((inhibit-field-text-motion t))
5261 (goto-char (point-max))
5262 (beginning-of-line)
5263 (looking-at comint-prompt-regexp))))
5264
5265(defun matlab-on-empty-prompt-p ()
5266 "Return t if we MATLAB is on an empty prompt."
5267 (save-excursion
5268 (let ((inhibit-field-text-motion t))
5269 (goto-char (point-max))
5270 (beginning-of-line)
5271 (looking-at (concat comint-prompt-regexp "\\s-*$")))))
5272
5273(defun matlab-shell-buffer-barf-not-running ()
5274 "Return a running MATLAB buffer iff it is currently active."
5275 (or (matlab-shell-active-p)
5276 (error "You need to run the command `matlab-shell' to do that!")))
5277
5278(defun matlab-shell-collect-command-output (command)
5279 "If there is a MATLAB shell, run the MATLAB COMMAND and return it's output.
5280It's output is returned as a string with no face properties. The text output
5281of the command is removed from the MATLAB buffer so there will be no
5282indication that it ran."
5283 (let ((msbn (matlab-shell-buffer-barf-not-running))
5284 (pos nil)
5285 (str nil)
5286 (lastcmd)
5287 (inhibit-field-text-motion t))
5288 (save-excursion
5289 (set-buffer msbn)
5290 (if (not (matlab-on-prompt-p))
5291 (error "MATLAB shell must be non-busy to do that"))
5292 ;; Save the old command
5293 (goto-char (point-max))
5294 (beginning-of-line)
5295 (re-search-forward comint-prompt-regexp)
5296 (setq lastcmd (buffer-substring (point) (matlab-point-at-eol)))
5297 (delete-region (point) (matlab-point-at-eol))
5298 ;; We are done error checking, run the command.
5299 (setq pos (point))
5300 (comint-simple-send (get-buffer-process (current-buffer))
5301 (concat command "\n"))
5302 ;;(message "MATLAB ... Executing command.")
5303 (goto-char (point-max))
5304 (while (or (>= (+ pos (string-width command)) (point)) (not (matlab-on-empty-prompt-p)))
5305 (accept-process-output (get-buffer-process (current-buffer)))
5306 (goto-char (point-max))
5307 ;;(message "MATLAB reading...")
5308 )
5309 ;;(message "MATLAB reading...done")
5310 (save-excursion
5311 (goto-char pos)
5312 (beginning-of-line)
5313 (setq str (buffer-substring-no-properties (save-excursion
5314 (goto-char pos)
5315 (beginning-of-line)
5316 (forward-line 1)
5317 (point))
5318 (save-excursion
5319 (goto-char (point-max))
5320 (beginning-of-line)
5321 (point))))
5322 (delete-region pos (point-max)))
5323 (insert lastcmd))
5324 str))
5325
5326(defun matlab-shell-send-string (string)
5327 "Send STRING to the currently running matlab process."
5328 (if (not matlab-shell-echoes)
5329 (let ((proc (get-buffer-process (current-buffer))))
5330 (goto-char (point-max))
5331 (insert string)
5332 (set-marker (process-mark proc) (point))))
5333 (comint-send-string (get-buffer-process (current-buffer)) string))
5334
5335(defun matlab-url-at (p)
5336 "Return the matlab-url overlay at P, or nil."
5337 (let ((url nil) (o (matlab-overlays-at p)))
5338 (while (and o (not url))
5339 (setq url (matlab-overlay-get (car o) 'matlab-url)
5340 o (cdr o)))
5341 url))
5342
5343(defun matlab-url-stack-top-at (p)
5344 "Return the matlab-url overlay at P, or nil."
5345 (let ((url nil) (o (matlab-overlays-at p)))
5346 (while (and o (not url))
5347 (setq url (or (matlab-overlay-get (car o) 'first-in-error-stack)
5348 (matlab-overlay-get (car o) 'matlab-url))
5349 o (cdr o)))
5350 url))
5351
5352(defun matlab-shell-previous-matlab-url (&optional stacktop)
5353 "Find a previous occurrence of an overlay with a MATLAB URL.
5354If STACKTOP is non-nil, then also get the top of some stack, which didn't
5355show up in reverse order."
5356 (save-excursion
5357 (let ((url nil) (o nil) (p (point)))
5358 (while (and (not url)
5359 (setq p (matlab-previous-overlay-change p))
5360 (not (eq p (point-min))))
5361 (setq url
5362 (if stacktop
5363 (matlab-url-stack-top-at p)
5364 (matlab-url-at p))))
5365 url)))
5366
5367(defun matlab-find-other-window-file-line-column (ef el ec &optional debug)
5368 "Find file EF in other window and to go line EL and 1-basec column EC.
5369If DEBUG is non-nil, then setup GUD debugging features."
5370 (cond ((file-exists-p ef)
5371 nil);; keep ef the same
5372 ((file-exists-p (concat ef ".m"))
5373 (setq ef (concat ef ".m"))) ;; Displayed w/out .m?
5374 ((string-match ">" ef)
5375 (setq ef (concat (substring ef 0 (match-beginning 0)) ".m")))
5376 )
5377 (find-file-other-window ef)
5378 (goto-line (string-to-number el))
5379 (when debug
5380 (setq gud-last-frame (cons (buffer-file-name) (string-to-number el)))
5381 (gud-display-frame))
5382 (setq ec (string-to-number ec))
5383 (if (> ec 0) (forward-char (1- ec))))
5384
5385(defun matlab-find-other-window-via-url (url &optional debug)
5386 "Find other window using matlab URL and optionally set DEBUG cursor."
5387 (cond ((string-match "^error:\\(.*\\),\\([0-9]+\\),\\([0-9]+\\)$" url)
5388 (let ((ef (substring url (match-beginning 1) (match-end 1)))
5389 (el (substring url (match-beginning 2) (match-end 2)))
5390 (ec (substring url (match-beginning 3) (match-end 3))))
5391 (matlab-find-other-window-file-line-column ef el ec debug)))
5392 ((string-match "opentoline('\\([^']+\\)',\\([0-9]+\\),\\([0-9]+\\))" url)
5393 (let ((ef (substring url (match-beginning 1) (match-end 1)))
5394 (el (substring url (match-beginning 2) (match-end 2)))
5395 (ec (substring url (match-beginning 3) (match-end 3))))
5396 (matlab-find-other-window-file-line-column ef el ec debug)))
5397 ((string-match "^matlab: *\\(.*\\)$" url)
5398 (process-send-string
5399 (get-buffer-process gud-comint-buffer)
5400 (concat (substring url (match-beginning 1) (match-end 1)) "\n")))))
5401
5402(defun matlab-shell-last-error ()
5403 "In the MATLAB interactive buffer, find the last MATLAB error, and go there.
5404To reference old errors, put the cursor just after the error text."
5405 (interactive)
5406 (catch 'done
5407 (let ((url (matlab-shell-previous-matlab-url t)))
5408 (if url
5409 (progn (matlab-find-other-window-via-url url) (throw 'done nil))
5410 (save-excursion
5411 (end-of-line) ;; In case we are before the linenumber 1998/06/05 16:54sk
5412 (if (not (re-search-backward gud-matlab-error-regexp nil t))
5413 (error "No errors found!"))
5414 (let ((ef (buffer-substring-no-properties
5415 (match-beginning 2) (match-end 2)))
5416 (el (buffer-substring-no-properties
5417 (match-beginning 3) (match-end 3))))
5418 (matlab-find-other-window-file-line-column ef el "0")))))))
5419
5420(defun matlab-shell-html-click (e)
5421 "Go to the error at the location of event E."
5422 (interactive "e")
5423 (mouse-set-point e)
5424 (matlab-shell-html-go))
5425
5426(defun matlab-shell-html-go ()
5427 "Go to the error at the location `point'."
5428 (interactive)
5429 (let ((url (matlab-url-at (point))))
5430 (if url (matlab-find-other-window-via-url url))))
5431
5432(defun matlab-shell-dbstop-error ()
5433 "Stop on errors."
5434 (interactive)
5435 (comint-send-string (get-buffer-process (current-buffer))
5436 "dbstop if error\n"))
5437
5438(defun matlab-shell-dbclear-error ()
5439 "Don't stop on errors."
5440 (interactive)
5441 (comint-send-string (get-buffer-process (current-buffer))
5442 "dbclear if error\n"))
5443
5444(defun matlab-shell-demos ()
5445 "MATLAB demos."
5446 (interactive)
5447 (comint-send-string (get-buffer-process (current-buffer)) "demo\n"))
5448
5449(defun matlab-shell-close-figures ()
5450 "Close any open figures."
5451 (interactive)
5452 (comint-send-string (get-buffer-process (current-buffer)) "close all\n"))
5453
5454(defun matlab-shell-close-current-figure ()
5455 "Close current figure."
5456 (interactive)
5457 (comint-send-string (get-buffer-process (current-buffer)) "delete(gcf)\n"))
5458
5459(defun matlab-shell-exit ()
5460 "Exit MATLAB shell."
5461 (interactive)
5462 (comint-send-string (get-buffer-process (current-buffer)) "exit\n")
5463 (kill-buffer nil))
5464
5465
5466;;; matlab-shell based Topic Browser and Help =================================
5467
5468(defcustom matlab-shell-topic-mode-hook nil
5469 "*MATLAB shell topic hook."
5470 :group 'matlab-shell
5471 :type 'hook)
5472
5473(defvar matlab-shell-topic-current-topic nil
5474 "The currently viewed topic in a MATLAB shell topic buffer.")
5475
5476(defun matlab-shell-topic-browser ()
5477 "Create a topic browser by querying an active MATLAB shell using HELP.
5478Maintain state in our topic browser buffer."
5479 (interactive)
5480 ;; Reset topic browser if it doesn't exist.
5481 (if (not (get-buffer "*MATLAB Topic*"))
5482 (setq matlab-shell-topic-current-topic nil))
5483 (let ((b (get-buffer-create "*MATLAB Topic*")))
5484 (switch-to-buffer b)
5485 (if (string= matlab-shell-topic-current-topic "")
5486 nil
5487 (matlab-shell-topic-mode)
5488 (matlab-shell-topic-browser-create-contents ""))))
5489
5490(defvar matlab-shell-topic-mouse-face-keywords
5491 '(;; These are subtopic fields...
5492 ("^\\(\\w+/\\w+\\)[ \t]+-" 1 font-lock-reference-face)
5493 ;; These are functions...
5494 ("^[ \t]+\\(\\w+\\)[ \t]+-" 1 font-lock-function-name-face)
5495 ;; Here is a See Also line...
5496 ("[ \t]+See also "
5497 ("\\(\\w+\\)\\([,.]\\| and\\|$\\) *" nil nil (1 font-lock-reference-face))))
5498 "These are keywords we also want to put mouse-faces on.")
5499
5500(defvar matlab-shell-topic-font-lock-keywords
5501 (append matlab-shell-topic-mouse-face-keywords
5502 '(("^[^:\n]+:$" 0 font-lock-keyword-face)
5503 ;; These are subheadings...
5504 ("^[ \t]+\\([^.\n]+[a-zA-Z.]\\)$" 1 'underline)
5505 ))
5506 "Keywords useful for highlighting a MATLAB TOPIC buffer.")
5507
5508(defvar matlab-shell-help-font-lock-keywords
5509 (append matlab-shell-topic-mouse-face-keywords
5510 '(;; Function call examples
5511 ("[ \t]\\([A-Z]+\\)\\s-*=\\s-*\\([A-Z]+[0-9]*\\)("
5512 (1 font-lock-variable-name-face)
5513 (2 font-lock-function-name-face))
5514 ("[ \t]\\([A-Z]+[0-9]*\\)("
5515 (1 font-lock-function-name-face))
5516 ;; Parameters: Not very accurate, unfortunately.
5517 ("[ \t]\\([A-Z]+[0-9]*\\)("
5518 ("'?\\(\\w+\\)'?\\([,)]\\) *" nil nil
5519 (1 font-lock-variable-name-face))
5520 )
5521 ;; Reference uppercase words
5522 ("\\<\\([A-Z]+[0-9]*\\)\\>" 1 font-lock-reference-face)))
5523 "Keywords for regular help buffers.")
5524
5525;; View-major-mode is an emacs20 thing. This gives us a small compatibility
5526;; layer.
5527(if (not (fboundp 'view-major-mode)) (defalias 'view-major-mode 'view-mode))
5528
5529(define-derived-mode matlab-shell-help-mode
5530 view-major-mode "M-Help"
5531 "Major mode for viewing MATLAB help text.
5532Entry to this mode runs the normal hook `matlab-shell-help-mode-hook'.
5533
5534Commands:
5535\\{matlab-shell-help-mode-map}"
5536 (make-local-variable 'font-lock-defaults)
5537 (setq font-lock-defaults '((matlab-shell-help-font-lock-keywords)
5538 t nil ((?_ . "w"))))
5539 ;; This makes sure that we really enter font lock since
5540 ;; kill-all-local-variables is not used by old view-mode.
5541 (and (boundp 'global-font-lock-mode) global-font-lock-mode
5542 (not font-lock-mode) (font-lock-mode 1))
5543 (easy-menu-add matlab-shell-help-mode-menu matlab-shell-help-mode-map)
5544 (matlab-shell-topic-mouse-highlight-subtopics)
5545 )
5546
5547(define-key matlab-shell-help-mode-map [return] 'matlab-shell-topic-choose)
5548(define-key matlab-shell-help-mode-map "t" 'matlab-shell-topic-browser)
5549(define-key matlab-shell-help-mode-map "q" 'bury-buffer)
5550(define-key matlab-shell-help-mode-map
5551 [(control h) (control m)] matlab-help-map)
5552(if (string-match "XEmacs" emacs-version)
5553 (define-key matlab-shell-help-mode-map [button2] 'matlab-shell-topic-click)
5554 (define-key matlab-shell-help-mode-map [mouse-2] 'matlab-shell-topic-click))
5555
5556(easy-menu-define
5557 matlab-shell-help-mode-menu matlab-shell-help-mode-map
5558 "MATLAB shell topic menu"
5559 '("MATLAB Help"
5560 ["Describe This Command" matlab-shell-topic-choose t]
5561 "----"
5562 ["Describe Command" matlab-shell-describe-command t]
5563 ["Describe Variable" matlab-shell-describe-variable t]
5564 ["Command Apropos" matlab-shell-apropos t]
5565 ["Topic Browser" matlab-shell-topic-browser t]
5566 "----"
5567 ["Exit" bury-buffer t]))
5568
5569(define-derived-mode matlab-shell-topic-mode
5570 matlab-shell-help-mode "M-Topic"
5571 "Major mode for browsing MATLAB HELP topics.
5572The output of the MATLAB command HELP with no parameters creates a listing
5573of known help topics at a given installation. This mode parses that listing
5574and allows selecting a topic and getting more help for it.
5575Entry to this mode runs the normal hook `matlab-shell-topic-mode-hook'.
5576
5577Commands:
5578\\{matlab-shell-topic-mode-map}"
5579 (setq font-lock-defaults '((matlab-shell-topic-font-lock-keywords)
5580 t t ((?_ . "w"))))
5581 (if (string-match "XEmacs" emacs-version)
5582 (setq mode-motion-hook 'matlab-shell-topic-highlight-line))
5583 (easy-menu-add matlab-shell-topic-mode-menu matlab-shell-topic-mode-map)
5584 )
5585
5586(easy-menu-define
5587 matlab-shell-topic-mode-menu matlab-shell-topic-mode-map
5588 "MATLAB shell topic menu"
5589 '("MATLAB Topic"
5590 ["Select This Topic" matlab-shell-topic-choose t]
5591 ["Top Level Topics" matlab-shell-topic-browser t]
5592 "----"
5593 ["Exit" bury-buffer t]))
5594
5595(defun matlab-shell-topic-browser-create-contents (subtopic)
5596 "Fill in a topic browser with the output from SUBTOPIC."
5597 (toggle-read-only -1)
5598 (erase-buffer)
5599 (insert (matlab-shell-collect-command-output (concat "help " subtopic)))
5600 (goto-char (point-min))
5601 (forward-line 1)
5602 (delete-region (point-min) (point))
5603 (setq matlab-shell-topic-current-topic subtopic)
5604 (if (not (string-match "XEmacs" emacs-version))
5605 (matlab-shell-topic-mouse-highlight-subtopics))
5606 (toggle-read-only 1)
5607 )
5608
5609(defun matlab-shell-topic-click (e)
5610 "Click on an item in a MATLAB topic buffer we want more information on.
5611Must be bound to event E."
5612 (interactive "e")
5613 (mouse-set-point e)
5614 (matlab-shell-topic-choose))
5615
5616(defun matlab-shell-topic-choose ()
5617 "Choose the topic to expand on that is under the cursor.
5618This can fill the topic buffer with new information. If the topic is a
5619command, use `matlab-shell-describe-command' instead of changing the topic
5620buffer."
5621 (interactive)
5622 (let ((topic nil) (fun nil) (p (point)))
5623 (save-excursion
5624 (beginning-of-line)
5625 (if (looking-at "^\\w+/\\(\\w+\\)[ \t]+-")
5626 (setq topic (match-string 1))
5627 (if (looking-at "^[ \t]+\\(\\(\\w\\|_\\)+\\)[ \t]+-")
5628 (setq fun (match-string 1))
5629 (if (and (not (looking-at "^[ \t]+See also"))
5630 (not (save-excursion (forward-char -2)
5631 (looking-at ",$"))))
5632 (error "You did not click on a subtopic, function or reference")
5633 (goto-char p)
5634 (forward-word -1)
5635 (if (not (looking-at "\\(\\(\\w\\|_\\)+\\)\\([.,]\\| and\\|\n\\)"))
5636 (error "You must click on a reference")
5637 (setq topic (match-string 1)))))))
5638 (message "Opening item %s..." (or topic fun))
5639 (if topic
5640 (matlab-shell-topic-browser-create-contents (downcase topic))
5641 (matlab-shell-describe-command fun))
5642 ))
5643
5644(defun matlab-shell-topic-mouse-highlight-subtopics ()
5645 "Put a `mouse-face' on all clickable targets in this buffer."
5646 (save-excursion
5647 (let ((el matlab-shell-topic-mouse-face-keywords))
5648 (while el
5649 (goto-char (point-min))
5650 (while (re-search-forward (car (car el)) nil t)
5651 (let ((cd (car (cdr (car el)))))
5652 (if (numberp cd)
5653 (put-text-property (match-beginning cd) (match-end cd)
5654 'mouse-face 'highlight)
5655 (while (re-search-forward (car cd) nil t)
5656 (put-text-property (match-beginning (car (nth 3 cd)))
5657 (match-end (car (nth 3 cd)))
5658 'mouse-face 'highlight)))))
5659 (setq el (cdr el))))))
5660
5661(defun matlab-shell-topic-highlight-line (event)
5662 "A value of `mode-motion-hook' which will highlight topics under the mouse.
5663EVENT is the user mouse event."
5664 ;; XEMACS only function
5665 (let* ((buffer (event-buffer event))
5666 (point (and buffer (event-point event))))
5667 (if (and buffer (not (eq buffer mouse-grabbed-buffer)))
5668 (save-excursion
5669 (save-window-excursion
5670 (set-buffer buffer)
5671 (mode-motion-ensure-extent-ok event)
5672 (if (not point)
5673 (detach-extent mode-motion-extent)
5674 (goto-char point)
5675 (end-of-line)
5676 (setq point (point))
5677 (beginning-of-line)
5678 (if (or (looking-at "^\\w+/\\(\\w+\\)[ \t]+-")
5679 (looking-at "^[ \t]+\\(\\(\\w\\|_\\)+\\)[ \t]+-"))
5680 (set-extent-endpoints mode-motion-extent (point) point)
5681 (detach-extent mode-motion-extent))))))))
5682
5683
5684;;; M File path stuff =========================================================
5685
5686(defun matlab-mode-determine-mfile-path ()
5687 "Create the path in `matlab-mode-install-path'."
5688 (let ((path (file-name-directory matlab-shell-command)))
5689 ;; if we don't have a path, find the MATLAB executable on our path.
5690 (if (not path)
5691 (let ((pl exec-path))
5692 (while (and pl (not path))
5693 (if (and (file-exists-p (concat (car pl) "/" matlab-shell-command))
5694 (not (car (file-attributes (concat (car pl) "/"
5695 matlab-shell-command)))))
5696 (setq path (car pl)))
5697 (setq pl (cdr pl)))))
5698 (if (not path)
5699 nil
5700 ;; When we find the path, we need to massage it to identify where
5701 ;; the M files are that we need for our completion lists.
5702 (if (string-match "/bin$" path)
5703 (setq path (substring path 0 (match-beginning 0))))
5704 ;; Everything stems from toolbox (I think)
5705 (setq path (concat path "/toolbox/")))
5706 path))
5707
5708(defcustom matlab-mode-install-path (list (matlab-mode-determine-mfile-path))
5709 "Base path pointing to the locations of all the m files used by matlab.
5710All directories under each element of `matlab-mode-install-path' are
5711checked, so only top level toolbox directories need be added.
5712Paths should be added in the order in which they should be searched."
5713 :group 'matlab-shell
5714 :type '(repeat (string :tag "Path: ")))
5715
5716(defun matlab-find-file-under-path (path filename)
5717 "Return the pathname or nil of PATH under FILENAME."
5718 (if (file-exists-p (concat path filename))
5719 (concat path filename)
5720 (let ((dirs (if (file-directory-p path)
5721 ;; Not checking as a directory first fails on XEmacs
5722 ;; Stelios Kyriacou <kyriacou@cbmv.jhu.edu>
5723 (directory-files path t nil t)))
5724 (found nil))
5725 (while (and dirs (not found))
5726 (if (and (car (file-attributes (car dirs)))
5727 ;; require directory readable
5728 (file-readable-p (car dirs))
5729 ;; don't redo our path names
5730 (not (string-match "/\\.\\.?$" (car dirs)))
5731 ;; don't find files in object directories.
5732 (not (string-match "@" (car dirs))))
5733 (setq found
5734 (matlab-find-file-under-path (concat (car dirs) "/")
5735 filename)))
5736 (setq dirs (cdr dirs)))
5737 found)))
5738
5739(defun matlab-find-file-on-path (filename)
5740 "Find FILENAME on the current MATLAB path.
5741The MATLAB path is determined by `matlab-mode-install-path' and the
5742current directory. You must add user-installed paths into
5743`matlab-mode-install-path' if you would like to have them included."
5744 (interactive
5745 (list
5746 (let ((default (matlab-read-word-at-point)))
5747 (if default
5748 (let ((s (read-string (concat "File (default " default "): "))))
5749 (if (string= s "") default s))
5750 (read-string "File: ")))))
5751 (if (string= filename "")
5752 (error "You must specify an M file"))
5753 (if (not (string-match "\\.m$" filename))
5754 (setq filename (concat filename ".m")))
5755 (let ((fname nil)
5756 (dirs matlab-mode-install-path))
5757 (if (file-exists-p (concat default-directory filename))
5758 (setq fname (concat default-directory filename)))
5759 (while (and (not fname) dirs)
5760 (if (stringp (car dirs))
5761 (progn
5762 (message "Searching for %s in %s" filename (car dirs))
5763 (setq fname (matlab-find-file-under-path (car dirs) filename))))
5764 (setq dirs (cdr dirs)))
5765 (if fname (find-file fname)
5766 (error "File %s not found on any known paths. \
5767Check `matlab-mode-install-path'" filename))))
5768
5769(defun matlab-find-file-click (e)
5770 "Find the file clicked on with event E on the current path."
5771 (interactive "e")
5772 (mouse-set-point e)
5773 (let ((f (matlab-read-word-at-point)))
5774 (if (not f) (error "To find an M file, click on a word"))
5775 (matlab-find-file-on-path f)))
5776
5777
5778;;; matlab-mode debugging =====================================================
5779
5780(defun matlab-show-line-info ()
5781 "Display type and attributes of current line. Used in debugging."
5782 (interactive)
5783 (let ((msg "line-info:")
5784 (indent (matlab-calculate-indentation (current-indentation)))
5785 (nexti (matlab-next-line-indentation)))
5786 (setq msg (concat msg
5787 " Line type: " (symbol-name (car indent))
5788 " This Line: " (int-to-string (nth 1 indent))
5789 " Next Line: " (int-to-string nexti)))
5790 (if (matlab-lattr-cont)
5791 (setq msg (concat msg " w/cont")))
5792 (if (matlab-lattr-comm)
5793 (setq msg (concat msg " w/comm")))
5794 (message msg)))
5795
5796(provide 'matlab)
5797
5798;;; matlab.el ends here