forked from abo-abo/matlab-mode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
matlab.el
4321 lines (4015 loc) · 178 KB
/
matlab.el
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; matlab.el --- major mode for MATLAB(R) dot-m files
;;
;; Author: Matt Wette <mwette@alumni.caltech.edu>,
;; Eric M. Ludlam <eludlam@mathworks.com>
;; Maintainer: Eric M. Ludlam <eludlam@mathworks.com>
;; Created: 04 Jan 91
;; Keywords: MATLAB(R)
;; Version:
;;
;; Copyright (C) 2004-2010, 2014 The Mathworks, Inc
;; Copyright (C) 1997-2004 Eric M. Ludlam: The MathWorks, Inc
;; Copyright (C) 1991-1997 Matthew R. Wette
;;
;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 2, or (at your option)
;; any later version.
;;
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs; see the file COPYING. If not, write to
;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
;;
;;; Commentary:
;;
;; This major mode for GNU Emacs provides support for editing MATLAB(R) dot-m
;; files. It automatically indents for block structures (including nested
;; functions), line continuations (e.g., ...), and comments.
;;
;; Additional features include auto-fill including auto-additions of
;; ellipsis for commands, and even strings. Block/end construct
;; highlighting as you edit. Primitive code-verification and
;; identification. Templates and other code editing functions.
;; Advanced symbol completion. Code highlighting via font-lock.
;; There are many navigation commands that let you move across blocks
;; of code at different levels.
;;
;; Lastly, there is support for running MATLAB(R) in an Emacs buffer,
;; with full shell history and debugger support (when used with the db
;; commands.) The shell can be used as an online help while editing
;; code, providing help on functions, variables, or running arbitrary
;; blocks of code from the buffer you are editing.
;;; Code:
(defconst matlab-mode-version "3.3.4"
"Current version of MATLAB(R) mode.")
(require 'easymenu)
(require 'derived)
(require 'hydra)
(require 'gdb-mi)
(require 'matlab-debug)
(eval-when-compile
(require 'gud)
(require 'comint)
(require 'shell))
;;* Customize
(defgroup matlab nil
"MATLAB(R) mode."
:prefix "matlab-"
:group 'languages)
(defcustom matlab-indent-level 4
"The basic indentation amount in `matlab-mode'."
:type 'integer)
(defcustom matlab-cont-level 4
"Basic indentation after continuation if no other methods are found."
:type 'integer)
(defcustom matlab-cont-requires-ellipsis t
"Specify if ellipses are required at the end of a line for continuation.
Future versions of Matlab may not require ellipses ... , so a heuristic
determining if there is to be continuation is used instead."
:type 'integer)
(defcustom matlab-case-level '(2 . 2)
"How far to indent case/otherwise statements in a switch.
This can be an integer, which is the distance to indent the CASE and
OTHERWISE commands, and how far to indent commands appearing in CASE
and OTHERWISE blocks. It can also be a cons cell which is of form
(CASEINDENT . COMMANDINDENT)
where CASEINDENT is the indentation of the CASE and OTHERWISE
statements, and COMMANDINDENT is the indentation of commands appearing
after the CASE or OTHERWISE command.
Note: Currently a bug exists if:
CASEINDENT+COMMANDINDENT != `matlab-indent-level'
so if you customize these variables, follow the above rule, and you
should be ok."
:type 'sexp)
(defcustom matlab-indent-function-body t
"If non-nil, indent body of function.
If the global value is nil, do not indent function bodies.
If the global value is t, always indent function bodies.
If the global value is 'guess, then the local value will be set to
either nil or t when the MATLAB mode is started in a buffer based on the
file's current indentation.
If the global value is 'MathWorks-Standard, then the local value is not
changed, and functions are indented based on `matlab-functions-have-end'."
:type '(choice (const :tag "Always" t)
(const :tag "Never" nil)
(const :tag "Guess" 'guess)
(const :tag "MathWorks Standard" 'MathWorks-Standard)))
(make-variable-buffer-local 'matlab-indent-function-body)
(defcustom matlab-functions-have-end nil
"If non-nil, functions-have-end minor mode is on by default."
:type 'boolean)
(make-variable-buffer-local 'matlab-functions-have-end)
(defun matlab-toggle-functions-have-end ()
(interactive)
(matlab-toggle-functions-have-end-minor-mode))
;; The following minor mode is on if and only if the above variable is true;
(define-minor-mode matlab-functions-have-end-minor-mode
"Toggle functions-have-end minor mode, indicating function/end pairing."
nil
(condition-case nil ;; avoid parse error on xemacs
(eval (read "#(\" function...end\" 0 15 (face (font-lock-keyword-face) fontified t))"))
(error " function...end"))
nil ; empty mode-map
;; body of matlab-functions-have-end-minor-mode
(if matlab-functions-have-end-minor-mode
(setq matlab-functions-have-end t)
(setq matlab-functions-have-end nil)))
(defun matlab-do-functions-have-end-p ()
"Non-nil if the first function in the current buffer terminates with end."
(save-excursion
(goto-char (point-min))
(if (re-search-forward matlab-defun-regex nil t)
(let ((matlab-functions-have-end t))
(beginning-of-line)
(condition-case nil
(progn (matlab-forward-sexp) t)
(error nil)))
nil)))
(defun matlab-toggle-functions-have-end-minor-mode ()
(matlab-functions-have-end-minor-mode)
(if (and matlab-functions-have-end-minor-mode (not (eq major-mode 'matlab-mode)))
(progn
(matlab-functions-have-end-minor-mode -1)
(error "functions-have-end minor mode is only for MATLAB Major mode")))
(setq matlab-functions-have-end matlab-functions-have-end-minor-mode))
(defun matlab-indent-function-body-p ()
"Non-nil if functions bodies are indented.
See `matlab-indent-function-body' variable."
(if (eq matlab-indent-function-body 'MathWorks-Standard)
;; Dec '09
;; The MathWorks standard is the same as if functions have end.
matlab-functions-have-end
;; Else, just return the variable.
matlab-indent-function-body))
(defcustom matlab-indent-past-arg1-functions "[sg]et\\(_param\\)?\\|waitfor"
"Regex describing functions whose first arg is special.
This specialness means that all following parameters which appear on
continued lines should appear indented to line up with the second
argument, not the first argument."
:type 'string)
(defcustom matlab-arg1-max-indent-length 15
"The maximum length to indent when indenting past arg1.
If arg1 is exceptionally long, then only this number of characters
will be indented beyond the open paren starting the parameter list."
:type 'integer)
(defcustom matlab-maximum-indents '( ;; = is a convenience. Don't go too far
(?= . (10 . 4))
;; Fns should provide hard limits
(?\( . 50)
;; Matrix/Cell arrays
(?\[ . 20)
(?\{ . 20))
"Alist of maximum indentations when lining up code.
Each element is of the form (CHAR . INDENT) where char is a character
the indent engine is using, and INDENT is the maximum indentation
allowed. Indent could be of the form (MAXIMUM . INDENT), where
MAXIMUM is the maximum allowed calculated indent, and INDENT is the
amount to use if MAXIMUM is reached."
:type '(repeat (cons
(character :tag "Open List Character")
(sexp :tag "Number (max) or cons (max indent)"))))
(defcustom matlab-auto-fill t
"If true, set variable `auto-fill-function' to our function at startup."
:type 'boolean)
(defcustom matlab-fill-fudge 10
"Number of characters around `fill-column' we can fudge filling.
Basically, there are places that are very convenient to fill at, but
might not be the closest fill spot, or occur after `fill-column'.
If they occur within this fudge factor, we will use them.
Also, if none of the above occur, and we find a symbol to break at,
but an open paren (group) starts or ends within this fudge factor,
move there to boost the amount of fill leverage we can get."
:type 'integer)
(defcustom matlab-fill-fudge-hard-maximum 79
"The longest line allowed when auto-filling code.
This overcomes situations where the `fill-column' plus the
`matlab-fill-fudge' is greater than some hard desired limit."
:type 'integer)
(defcustom matlab-elipsis-string "..."
"Text used to perform continuation on code lines.
This is used to generate and identify continuation lines.")
(defcustom matlab-fill-code nil
"If true, `auto-fill-mode' causes code lines to be automatically continued."
:type 'boolean)
(defcustom matlab-fill-count-ellipsis-flag t
"Non-nil means to count the ellipsis when auto filling.
This effectively shortens the `fill-column' by the length of
`matlab-elipsis-string'."
:type 'boolean)
(defcustom matlab-fill-strings-flag t
"Non-nil means that when auto-fill is on, strings are broken across lines.
If `matlab-fill-count-ellipsis-flag' is non nil, this shortens the
`fill-column' by the length of `matlab-elipsis-string'.")
(defcustom matlab-comment-column 40
"The goal comment column in `matlab-mode' buffers."
:type 'integer)
(defcustom matlab-comment-anti-indent 0
"Amount of anti-indentation to use for comments in relation to code."
:type 'integer)
(defcustom matlab-comment-line-s "% "
"String to start comment on line by itself."
:type 'string)
(defcustom matlab-comment-on-line-s "% "
"String to start comment on line with code."
:type 'string)
(defcustom matlab-verify-on-save-flag t
"Non-nil means to verify M whenever we save a file."
:type 'boolean)
(defcustom matlab-mode-verify-fix-functions
'(matlab-mode-vf-functionname matlab-mode-vf-classname)
"List of function symbols which perform a verification and fix to M code.
Each function gets no arguments, and returns nothing. They can move
point, but it will be restored for them."
:type '(repeat (choice :tag "Function: "
'(matlab-mode-vf-functionname
matlab-mode-vf-classname
matlab-mode-vf-block-matches-forward
matlab-mode-vf-block-matches-backward
matlab-mode-vf-quiesce-buffer))))
(defcustom matlab-block-verify-max-buffer-size 50000
"Largest buffer size allowed for block verification during save."
:type 'integer)
(defcustom matlab-mode-hook nil
"List of functions to call on entry to MATLAB mode."
:type 'hook)
(defcustom matlab-return-add-semicolon nil
"If non nil, check to see a semicolon is needed when RET is pressed."
:type 'boolean)
(make-variable-buffer-local 'matlab-return-add-semicolon)
(defcustom matlab-change-current-directory nil
"If non nil, make file's directory the current directory when
evaluating it."
:type 'boolean)
(make-variable-buffer-local 'matlab-change-current-directory)
(defface matlab-region-face
'((t :inherit region))
"Face used to highlight a matlab region.")
(defvar matlab-unterminated-string-face 'matlab-unterminated-string-face
"Self reference for unterminated string face.")
(defvar matlab-simulink-keyword-face 'matlab-simulink-keyword-face
"Self reference for simulink keywords.")
(defvar matlab-nested-function-keyword-face 'matlab-nested-function-keyword-face
"Self reference for nested function/end keywords.")
(defvar matlab-cross-function-variable-face 'matlab-cross-function-variable-face
"Self reference for cross-function variables.")
(defvar matlab-cellbreak-face 'matlab-cellbreak-face
"Self reference for cellbreaks.")
(defface matlab-unterminated-string-face
'((t :inherit font-lock-string-face :underline t))
"Face used to highlight unterminated strings.")
(defface matlab-simulink-keyword-face
'((t :inherit font-lock-type-face :underline t))
"Face used to highlight simulink specific functions.")
(defface matlab-nested-function-keyword-face
'((t :inherit default :slant italic))
"Face to use for cross-function variables.")
(defface matlab-cross-function-variable-face
'((t :inherit default :weight bold :slant italic))
"Face to use for cross-function variables.")
(defface matlab-cellbreak-face
'((t
:inherit font-lock-comment-face
:overline t
:bold t))
"Face to use for cellbreak %% lines.")
;;* Variables
(defvar matlab-mode-syntax-table
(let ((st (make-syntax-table (standard-syntax-table))))
(modify-syntax-entry ?_ "w" st)
;; (modify-syntax-entry ?% "<" st)
;; (modify-syntax-entry ?\n ">" st)
(modify-syntax-entry ?\\ "." st)
(modify-syntax-entry ?\t " " st)
(modify-syntax-entry ?+ "." st)
(modify-syntax-entry ?- "." st)
(modify-syntax-entry ?* "." st)
(modify-syntax-entry ?\' "." st)
(modify-syntax-entry ?/ "." st)
(modify-syntax-entry ?= "." st)
(modify-syntax-entry ?< "." st)
(modify-syntax-entry ?> "." st)
(modify-syntax-entry ?& "." st)
(modify-syntax-entry ?| "." st)
st)
"The syntax table used in `matlab-mode' buffers.")
(defvar matlab-mode-special-syntax-table
(let ((st (copy-syntax-table matlab-mode-syntax-table)))
;; Make _ a part of words so we can skip them better
(modify-syntax-entry ?_ "w" st)
st)
"The syntax table used when navigating blocks.")
(defvar matlab-mode-abbrev-table nil
"The abbrev table used in `matlab-mode' buffers.")
(define-abbrev-table 'matlab-mode-abbrev-table ())
;;* Keybindings
(defvar matlab-insert-map
(let ((km (make-sparse-keymap)))
;; Not really inserts, but auto coding stuff
(define-key km "\C-s" 'matlab-ispell-strings)
(define-key km "\C-c" 'matlab-ispell-comments)
km)
"Keymap used for inserting simple texts based on context.")
(defvar matlab-mode-map
(let ((km (make-sparse-keymap)))
(define-key km (kbd "RET") 'matlab-return)
(define-key km "%" 'matlab-electric-comment)
(define-key km [(control c) return] 'matlab-comment-return)
(define-key km [(control c) (control c)] matlab-insert-map)
(define-key km [(control c) (control f)] 'matlab-fill-comment-line)
(define-key km [(control c) (control j)] 'matlab-justify-line)
(define-key km [(control c) (control q)] 'matlab-fill-region)
(define-key km [(control c) (control s)] 'matlab-shell-save-and-go)
(define-key km [(control c) (control r)] 'matlab-shell-run-region)
(define-key km [(meta control return)] 'matlab-shell-run-cell)
(define-key km [(control c) (control t)] 'matlab-show-line-info)
(define-key km [(control c) ?.] 'matlab-find-file-on-path)
(define-key km [(control j)] 'matlab-linefeed)
(define-key km "\M-\r" 'newline)
(define-key km [(meta \;)] 'matlab-comment)
(define-key km [(meta q)] 'matlab-fill-paragraph)
(define-key km [(meta a)] 'matlab-beginning-of-command)
(define-key km [(meta e)] 'matlab-end-of-command)
(define-key km [(meta j)] 'matlab-comment-line-break-function)
(define-key km [(meta s)] 'matlab-show-matlab-shell-buffer)
(define-key km (kbd "C-M-f") 'matlab-forward-sexp)
(define-key km (kbd "C-M-b") 'matlab-backward-sexp)
(define-key km [(meta control q)] 'matlab-indent-sexp)
(if (string-match "XEmacs" emacs-version)
(define-key km [(control meta button1)] 'matlab-find-file-click)
(define-key km [(control meta mouse-2)] 'matlab-find-file-click))
(define-key km [left-fringe mouse-1] 'matlab-dbg-breakpoint-toggle)
(define-key km (kbd "M-.") 'matlab-goto-symbol)
(define-key km (kbd "M-,") 'pop-tag-mark)
;; (define-key km (kbd "C-o") 'hydra-matlab/body)
km)
"The keymap used in `matlab-mode'.")
;;* Font locking keywords
(defvar matlab-string-start-regexp "\\(^\\|[^]})a-zA-Z0-9_.']\\)"
"Regexp used to represent the character before the string char '.
The ' character has restrictions on what starts a string which is needed
when attempting to understand the current context.")
;; To quote a quote, put two in a row, thus we need an anchored
;; first quote. In addition, we don't want to color strings in comments.
(defvar matlab-string-end-regexp "[^'\n]*\\(''[^'\n]*\\)*'"
"Regexp used to represent the character pattern for ending a string.
The ' character can be used as a transpose, and can transpose transposes.
Therefore, to end, we must check all that goop.")
(defun matlab-font-lock-string-match-normal (limit)
"When font locking strings, call this function for normal strings.
Argument LIMIT is the maximum distance to scan."
(matlab-font-lock-string-match-here
(concat matlab-string-start-regexp
"\\('" matlab-string-end-regexp "\\)"
"\\([^']\\|$\\)")
limit))
(defun matlab-font-lock-string-match-unterminated (limit)
"When font locking strings, call this function for normal strings.
Argument LIMIT is the maximum distance to scan."
(matlab-font-lock-string-match-here
(concat matlab-string-start-regexp "\\('[^'\n]*\\(''[^'\n]*\\)*\\)$")
limit))
(defun matlab-font-lock-string-match-here (regex limit)
"When font-locking strings, call this function to determine a match.
Argument REGEX is the expression to scan for. Match 2 must be the string.
Argument LIMIT is the maximum distance to scan."
(let (e)
(while (and (re-search-forward regex limit t)
(progn
;; This gets us out of a comment after the string.
(setq e (match-end 2))
(goto-char (match-beginning 2))
(prog1
(or (matlab-cursor-in-comment)
(if (bolp) nil
(save-excursion
(forward-char -1)
(matlab-cursor-in-string))))
(goto-char e))))
(setq e nil))
(if (not e)
nil
(goto-char e)
t)))
(defun matlab-font-lock-comment-match (limit)
"When font-locking comments, call this function to determine a match.
Argument LIMIT is the maximum distance to scan."
(let (e)
(while (and (re-search-forward "\\(%[^%\n]*\\)" limit t)
(progn
(setq e (match-end 1))
(member (get-text-property (match-beginning 0) 'face)
'(font-lock-string-face
matlab-unterminated-string-face))))
(setq e nil))
(if (not e)
nil
(goto-char e)
t)))
(defun matlab-font-lock-nested-function-keyword-match (limit)
"Find next nested function/end keyword for font-lock.
Argument LIMIT is the maximum distance to search."
;; Because of the way overlays are setup, the cursor will be sitting
;; on either a "function" or "end" keyword.
(catch 'result
(let ((pos (point))
overlays)
(while (< pos limit)
(setq overlays (overlays-at pos))
(while overlays
(let ((overlay (car overlays)))
(when (overlay-get overlay 'nested-function)
(when (= pos (overlay-start overlay))
(goto-char pos)
;; The following line presumably returns true.
(throw 'result (re-search-forward "function" (+ pos 8) t)))
(let ((end-of-overlay (- (overlay-end overlay) 3)))
(when (<= pos end-of-overlay)
(goto-char end-of-overlay)
(throw 'result
(re-search-forward "end" (+ end-of-overlay 3) t))))))
(setq overlays (cdr overlays)))
(setq pos (next-overlay-change pos)))
;; no matches, stop
nil)))
(defun matlab-font-lock-cross-function-variables-match (limit)
"Find next cross-function variable for font-lock.
Argument LIMIT is the maximum distance to search."
(catch 'result
(let ((pos (point))
overlays variables)
(while (< pos limit)
(let ((overlays (overlays-at pos)))
(while overlays
(let ((overlay (car overlays)))
(setq variables (overlay-get
overlay 'cross-function-variables))
(if variables
(progn
(goto-char pos)
(setq pos (min limit (overlay-end overlay)))
(if (re-search-forward variables pos t)
(progn
(throw 'result t))))))
(setq overlays (cdr overlays))))
(setq pos (next-overlay-change pos)))
;; no matches, stop
nil)))
(defun matlab-find-block-comments (limit)
"Find code that is commented out with %{ until %}.
Argument LIMIT is the maximum distance to search."
(if (and (< (point) limit)
(re-search-forward "%{" limit t))
(let ((b1 (match-beginning 0))
(e1 (match-end 0))
(b2 nil) (e2 nil)
(b3 nil) (e3 nil))
(goto-char b1)
(forward-char -1)
(when (not (matlab-cursor-in-comment))
(setq b2 (re-search-forward "%}" limit t))
(when b2
(setq b2 (match-beginning 0)
e2 (match-end 0))
(set-match-data
(list b1 e2 ; full match
b1 e2 ; the full comment
b1 e1 ; the block start
b2 e2 ; the block end
))
t)))))
(defcustom matlab-keyword-list '("global" "persistent" "for" "parfor" "while"
"spmd" "if" "elseif" "else"
"endfunction" "return" "break" "continue"
"switch" "case" "otherwise" "try"
"catch" "tic" "toc"
;; MCOS keywords
"classdef" "properties" "methods" "enumeration")
"List of keywords for MATLAB used in highlighting.
Customizing this variable is only useful if `regexp-opt' is available."
:type '(repeat (string :tag "Keyword: ")))
(defcustom matlab-handle-graphics-list '("figure" "axes" "axis" "line"
"surface" "patch" "text" "light"
"image" "set" "get" "uicontrol"
"uimenu" "uitoolbar"
"uitoggletool" "uipushtool"
"uicontext" "uicontextmenu"
"setfont" "setcolor")
"List of handle graphics functions used in highlighting.
Customizing this variable is only useful if `regexp-opt' is available."
:type '(repeat (string :tag "HG Keyword: ")))
;; font-lock keywords
(defvar matlab-font-lock-keywords
(list
;; String quote chars are also used as transpose, but only if directly
;; after characters, numbers, underscores, or closing delimiters.
'(matlab-font-lock-string-match-normal 2 font-lock-string-face)
;; A string with no termination is not currently highlighted.
;; This will show that the string needs some attention.
'(matlab-font-lock-string-match-unterminated
2 matlab-unterminated-string-face)
;; Comments must occur after the string, that way we can check to see
;; if the comment start char has occurred inside our string. (EL)
'(matlab-font-lock-comment-match 1 font-lock-comment-face)
;; Various pragmas should be in different colors.
;; I think pragmas are always lower case?
'("%#\\([a-z]+\\)" (1 'bold prepend))
;; General keywords
(list
(if (fboundp 'regexp-opt)
(concat "\\<\\(" (regexp-opt matlab-keyword-list) "\\)\\>")
;; Original hard-coded value for pre Emacs 20.1
"\\<\\(break\\|ca\\(se\\|tch\\)\\|e\\(lse\\(\\|if\\)\\|ndfunction\\)\
\\|\\(par\\)?for\\|spmd\\|global\\|if\\|otherwise\\|return\\|switch\\|try\\|while\\|tic\\|toc\\)\\>")
'(0 font-lock-keyword-face))
;; The end keyword is only a keyword when not used as an array
;; dereferencing part.
'("\\(^\\|[;,]\\)[ \t]*\\(end\\)\\b"
2 (if (matlab-valid-end-construct-p) font-lock-keyword-face nil))
;; block comments need to be commented out too!
'(matlab-find-block-comments
(1 font-lock-comment-face prepend) ; commented out
(2 'underline prepend)
(3 'underline prepend) ;the comment parts
)
;; Cell mode breaks get special treatment
'("^\\s-*\\(%%[^\n]*\n\\)" (1 matlab-cellbreak-face append))
;; Highlight cross function variables
'(matlab-font-lock-cross-function-variables-match
(1 matlab-cross-function-variable-face prepend))
;; Highlight nested function/end keywords
'(matlab-font-lock-nested-function-keyword-match
(0 matlab-nested-function-keyword-face prepend))
;; The global keyword defines some variables. Mark them.
'("^\\s-*global\\s-+"
("\\(\\w+\\)\\(\\s-*=[^,; \t\n]+\\|[, \t;]+\\|$\\)"
nil nil (1 font-lock-variable-name-face)))
;; Handle graphics stuff
(list
(if (fboundp 'regexp-opt)
(concat "\\<\\(" (regexp-opt matlab-handle-graphics-list) "\\)\\>")
;; The original regular expression for pre Emacs 20.1
"\\<\\(ax\\(es\\|is\\)\\|figure\\|get\\|image\\|li\\(ght\\|ne\\)\\|\
patch\\|s\\(et\\(\\|color\\|font\\)\\|urface\\)\\|text\\|\
ui\\(cont\\(ext\\(\\|menu\\)\\|rol\\)\\|menu\\|\
\\(toggle\\|push\\)tool\\|toolbar\\)\\)\\>")
'(0 font-lock-type-face)))
"Expressions to highlight in MATLAB mode.")
(defconst matlab-function-arguments
"\\(([^)]*)\\)?\\s-*\\([,;\n%]\\|$\\)")
(defvar matlab-gaudy-font-lock-keywords
(append
matlab-font-lock-keywords
(list
;; defining a function, a (possibly empty) list of assigned variables,
;; function name, and an optional (possibly empty) list of input variables
(list (concat "^\\s-*\\(function\\)\\>[ \t\n.]*"
"\\(\\[[^]]*\\]\\|\\sw+\\)[ \t\n.]*"
"=[ \t\n.]*\\(\\sw+\\)[ \t\n.]*"
matlab-function-arguments)
'(1 font-lock-keyword-face append)
'(2 font-lock-variable-name-face append)
'(3 font-lock-function-name-face append))
;; defining a function, a function name, and an optional (possibly
;; empty) list of input variables
(list (concat "^\\s-*\\(function\\)[ \t\n.]+"
"\\(\\sw+\\)[ \t\n.]*"
matlab-function-arguments)
'(1 font-lock-keyword-face append)
'(2 font-lock-function-name-face append))
;; Anchor on the function keyword, highlight params
(list (concat "^\\s-*function\\>[ \t\n.]*"
"\\(\\(\\[[^]]*\\]\\|\\sw+\\)[ \t\n.]*=[ \t\n.]*\\)?"
"\\sw+\\s-*(")
'("\\s-*\\(\\sw+\\)\\s-*[,)]" nil nil
(1 font-lock-variable-name-face)))
;; I like variables for FOR loops
'("\\<\\(for\\|parfor\\)\\s-+\\(\\sw+\\)\\s-*=\\s-*\
\\(\\([^\n,;%(]+\\|([^\n%)]+)\\)+\\)"
(1 font-lock-keyword-face)
(2 font-lock-variable-name-face append)
(3 font-lock-reference-face append))
;; Items after a switch statements are cool
'("\\<\\(case\\|switch\\)\\s-+\\({[^}\n]+}\\|[^,%\n]+\\)"
(1 font-lock-keyword-face) (2 font-lock-reference-face))
;; How about a few matlab constants such as pi, infinity, and sqrt(-1)?
;; The ^>> is in case I use this in an interactive mode someday
'("\\<\\(eps\\|pi\\|inf\\|Inf\\|NaN\\|nan\\|ans\\|i\\|j\\|^>>\\)\\>"
1 font-lock-reference-face)
'("\\<[0-9]\\.?\\(i\\|j\\)\\>" 1 font-lock-reference-face)
;; Define these as variables since this is about as close
;; as matlab gets to variables
(list (concat "\\<" matlab-indent-past-arg1-functions "\\s-*")
'("(\\s-*\\(\\w+\\)\\s-*\\(,\\|)\\)" nil nil
(1 font-lock-variable-name-face)))))
"Expressions to highlight in MATLAB mode.")
(defvar matlab-really-gaudy-font-lock-keywords
(append
matlab-gaudy-font-lock-keywords
(list
;; Since it's a math language, how bout dem symbols?
'("\\([<>~]=?\\|\\.[/*^']\\|==\\|\\<xor\\>\\|[-!^&|*+\\/~:]\\)"
1 font-lock-type-face)
;; How about references in the HELP text.
(list (concat "^" matlab-comment-line-s "\\s-*"
"\\(\\([A-Z]+\\s-*=\\s-+\\|\\[[^]]+]\\s-*=\\s-+\\|\\)"
"\\([A-Z][0-9A-Z]+\\)\\(([^)\n]+)\\| \\)\\)")
'(1 font-lock-reference-face prepend))
(list (concat "^" matlab-comment-line-s "\\s-*"
"See also\\s-+")
'("\\([A-Z][A-Z0-9]+\\)\\([,.]\\| and\\|$\\) *" nil nil
(1 font-lock-reference-face prepend)))
(list (concat "^" matlab-comment-line-s "\\s-*"
"\\(\\$" "Revision" "[^\n$]+\\$\\)")
'(1 font-lock-reference-face prepend))
;; continuation ellipsis.
'("[^.]\\(\\.\\.\\.+\\)\\([^\n]*\\)" (1 'underline)
(2 font-lock-comment-face))))
"Expressions to highlight in MATLAB mode.")
(defvar matlab-shell-font-lock-keywords
(list
;; How about Errors?
'("^\\(Error in\\|Syntax error in\\)\\s-+==>\\s-+\\(.+\\)$"
(1 font-lock-comment-face) (2 font-lock-string-face))
;; and line numbers
'("^\\(\\(On \\)?line [0-9]+\\)" 1 font-lock-comment-face)
;; User beep things
'("\\(\\?\\?\\?[^\n]+\\)" 1 font-lock-comment-face)
;; Useful user commands, but not useful programming constructs
'("\\<\\(demo\\|whatsnew\\|info\\|subscribe\\|help\\|doc\\|lookfor\\|what\
\\|whos?\\|cd\\|clear\\|load\\|save\\|helpdesk\\|helpwin\\)\\>"
1 font-lock-keyword-face)
;; Various notices
'(" M A T L A B " 0 'underline)
'("All Rights Reserved" 0 'italic)
'("\\((c)\\s-+Copyright[^\n]+\\)" 1 font-lock-comment-face)
'("\\(Version\\)\\s-+\\([^\n]+\\)"
(1 font-lock-function-name-face) (2 font-lock-variable-name-face)))
"Additional keywords used by MATLAB when reporting errors in interactive\
mode.")
(defun matlab-sexp-beg ()
(save-excursion
(while (cond ((< (skip-chars-backward "[a-z_A-Z0-9]") 0)
t)
((eq ?. (char-before))
(backward-char 1)
t)
((memq (char-before) '(?\) ?\}))
(backward-list 1)
t)))
(point)))
(defun matlab-completion-at-point ()
(cond ((or (matlab-cursor-in-string) (looking-at "'"))
(setq default-directory (matlab-eval "pwd"))
(comint--complete-file-name-data))
((looking-back "[a-z_.A-Z0-9]+")
(let* ((bnd-expr (cons (matlab-sexp-beg) (point)))
(bnd-last (bounds-of-thing-at-point 'symbol))
expr res)
(setq expr
(buffer-substring-no-properties
(car bnd-expr)
(cdr bnd-expr)))
(if (string-match "($" expr)
(error "need at least one letter of prefix")
(setq res (matlab-shell-completion-list expr))
(when bnd-last
(let ((re (concat "^" (buffer-substring-no-properties
(car bnd-last)
(cdr bnd-last)))))
(setq res (cl-remove-if-not (lambda (s) (string-match re s)) res))))
(list
(if bnd-last (car bnd-last) (point))
(if bnd-last (cdr bnd-last) (point))
res))))
(t
(error "unexpected"))))
;;* MATLAB mode entry point
;;;###autoload
(add-to-list 'auto-mode-alist '("\\.m$" . matlab-mode))
;;;###autoload
(defun matlab-mode ()
"MATLAB(R) mode is a major mode for editing MATLAB dot-m files.
\\<matlab-mode-map>
Convenient editing commands are:
\\[matlab-fill-comment-line] - Fill the current comment line.
\\[matlab-fill-region] - Fill code and comments in region.
\\[matlab-fill-paragraph] - Refill the current command or comment.
\\[matlab-indent-sexp] - Indent syntactic block of code.
Convenient navigation commands are:
\\[matlab-beginning-of-command] - Move to the beginning of a command.
\\[matlab-end-of-command] - Move to the end of a command.
\\[matlab-beginning-of-defun] - Move to the beginning of a function.
\\[matlab-end-of-defun] - Move do the end of a function.
\\[matlab-forward-sexp] - Move forward over a syntactic block of code.
\\[matlab-backward-sexp] - Move backwards over a syntactic block of code.
Variables:
`matlab-indent-level' Level to indent blocks.
`matlab-cont-level' Level to indent continuation lines.
`matlab-cont-requires-ellipsis' Does your MATLAB support implied elipsis.
`matlab-case-level' Level to unindent case statements.
`matlab-indent-past-arg1-functions'
Regexp of functions to indent past the first
argument on continuation lines.
`matlab-maximum-indents' List of maximum indents during lineups.
`matlab-comment-column' Goal column for on-line comments.
`fill-column' Column used in auto-fill.
`matlab-indent-function-body' If non-nil, indents body of MATLAB functions.
`matlab-functions-have-end' If non-nil, MATLAB functions terminate with end.
`matlab-return-function' Customize RET handling with this function.
`matlab-auto-fill' Non-nil, do auto-fill at startup.
`matlab-fill-code' Non-nil, auto-fill code.
`matlab-fill-strings' Non-nil, auto-fill strings.
`matlab-verify-on-save-flag' Non-nil, enable code checks on save.
All Key Bindings:
\\{matlab-mode-map}"
(interactive)
(kill-all-local-variables)
(use-local-map matlab-mode-map)
(setq major-mode 'matlab-mode)
(setq mode-name "MATLAB")
(setq-local completion-at-point-functions '(matlab-completion-at-point t))
(if (boundp 'whitespace-modes)
(add-to-list 'whitespace-modes 'matlab-mode))
(setq local-abbrev-table matlab-mode-abbrev-table)
(set-syntax-table matlab-mode-syntax-table)
(setq indent-tabs-mode nil)
(setq-local beginning-of-defun-function 'matlab-beginning-of-defun)
(setq-local end-of-defun-function 'matlab-end-of-defun)
(setq-local indent-line-function 'matlab-indent-line)
(setq-local paragraph-start (concat "^$\\|" page-delimiter))
(setq-local paragraph-separate paragraph-start)
(setq-local paragraph-ignore-fill-prefix t)
(setq-local comment-start-skip "%\\s-+")
(setq-local comment-start "%")
(setq-local page-delimiter "^\\(\f\\|%%\\(\\s-\\|\n\\)\\)")
(setq-local comment-column matlab-comment-column)
(setq-local comment-indent-function 'matlab-comment-indent)
(setq-local add-log-current-defun-function 'matlab-current-defun)
(setq-local fill-column default-fill-column)
(make-local-variable 'auto-fill-function)
(if matlab-auto-fill (setq auto-fill-function 'matlab-auto-fill))
(setq-local normal-auto-fill-function 'matlab-auto-fill)
(make-local-variable 'fill-prefix)
;; Save hook for verifying src. This lets us change the name of
;; the function in `write-file' and have the change be saved.
;; It also lets us fix mistakes before a `save-and-go'.
(make-local-variable 'write-contents-hooks)
(add-hook 'write-contents-hooks 'matlab-mode-verify-fix-file-fn)
;; give each file it's own parameter history
(make-local-variable 'matlab-shell-save-and-go-history)
(setq-local font-lock-defaults
'((matlab-font-lock-keywords
matlab-gaudy-font-lock-keywords
matlab-really-gaudy-font-lock-keywords)
t ; do not do string/comment highlighting
nil ; keywords are case sensitive.
;; This puts _ as a word constituent,
;; simplifying our keywords significantly
((?_ . "w"))))
(if window-system (matlab-frame-init))
;; If first function is terminated with an end statement, then functions have
;; ends.
(if (matlab-do-functions-have-end-p)
(matlab-functions-have-end-minor-mode 1)
(matlab-functions-have-end-minor-mode -1))
;; When matlab-indent-function-body is set to 'MathWorks-Standard,
;; - we indent all functions that terminate with an end statement
;; - old style functions (those without end statements) are not
;; indented.
;; It is desired that all code be terminate with an end statement.
;;
;; When matlab-indent-function-body is set to 'guess,
;; - look at the first line of code and if indented, keep indentation
;; otherwise use MathWorks-Standard
;;
(cond
((eq matlab-indent-function-body 'MathWorks-Standard))
((eq matlab-indent-function-body 'guess)
(save-excursion
(goto-char (point-max))
(if (re-search-backward matlab-defun-regex nil t)
(let ((beg (point))
end ; filled in later
(cc (current-column)))
(setq end (if matlab-functions-have-end
(progn (forward-line 0) (point))
(point-max)))
(goto-char beg)
(catch 'done
(while (progn (forward-line 1) (< (point) end))
(if (looking-at "\\s-*\\(%\\|$\\)")
nil ; go on to next line
(looking-at "\\s-*")
(goto-char (match-end 0))
(setq matlab-indent-function-body (> (current-column) cc))
(throw 'done nil)))))
(setq matlab-indent-function-body 'MathWorks-Standard))))
(t))
(save-excursion
(goto-char (point-min))
(run-hooks 'matlab-mode-hook)))
;;* Utilities
(defun matlab-show-version ()
"Show the version number in the minibuffer."
(interactive)
(message "matlab-mode, version %s" matlab-mode-version))
(defun matlab-find-prev-line ()
"Recurse backwards until a code line is found."
(if (= -1 (forward-line -1))
nil
(if (matlab-ltype-empty)
(matlab-find-prev-line)
t)))
(defun matlab-prev-line ()
"Go to the previous line of code. Return nil if not found."
(interactive)
(let ((old-point (point)))
(if (matlab-find-prev-line)
t
(goto-char old-point)
nil)))
(defun matlab-uniquafy-list (lst)
"Return a list that is a subset of LST where all elements are unique."
(let ((nlst nil))
(while lst
(if (and (car lst) (not (member (car lst) nlst)))
(setq nlst (cons (car lst) nlst)))
(setq lst (cdr lst)))
(nreverse nlst)))
(defmacro matlab-navigation-syntax (&rest forms)
"Set the current environment for syntax-navigation and execute FORMS."
(list 'let '((oldsyntax (syntax-table))
(case-fold-search nil))
(list 'unwind-protect
(list 'progn
'(set-syntax-table matlab-mode-special-syntax-table)
(cons 'progn forms))
'(set-syntax-table oldsyntax))))
(put 'matlab-navigation-syntax 'lisp-indent-function 0)
(add-hook 'edebug-setup-hook
(lambda ()
(def-edebug-spec matlab-navigation-syntax def-body)))
(defun matlab-up-list (count &optional restrict)
"Move forwards or backwards up a list by COUNT.
Optional argument RESTRICT is where to restrict the search."
;; MATLAB syntax table has no disabling strings or comments.
(let ((dir (if (> 0 count) -1 1))
(origin (point))
(ms nil))
;; Make count positive
(setq count (* count dir))
(if (= dir -1)
(while (/= count 0)
;; Search till we find an unstrung paren object.
(setq ms (re-search-backward "\\s(\\|\\s)" restrict t))
(while (and (save-match-data (matlab-cursor-in-string-or-comment))
(setq ms (re-search-backward "\\s(\\|\\s)" restrict t))))
(if (not ms)
(progn
(goto-char origin)
(error "Scan Error: List missmatch")))
;; View it's match.
(let ((s (match-string 0)))
(if (string-match "\\s(" s)
(setq count (1- count))
(setq count (1+ count)))))
(error "Not implemented"))
ms))
(defun matlab-valid-end-construct-p ()
"Return non-nil if the end after point terminates a block.
Return nil if it is being used to dereference an array."
(let ((p (point))
(err1 t))
(condition-case nil
(save-restriction
;; Restrict navigation only to the current command line
(save-excursion
(matlab-beginning-of-command)
(narrow-to-region (point)
(save-excursion
(goto-char p)
(line-end-position))))
;; This used to add some sort of protection, but I don't know what
;; the condition was, or why the simple case doesn't handle it.
;;
;; The above replacement fixes a case where a continuation in an array
;; befuddles the indenter.
;; (progn ;;(matlab-end-of-command (point))
;; (end-of-line)
;; (if (> p (point))
;; (progn
;; (setq err1 nil)
;; (error)))
;; (point))))
(save-excursion
;; beginning of param list