-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmatlab-ts-mode.el
More file actions
4737 lines (4141 loc) · 207 KB
/
matlab-ts-mode.el
File metadata and controls
4737 lines (4141 loc) · 207 KB
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-ts-mode.el --- MATLAB(R) Tree-Sitter Mode -*- lexical-binding: t -*-
;; Version: 8.2.0
;; URL: https://github.com/mathworks/Emacs-MATLAB-Mode
;; SPDX-License-Identifier: GPL-3.0-or-later
;;
;; Author: John Ciolfi <john.ciolfi.32@gmail.com>
;; Created: Jul-7-2025
;; Keywords: MATLAB
;; Copyright (C) 2025-2026 Free Software Foundation, Inc.
;;
;; This file 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 3 of the License,
;; or (at your option) any later version.
;;
;; This file 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 this file. If not, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;;
;; Tree-sitter, https://tree-sitter.github.io/tree-sitter
;; based matlab mode: `matlab-ts-mode'
;; using https://github.com/acristoffers/tree-sitter-matlab
;;
;; Install tree-sitter-matlab by taking the matlab.EXT (EXT= .dll, .so, .dylib)
;; from the latest release of https://github.com/emacs-tree-sitter/tree-sitter-langs
;; and rename it to ~/.emacs.d/tree-sitter/libtree-sitter-matlab.EXT
;;
;;; Code:
(require 'compile)
(require 'treesit)
(require 'matlab--access)
(require 'matlab--shared)
(require 'matlab-is-matlab-file)
(require 'matlab-sections)
(require 'matlab-ts-mode--builtins)
(require 'matlab-ts-mode--ei)
;;; Customizations
(defgroup matlab-ts nil
"MATLAB(R) tree-sitter mode."
:prefix "matlab-ts-mode-"
:group 'languages)
(defcustom matlab-ts-mode-font-lock-level 3
"*Level of font lock for MATLAB code.
The \"Standard\" level plus either MLint flycheck or the MATLAB Language
Server gives all syntactic faces along with error indicators.
The \"Standard plus parse errors\" can result in too much use of the
`font-lock-warning-face' when there are syntax errors and is thus
not recommended."
:type '(choice (const :tag "Minimal" 1)
(const :tag "Low" 2)
(const :tag "Standard" 3)
(const :tag "Standard plus parse errors" 4)))
(defcustom matlab-ts-mode-on-save-fixes
'(matlab-ts-mode-on-save-fix-name)
"*List of function symbols which offer to fix *.m files on save.
During save these functions are called and will prompt to fix issues in
*.m files. 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-ts-mode-on-save-fix-name))))
(defcustom matlab-ts-mode-highlight-comment-markers t
"*Highlight triple-x, to-do, and fix-me comment markers?
See \\[matlab-ts-mode-comment-marker-help]."
:type 'boolean)
(defcustom matlab-ts-mode-enable-mlint-flycheck t
"*Enable MLint code analyzer via flycheck.
This requires that you install the flycheck package
https://www.flycheck.org can be installed by adding
to your ~/.emacs
(require \\='package)
(add-to-list \\='package-archives
\\='(\"MELPA Stable\" . \"https://stable.melpa.org/packages/\") t)
Then restart Emacs and run
\\[package-install] RET flycheck RET
You can also install via use-package or other methods."
:type 'boolean)
(defcustom matlab-ts-mode-electric-ends t
"*If t, insert end keywords to complete statements and insert % for doc comments.
For example, if you type
classdef foo<RET>
an end statement will be inserted resulting in:
classdef foo<RET>
^ <== point here
end
Insertion of end keywords works well when the code is
indented. If you are editing code that is not indented,
you may wish to turn this off.
This will also add \"% \" for documentation comments. For example,
function foo
% help for foo<RET>
%
^ <== \"% \" is inserted and point is here
end"
:type 'boolean)
(defgroup matlab-ts-faces nil
"Faces used by `matlab-ts-mode'."
:group 'matlab-ts)
(defface matlab-ts-mode-pragma-face
'((t :inherit font-lock-comment-face
:bold t))
"*Face to use for comment lines which start with %#.
These include lines like
%#ok // pragmas used by the MATLAB Code Analyzer, mlint
%#function // pragmas used by the MATLAB Compiler")
(defface matlab-ts-mode-string-delimiter-face
'((t :inherit font-lock-string-face
:bold t))
"*Face to use for \\='single quote\\=' and \"double quote\" string delimiters.")
(defface matlab-ts-mode-comment-heading-face
'((t :inherit font-lock-comment-face
:overline t
:bold t))
"*Face for \"%% code section\" headings.")
(defface matlab-ts-mode-comment-to-do-marker-face
'((((class color) (background light))
:inherit font-lock-comment-face
:background "yellow"
:weight bold)
(((class color) (background dark))
:inherit font-lock-comment-face
:background "yellow4"
:weight bold))
;; Note we split up the markers with spaces below so C-s when editing this file
;; doesn't find them.
(concat "*Face use to highlight "
"TO" "DO," " FIX" "ME," " and XX" "X markers ignoring case in comments.
Guidelines:
- FIX" "ME" " and XX" "X markers should be fixed prior to committing
code to a source repository.
- TO" "DO markers can remain in code and be committed with the code to a
source repository. TO" "DO markers should reflect improvements are
not problems with the existing code."))
(defface matlab-ts-mode-operator-face
'((((class color) (background light)) :foreground "navy")
(((class color) (background dark)) :foreground "LightBlue")
(t :inverse-video t
:weight bold))
"*Face for operators: *, /, +, -, etc.")
(defface matlab-ts-mode-command-arg-face
'((t :inherit font-lock-string-face
:slant italic))
"*Face used to highlight command dual arguments.")
(defface matlab-ts-mode-system-command-face
'((t :inherit font-lock-builtin-face
:slant italic))
"*Face used to highlight \"!\" system commands.")
(defface matlab-ts-mode-property-face
'((t :inherit font-lock-property-name-face
:slant italic))
"*Face used on properties, enumerations, and events.")
(defface matlab-ts-mode-number-face
'((t :inherit font-lock-constant-face))
"*Face used for numbers.")
(defface matlab-ts-mode-end-number-face
'((t :inherit matlab-ts-mode-number-face
:slant italic))
"*Face used for \"end\" when used as an array or cell dimension number index.
For example:
mat1 = [1:10;
2:2:20];
mat2 = mat1(2:end, end:end);")
(defface matlab-function-signature-face
'((t :inherit font-lock-type-face
:weight bold
:slant italic))
"*Face used for classdef abstract method function signature declarations.
In this example, fcn1 will get this face:
classdef MyClass
methods(Abstract)
a = fcn1(obj);
end
end")
(defface matlab-ts-mode-variable-override-builtin-face
'((t :inherit font-lock-variable-name-face
:underline t))
"*Face used for variable overriding a builtin.
For example, it is valid to override the disp command:
disp = 1:10;
and then trying to use disp to display results will not work.")
(defface matlab-ts-region-face
'((t :inherit region))
"*Face used to highlight a region of text when prompting for input.
For example, if the function name and *.m file name are different
the function name will be highlighted and you will see prompt
Function name and file names are different. Fix?
when saving.")
;;; Global variables used in multiple code ";;; sections"
(defvar matlab-ts-mode--comment-section-heading-re
"^[ \t]*\\(%%\\(?:[ \t].+\\)?\\)$"
"Regexp matching \"%% headings\" lines.")
;;; Utilities
(defun matlab-ts-mode--real-node-at-point ()
"Return \\='(pt . node) where node is not a newline.
The MATLAB tree-sitter grammar includes a newline as a node.
If we are on a newline, this will backup to a real node.
The returned point, pt, reflects that location."
(let* ((pt (point))
(node-at-point (treesit-node-at pt))
;; Handle case at end of a start node, e.g. point just after properties:
;; properties
;; ^
;; foo;
;; end
;; Likewise for comments
;; % comment
;; ^
(real-node (if (and (equal "\n" (treesit-node-type node-at-point))
(> pt 1))
(progn
(setq pt (1- pt))
(treesit-node-at pt))
node-at-point)))
(cons pt real-node)))
(defun matlab-ts-mode--child-last-node (parent-node)
"Get the logical child last node of PARENT-NODE.
Consider:
classdef enum1 < uint32
enumeration
A (0)
B (1)
end
end
with parse tree:
(source_file
(class_definition classdef name: (identifier)
(superclasses <
(property_name (identifier)))
\\n
(enumeration enumeration \\n
(enum (identifier) ( (number) ))
\\n
(enum (identifier) ( (number) ))
\\n end \\n)
end)
\\n)
The last node of the \"(enumeration ... \\n)\" is \"\\n\" and the
logical last node is \"end\"."
(let* ((children (treesit-node-children parent-node))
(last-idx (1- (length children)))
(last-node (nth last-idx children)))
(while (and (>= last-idx 0)
(string= (treesit-node-type last-node) "\n"))
(setq last-idx (1- last-idx))
(setq last-node (nth last-idx children)))
last-node))
;;; File encoding
(defun matlab-ts-mode--check-file-encoding ()
"Check/set file encoding.
Error is signaled if contents are corrupt because non-utf8 printable
content can crash Emacs via the matlab tree-sitter parser."
;; MCR check. Version info is at start.
;; R2025a example: V2MCC8000MEC2000MCR2000<binary-data>
(save-excursion
(goto-char (point-min))
(when (looking-at "^V[0-9A-Z]+MCR[0-9]+" t)
(fundamental-mode)
(user-error "Not activating matlab-ts-mode because this is MATLAB Compiler Runtime content")))
;; We could check for utf-8 and error when non-utf8, but that may cause grief. Suppose
;; a malformed character is in a comment. That should be allowed.
;; (when (not (string-match "utf-8" (symbol-name buffer-file-coding-system)))
;; (user-error "Buffer does not have utf-8 encoding"))
;; Note we cannot
;; (set-buffer-file-coding-system 'utf-8))
;; because this would modify it and modes shouldn't modify the buffer.
(let ((bad-char-point (save-excursion
(goto-char (point-min))
;; Due to the matlab-ts-mode syntax table entry
;; (modify-syntax-entry ?\n ">" st)
;; [:space:] doesn't match newlines.
(when (re-search-forward "[^[:print:][:space:]\n\r]" nil t)
(point)))))
(when bad-char-point
(fundamental-mode)
(goto-char bad-char-point)
(user-error
"Not entering matlab-ts-mode due to non-printable utf8 character \"%c\" at point %d"
(char-before) bad-char-point))))
;;; Syntax table
(defvar matlab-ts-mode--syntax-table
(let ((st (make-syntax-table (standard-syntax-table))))
;; Comment Handling:
;; 1. Single line comments: % text (single char start),
;; note includes "%{ text"
;; 2. Multiline comments: %{
;; lines
;; %}
;; 3. Ellipsis line continuations comments: "... optional text"
;; are handled in `matlab-ts-mode--syntax-propertize'
(modify-syntax-entry ?% "< 13" st)
(modify-syntax-entry ?{ "(} 2c" st)
(modify-syntax-entry ?} "){ 4c" st)
;; \n is a comment ender. Therefore, regex [:space:] won't recognize \n
(modify-syntax-entry ?\n ">" st)
;; String Handling:
;; Single quoted string (character vector): 'text'
;; Double-quoted string: "text"
;; Transpose: varname'
;; Quoted quotes: ' don''t ' or " this "" "
;; Unterminated Char V: ' text
(modify-syntax-entry ?' "\"" st)
(modify-syntax-entry ?\" "\"" st)
;; Words and Symbols:
(modify-syntax-entry ?_ "_" st)
;; Punctuation:
(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)
;; Parenthetical blocks:
;; Note: these are in standard syntax table, repeated here for completeness.
(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 matlab-ts-mode syntax table.")
(defun matlab-ts-mode--put-char-category (pos category)
"At character POS, put text property CATEGORY."
(when (not (eobp))
(put-text-property pos (1+ pos) 'category category)
(put-text-property pos (1+ pos) 'mcm t)))
(defmacro matlab-ts-mode--syntax-symbol (symbol syntax doc)
"Create a new SYMBOL with DOC used as a text property category with SYNTAX."
(declare (indent defvar) (debug (sexp form sexp)) (doc-string 3))
`(progn (defconst ,symbol ,syntax ,doc)
(put ',symbol 'syntax-table ,symbol)))
;; In the Syntax Table descriptors, "<" is for comments
(matlab-ts-mode--syntax-symbol matlab-ts-mode--ellipsis-syntax (string-to-syntax "<")
"Syntax placed on ellipsis to treat them as comments.")
(defun matlab-ts-mode--syntax-propertize (&optional start end)
"Scan region between START and END to add properties.
If region is not specified, scan the whole buffer.
This will mark ellipsis line continuation's
... optional text
as comments which is how they are treated by MATLAB."
(save-match-data ;; avoid 'Syntax Checking transmuted the match-data'
(save-excursion
;; Scan region, but always expand to beginning of line
(goto-char (or start (point-min)))
(forward-line 0)
;; Edits can change what properties characters can have so remove ours and reapply
(remove-text-properties (point) (save-excursion
(goto-char (or end (point-max)))
(let ((inhibit-field-text-motion t)) (end-of-line))
(point))
'(category nil mcm nil))
;; Tell Emacs that ellipsis (...) line continuations are comments.
(while (and (not (>= (point) (or end (point-max)))) (not (eobp)))
(if (treesit-search-forward-goto (treesit-node-at (point))
(rx bos "line_continuation" eos)
t) ;; goto start of: ... optional text
(matlab-ts-mode--put-char-category (point) 'matlab-ts-mode--ellipsis-syntax)
(goto-char (point-max)))))))
;;; font-lock
(defvar matlab-ts-mode--keywords
;; Nodes like "if" are captured by their text because they are part of a bigger node that captures
;; them as such (and need more than just their text to define the node), but it doesn't make much
;; sense to create a node for the text "break", "continue", etc. because that would create two
;; nodes for the same purpose, where one is sufficient. In other words, "break" like nodes are
;; captured as named nodes, not as unnamed ones, so you need to use their node names instead of
;; the "content". See https://github.com/acristoffers/tree-sitter-matlab/issues/25
;;
;; Keywords are documented here https://www.mathworks.com/help/matlab/ref/iskeyword.html
;; Note, arguments, methods, properties are semi-keywords in that in the right location
;; the are keywords, otherwise in the wrong location they are variables, but tree-sitter
;; correctly handles them by letting us look for these as content of the nodes.
'("arguments"
(break_statement)
"case"
"catch"
"classdef"
(continue_statement)
"else"
"elseif"
"end"
"enumeration"
"events"
"for"
"function"
"get." ;; when used in a classdef method, e.g. function value = get.propName(obj)
"global"
"if"
"methods"
"otherwise"
"parfor"
"persistent"
"properties"
(return_statement)
"set." ;; when used in a classdef method, e.g. function obj = set.propName(obj, val)
"spmd"
"switch"
"try"
"while")
"The matlab-ts-mode font-lock keywords.")
(defvar matlab-ts-mode--operators
;; https://www.mathworks.com/help/matlab/matlab_prog/matlab-operators-and-special-characters.html
'("+" ;; Addition or Unary plus, +value
"-" ;; Subtraction or Unary minus, -value
".*" ;; Element-wise multiplication
"*" ;; Matrix multiplication
"./" ;; Element-wise right division
"/" ;; Matrix right division
".\\" ;; Element-wise left division
"\\" ;; Matrix left division (also known as backslash)
".^" ;; Element-wise power
"^" ;; Matrix power
".'" ;; Transpose
"'" ;; Complex conjugate transpose
"==" ;; Equal to
"~=" ;; Not equal to
">" ;; Greater than
">=" ;; Greater than or equal to
"<" ;; Less than
"<=" ;; Less than or equal to
"&" ;; Find logical AND
"|" ;; Find logical OR
"&&" ;; Find logical AND (with short-circuiting)
"||" ;; Find logical OR (with short-circuiting)
"~" ;; Find logical NOT
"@" ;; Create anonymous functions and function handles, call superclass methods
;; "!" ;; "!" is like an operator, but has command-dual like syntax, so handled elsewhere
"?" ;; Retrieve metaclass information for class name
"~" ;; Represent logical NOT, suppress specific input or output arguments.
"=" ;; Variable creation and indexing assignment.
"<" "&" ;; Specify one or more superclasses in a class definition.
".?" ;; Specify the fields of a name-value structure as the names of all
;; ; writable properties of the class.
;; ; However, this isn't parsed correctly by matlab tree-sitter, see
;; ; https://github.com/acristoffers/tree-sitter-matlab/issues/35
)
"The matlab-ts-mode font-lock operators.")
(defvar matlab-ts-mode--type-functions
'("double"
"single"
"int8"
"int16"
"int32"
"int64"
"uint8"
"uint16"
"uint32"
"uint64")
"The matlab-ts-mode data type functions.")
(cl-defun matlab-ts-mode--get-doc-comment-candidate (comment-node)
"Get candidate doc comment node or nil.
Return a comment node based on COMMENT-NODE if it is a candidate for a
help doc comment."
;; Backup over a copyright comment line
(when (string-match-p "\\`[ \t]*%[ \t]*copyright\\b"
(treesit-node-text comment-node))
(setq comment-node (treesit-node-prev-sibling comment-node))
(when (not (string= "comment" (treesit-node-type comment-node)))
(cl-return-from matlab-ts-mode--get-doc-comment-candidate)))
(let ((prev-node (treesit-node-prev-sibling comment-node)))
(when prev-node
(while (and prev-node
(string-match-p (rx bos (or "line_continuation" "\n") eos)
(treesit-node-type prev-node)))
(setq prev-node (treesit-node-prev-sibling prev-node)))
(let ((prev-type (or (treesit-node-type prev-node) "")))
;; The true (t) cases. Note line continuation ellipsis are allowed.
;; function foo function foo(a)
;; % doc comment % doc comment
;; end end
(when (or (string-match-p (rx bos (or
"function_arguments" ;; function input args?
"superclasses") ;; subclass
eos)
prev-type)
(and (string= prev-type "identifier") ;; id could be a fcn or class id
(let* ((prev-sibling (treesit-node-prev-sibling prev-node))
(prev-type (and prev-sibling (treesit-node-type prev-sibling))))
(and prev-type
(or
(string-match-p
(rx bos
(or "function" ;; fcn without in and out args
"function_output" ;; fcn w/out args and no in args
"classdef") ;; base class
eos)
prev-type)
(and (string= prev-type "attributes")
(equal (treesit-node-type (treesit-node-parent prev-sibling))
"class_definition")))))))
comment-node)))))
(defun matlab-ts-mode--is-doc-comment (comment-node parent)
"Is the COMMENT-NODE under PARENT a help doc comment.
In MATLAB,
function out = myFunction
% The documentation help comment for myFunction immediately follows the
% function definition.
% code comments are preceded with a blank line
out = 1;
end
function out = myFunction
% The documentation help comment for myFunction immediately follows the
% function definition.
% copyright at column 0 and preceded by blank lines after the help comment
% code comments are preceded with a blank line
out = 1;
end
function out = myFunctionWithoutHelp
% code comments are preceded with a blank line
out = 1;
end
Similar behavior for classdef's."
(setq comment-node (matlab-ts-mode--get-doc-comment-candidate comment-node))
(when (and comment-node
(string-match-p (rx bos (or "function_definition" "class_definition") eos)
(treesit-node-type parent)))
(let ((definition-point (treesit-node-start parent)))
(save-excursion
(goto-char (treesit-node-start comment-node))
(forward-line 0)
;; result - is doc comment?
(or (<= (point) definition-point) ;; at definition?
(and (> (point) definition-point)
(not (re-search-backward "^[ \t]*$" definition-point t))))))))
(defun matlab-ts-mode--doc-comment-capture (comment-node override start end &rest _)
"Fontify function/classdef documentation comments.
COMMENT-NODE is the tree-sitter node from a treesit-font-lock-rules rule
and OVERRIDE is from that rule. START and END specify the region to be
fontified which could be smaller or larger than the COMMENT-NODE
start-point and end-point."
(when (matlab-ts-mode--is-doc-comment comment-node (treesit-node-parent comment-node))
(treesit-fontify-with-override
(treesit-node-start comment-node) (treesit-node-end comment-node)
font-lock-doc-face override start end)))
(defun matlab-ts-mode--comment-heading-capture (comment-node override start end &rest _)
"Fontify the \"%% heading\" start line in COMMENT-NODE.
COMMENT-NODE is the tree-sitter node from a treesit-font-lock-rules rule
and OVERRIDE is from that rule. START and END specify the region to be
fontified which could be smaller or larger than the COMMENT-NODE
start-point and end-point."
(save-excursion
(goto-char (treesit-node-start comment-node))
(forward-line 0)
(when (looking-at matlab-ts-mode--comment-section-heading-re)
(let ((heading-start (match-beginning 1))
(heading-end (match-end 1)))
(treesit-fontify-with-override heading-start heading-end
'matlab-ts-mode-comment-heading-face
override start end)))))
(defun matlab-ts-mode--comment-pragma-capture (comment-node override start end &rest _)
"Fontify %#pragma, %-indent-mode=minimal, %-indent=mode=full.
COMMENT-NODE is the tree-sitter comment node from a
treesit-font-lock-rules rule and OVERRIDE is from that rule. START and
END specify the region to be fontified which could be smaller or larger
than the COMMENT-NODE start-point and end-point."
;; Note comment-node can contain many single-line comments, e.g. this is one comment node:
;; %#ok
;; % some other comment
(save-excursion
(goto-char (treesit-node-start comment-node))
(let ((comment-end (treesit-node-end comment-node)))
(while (< (point) comment-end)
(if (re-search-forward
;; String below is the efficient form of
;; (rx (group (or (seq "%" "#" (1+ (not space)))
;; (seq "%-indent-mode=minimal" word-end)
;; (seq "%-indent-mode=full" word-end)))
"\\(%\\(?:#[^ \t\n\r]+\\|\\(?:-indent-mode=\\(?:minimal\\|full\\)\\)\\>\\)\\)"
comment-end t)
(let ((pragma (match-string 1))
(pragma-start (match-beginning 1))
(pragma-end (match-end 1)))
(when (or (string-match-p "^%#" pragma) ;; %#pragma can be on any line
(save-excursion ;; %-indent-mode=* must be on line by itself
(goto-char pragma-start)
(forward-line 0)
(= (1- (re-search-forward "[^ ]")) pragma-start)))
(treesit-fontify-with-override pragma-start pragma-end
'matlab-ts-mode-pragma-face
override start end)))
(goto-char comment-end))))))
(defvar matlab-ts-mode--comment-markers
(list (concat "XX" "X")
(concat "FIX" "ME")
(concat "TO" "DO")))
(defvar matlab-ts-mode--comment-markers-re
(rx-to-string `(seq word-start (group (or ,@matlab-ts-mode--comment-markers) word-end))))
(defun matlab-ts-mode--comment-to-do-capture (comment-node override start end &rest _)
"Fontify triple-x, fix me, and to do markers in comments.
For guidelines on using these comment markers see:
\\[matlab-ts-mode-comment-marker-help]
COMMENT-NODE is the tree-sitter comment node from a
treesit-font-lock-rules rule and OVERRIDE is from that rule. START and
END specify the region to be fontified which could be smaller or larger
than the COMMENT-NODE start-point and end-point."
(when matlab-ts-mode-highlight-comment-markers
(save-excursion
(let ((comment-end (treesit-node-end comment-node)))
(goto-char (treesit-node-start comment-node))
(while (< (point) comment-end)
;; Note, the markers below have spaces in them so we don't find them when searching "C-s"
;; while editing this file.
(if (re-search-forward matlab-ts-mode--comment-markers-re comment-end t)
(let ((keyword-start (match-beginning 1))
(keyword-end (match-end 1)))
(treesit-fontify-with-override keyword-start keyword-end
'matlab-ts-mode-comment-to-do-marker-face
override start end))
(goto-char comment-end)))))))
(defun matlab-ts-mode--namespace-path (namespace-node)
"Get the a.b.c path of NAMESPACE-NODE."
(let ((children (treesit-node-children namespace-node))
path)
(cl-loop for child in children do
(let ((child-type (treesit-node-type child)))
(cond
;; Case: (identifier) or "."
((or (string= child-type "identifier")
(string= child-type "."))
(setq path (concat path (treesit-node-text child))))
;; Case: (function_call)
((string= child-type "function_call")
;; Consider: a.b.c{1}{2} or a.b.c{1}(1)
(let ((fcn-name-node (treesit-node-child-by-field-name child "name")))
(let ((fcn-name-type (treesit-node-type fcn-name-node)))
(while (string= fcn-name-type "function_call")
(setq fcn-name-node (treesit-node-child-by-field-name fcn-name-node "name")
fcn-name-type (treesit-node-type fcn-name-node)))
(if (string= fcn-name-type "field_expression")
(setq path (concat path (matlab-ts-mode--namespace-path fcn-name-node)))
(setq path (concat path (treesit-node-text fcn-name-node)))))))
;; Case: other - shouldn't be able to get here, but be safe.
(t
(cl-return)))))
path))
(defun matlab-ts-mode--namespace-builtins-capture (namespace-node override start end &rest _)
"Fontify foo.bar.goo when it is a builtin function.
NAMESPACE-NODE is the tree-sitter field_expression or a superclass
property_name node. These nodes have children that for a PATH,
e.g. \"foo.bar.goo\". This is connected to the namespace-builtins
treesit-font-lock-rules rule and OVERRIDE is from that rule. START and
END specify the region to be fontified which could be smaller or larger
than the FILED-EXPRESSION-NODE start-point and end-point."
(let ((path (matlab-ts-mode--namespace-path namespace-node))) ;; The "path" e.g. foo.bar.goo
(let ((builtin-type (gethash path matlab-ts-mode--builtins-ht)))
(when builtin-type
(let ((builtin-start (treesit-node-start namespace-node))
builtin-end
prop-start
prop-end)
(if (eq builtin-type t)
(setq builtin-end (+ builtin-start (length path)))
;; builtin-type is 'property or 'enumeration
(when (not (string-match "\\`\\(.+\\.\\)\\([^.]+\\)\\'" path))
(error "Assert: failed to parse path, %s" path))
(setq builtin-end (+ builtin-start (- (length (match-string 1 path)) 2)))
;; We give the "." before the property or enum font-lock-delimiter-face, hence the +2.
(setq prop-start (+ builtin-end 2))
(setq prop-end (+ prop-start (length (match-string 2 path)))))
(treesit-fontify-with-override builtin-start builtin-end 'font-lock-builtin-face
override start end)
(when prop-start
(treesit-fontify-with-override prop-start prop-end 'matlab-ts-mode-property-face
override start end)))))))
(defun matlab-ts-mode--is-fcn-name-value (identifier-node)
"Return t if IDENTIFIER-NODE is a function name-value property."
(let ((next-sibling (treesit-node-next-sibling identifier-node)))
(and next-sibling
(string= (treesit-node-text next-sibling) "="))))
(defun matlab-ts-mode--is-identifier-builtin (identifier-node)
"Return t if IDENTIFIER-NODE is a function provided with MATLAB."
(let ((parent (treesit-node-parent identifier-node)))
;; Consider
;; foo.bar.disp.goo = 1; % both foo and disp are builtin functions, but in this case fields
;; foo.bar(1) % +foo/bar.m - bar is a builtin, but foo.bar(1) is not.
(when (and (not (equal (treesit-node-type parent) "field_expression"))
(not (equal (treesit-node-type (treesit-node-parent parent)) "field_expression")))
(let ((id (treesit-node-text identifier-node)))
(gethash id matlab-ts-mode--builtins-ht)))))
(defun matlab-ts-mode--is-command-builtin (command-node)
"Return t if COMMAND-NODE is a function provided with MATLAB."
(let ((command (treesit-node-text command-node)))
(gethash command matlab-ts-mode--builtins-ht)))
(defun matlab-ts-mode--is-variable-overriding-builtin (variable-node)
"Is VARIABLE-NODE overriding a builtin?
Example, disp variable is overriding the disp builtin function:
disp = 1:10;"
(let ((variable (treesit-node-text variable-node)))
(or (gethash variable matlab-ts-mode--builtins-ht)
;; Initially arguments, etc. capabilities didn't exist in MATLAB. When they were added,
;; compatibility was kept when these were used as variables. So, they are "semi-keywords".
(string-match-p (rx bos (or "arguments" "enumeration" "events" "methods" "properties") eos)
(treesit-node-text variable-node)))))
(defvar matlab-ts-mode--font-lock-settings
(treesit-font-lock-rules
;; F-Rule: Comments and line continuation: ... optional text
:language 'matlab
:feature 'comment
'(
;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_comment_types.m
(comment) @font-lock-comment-face
;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_continuation.m
;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_continuation_fcn.m
;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_continuation_fcn_g2.m
;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_continuation_multiArgFcn.m
(line_continuation) @font-lock-comment-face)
;; F-Rule: special comments that override normal comment font
:language 'matlab
:feature 'comment-special
:override t
'(;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_pragma_in_fcn.m
((comment) @matlab-ts-mode--comment-pragma-capture)
;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_comment_heading.m
;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_sections.m
((comment) @matlab-ts-mode--comment-heading-capture) ;; %% comment section heading
;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_comment_no_doc_help.m
;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_comment_fcn.m
(function_definition (comment) @matlab-ts-mode--doc-comment-capture) ;; doc help comments
;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_MyClass.m
(class_definition (comment) @matlab-ts-mode--doc-comment-capture)) ;; doc help comments
;; F-Rule: to do, fix me, triple-x marker comment keywords
;; See: test-matlab-ts-mode-font-lock-files/font_lock_comment_markers.m
:language 'matlab
:feature 'comment-marker
:override t
'(((comment) @matlab-ts-mode--comment-to-do-capture)
((line_continuation) @matlab-ts-mode--comment-to-do-capture))
;; F-Rule: Constant literal numbers, e.g. 1234, 12.34, 10e10
;; We could use this for items like true, false, pi, etc. See some of these numbers in:
;; https://www.mathworks.com/content/dam/mathworks/fact-sheet/
;; matlab-basic-functions-reference.pdf
;; however, they do show up as builtins, which to me seems more accurate.
;; This rule needs to come before the "F-Rule: keywords: if, else, end, etc." because
;; we want the end_keyword when used as a number index into a cell/matrix to be a number font.
;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_numbers.m
:language 'matlab
:feature 'number
'(((number) @matlab-ts-mode-number-face)
((end_keyword) @matlab-ts-mode-end-number-face))
;; F-Rule: variable
;; Could add font-lock-variable-name-face to variable uses. Consider
;; i1 = [1, 2];
;; i2 = i1(1) + i3 + i4(i3);
;; we know i1 and i2 are variables from the (assignment left: (identifier))
;; However, we don't know if i3 or i4 are variables or functions because a function
;; can be called with no arguments, e.g. to call i3 function use i3 or i3(). i4 could
;; be a variable indexed by i1 or a function.
;;
;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_variable.m
:language 'matlab
:feature 'variable
'(((assignment left: (identifier) @matlab-ts-mode-variable-override-builtin-face
(:pred matlab-ts-mode--is-variable-overriding-builtin
@matlab-ts-mode-variable-override-builtin-face)))
(assignment left: (identifier) @font-lock-variable-name-face)
(multioutput_variable (identifier) @matlab-ts-mode-variable-override-builtin-face
(:pred matlab-ts-mode--is-variable-overriding-builtin
@matlab-ts-mode-variable-override-builtin-face))
(multioutput_variable (identifier) @font-lock-variable-name-face)
(global_operator (identifier) @matlab-ts-mode-variable-override-builtin-face
(:pred matlab-ts-mode--is-variable-overriding-builtin
@matlab-ts-mode-variable-override-builtin-face))
(global_operator (identifier) @font-lock-variable-name-face)
(persistent_operator (identifier) @matlab-ts-mode-variable-override-builtin-face
(:pred matlab-ts-mode--is-variable-overriding-builtin
@matlab-ts-mode-variable-override-builtin-face))
(persistent_operator (identifier) @font-lock-variable-name-face)
(for_statement (iterator (identifier) @matlab-ts-mode-variable-override-builtin-face
(:pred matlab-ts-mode--is-variable-overriding-builtin
@matlab-ts-mode-variable-override-builtin-face)))
(for_statement (iterator (identifier) @font-lock-variable-name-face))
;; Function inputs: functionName(in1, in2, in3)
;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_fcn_small_in_args.m
(function_arguments arguments:
(identifier) @font-lock-variable-name-face
("," (identifier) @font-lock-variable-name-face) :*)
;; Function single output argument: function out = functionName(in1, in2)
;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_fcn_small_out_args.m
(function_output (identifier) @font-lock-variable-name-face)
;; Function multiple output arguments: function [out1, out2] = functionName(in1, in2)
(function_output (multioutput_variable (identifier) @font-lock-variable-name-face))
;; Enumeration's
;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_class_enum.m
;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_enum_FlowRate.m
(enum (identifier) @matlab-ts-mode-property-face)
;; Events block in classdef
;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_class_events.m
(events (identifier) @matlab-ts-mode-property-face)
;; Namespaces, structs, classdef methods/property access. Note any keyword is allowed,
;; e.g. foo.methods.function = 1;
(field_expression (identifier) @default))
;; F-Rule: keywords: if, else, end, etc.
;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_keywords.m
;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_class_methods.m
;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_keyword_spmd.m
:language 'matlab
:feature 'keyword
`([,@matlab-ts-mode--keywords] @font-lock-keyword-face)
;; F-Rule: Types, e.g. int32()
:language 'matlab
:feature 'type
`((function_call name: (identifier)
@font-lock-type-face
(:match ,(rx-to-string `(seq bos
(or ,@matlab-ts-mode--type-functions)
eos)
t)
@font-lock-type-face))
(property name: (identifier) (identifier) @font-lock-type-face :?)
(property name: (property_name (identifier)) (identifier) @font-lock-type-face :?))
;; F-Rule: namespaces (the +dir's, class methods, etc.)
;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_namespaces.m
:language 'matlab
:feature 'namespace-builtins
:override t
`((superclasses (property_name) @matlab-ts-mode--namespace-builtins-capture)
(field_expression) @matlab-ts-mode--namespace-builtins-capture)
;; F-Rule: factory items that come with MATLAB, Simulink, or add-on products
;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_builtins.m
:language 'matlab
:feature 'builtins
`(((identifier) @font-lock-builtin-face
(:pred matlab-ts-mode--is-identifier-builtin @font-lock-builtin-face))
((command_name) @font-lock-builtin-face
(:pred matlab-ts-mode--is-command-builtin @font-lock-builtin-face)))
;; F-Rule: function/classdef and items defining them, e.g. the function arguments
:language 'matlab
:feature 'definition
'(
;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_class_issue55_abstract.m
(function_signature name: (identifier) @matlab-function-signature-face)
;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_fcn_small_no_args.m
(function_definition name: (identifier) @font-lock-function-name-face)
;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_symPosDef.m
(class_definition name: (identifier) @font-lock-function-name-face)
;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_MySubClass.m
;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_MySubSubClass.m
(superclasses (property_name (identifier)) @font-lock-function-name-face)
;; Fields of: arguments ... end , properties ... end
;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_fcn_arguments.m
;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_class_properties.m
;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_class_MultiplePropBlocks.m
;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_class_prop_access.m
(property (validation_functions (identifier) @font-lock-function-call-face))
(property name: (identifier) @matlab-ts-mode-property-face)
(property name: (property_name (identifier) @matlab-ts-mode-property-face))
;; Attributes of properties, methods
;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_class_attributes.m
(attribute (identifier) @font-lock-type-face "=" (identifier) @font-lock-builtin-face)
(attribute (identifier) @font-lock-type-face))
;; F-Rule: validation functions from namespace
;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_fcn_arguments2_issue57.m
:language 'matlab
:feature 'definition
:override t
'((property (validation_functions (field_expression (identifier) @font-lock-function-call-face)))
(property (validation_functions ((field_expression
(function_call name: (identifier)
@font-lock-function-call-face))))))
;; F-Rule: Function Name = Value arguments
;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_fcn_name_value_properties.m
:language 'matlab
:feature 'fcn-name-value
'(((function_call (arguments (identifier) @matlab-ts-mode-property-face))
(:pred matlab-ts-mode--is-fcn-name-value @matlab-ts-mode-property-face)))
;; F-Rule: command dual arguments
:language 'matlab
:feature 'command-arg
'((command_argument) @matlab-ts-mode-command-arg-face)
;; F-Rule: system and command dual commands.
;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_command.m
:language 'matlab
:feature 'command-name
'(((command_name) @matlab-ts-mode-system-command-face
;; System command: ! ls *.m *.txt
(:match "^!" @matlab-ts-mode-system-command-face))
;; Command-dual with at least one arg: myFunction arg
;; Commands with no args could be a variable or a function
((command (command_name) @font-lock-function-call-face (command_argument))))
;; F-Rule: strings "double quote" and 'single quote'
;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_strings.m
:language 'matlab
:feature 'string
'((string_content) @font-lock-string-face
((string_content) ["\"" "'"]) @matlab-ts-mode-string-delimiter-face
(string ["\"" "'"] @matlab-ts-mode-string-delimiter-face)
(escape_sequence) @font-lock-escape-face