-
Notifications
You must be signed in to change notification settings - Fork 79
/
typescript-mode.el
3145 lines (2734 loc) · 122 KB
/
typescript-mode.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
;;; typescript-mode.el --- Major mode for editing typescript
;; -----------------------------------------------------------------------------------
;; TypeScript support for Emacs
;; Unmodified original sourve available at http://www.karllandstrom.se/downloads/emacs/javascript.el
;; Copyright (c) 2008 Free Software Foundation
;; Portions Copyright (C) Microsoft Open Technologies, Inc. All rights reserved.
;;
;; 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 3 of the License, 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 this program. If not, see <http://www.gnu.org/licenses/>.
;; -------------------------------------------------------------------------------------------
;; URL: http://github.com/ananthakumaran/typescript.el
;; Version: 0.4
;; Keywords: typescript languages
;; Package-Requires: ((emacs "24.3"))
;; This file is not part of GNU Emacs.
;;; Commentary:
;; This is based on Karl Landstrom's barebones typescript-mode. This
;; is much more robust and works with cc-mode's comment filling
;; (mostly).
;; The modifications to the original javascript.el mode mainly consisted in
;; replacing "javascript" with "typescript"
;;
;; The main features of this typescript mode are syntactic
;; highlighting (enabled with `font-lock-mode' or
;; `global-font-lock-mode'), automatic indentation and filling of
;; comments.
;;
;;
;; General Remarks:
;;
;; XXX: This mode assumes that block comments are not nested inside block
;; XXX: comments
;;
;; Exported names start with "typescript-"; private names start with
;; "typescript--".
;;; Code:
(eval-and-compile
(require 'compile)
(require 'cc-mode)
(require 'font-lock)
(require 'rx)
(require 'newcomment))
(eval-when-compile
(require 'cl-lib))
;;; Constants
(defconst typescript--type-name-re "\\(?:[A-Z][A-Za-z0-9]+\\.\\)\\{0,\\}\\(?:[A-Z][A-Za-z0-9]+\\)"
"Regexp matching a conventional TypeScript type-name. Must start with upper-case letter!")
(defconst typescript--name-start-re "[a-zA-Z_$]"
"Regexp matching the start of a typescript identifier, without grouping.")
(defconst typescript--name-re (concat typescript--name-start-re
"\\(?:\\s_\\|\\sw\\)*")
"Regexp matching a typescript identifier, without grouping.")
(defconst typescript--objfield-re (concat typescript--name-re ":")
"Regexp matching the start of a typescript object field.")
(defconst typescript--dotted-name-re
(concat typescript--name-re "\\(?:\\." typescript--name-re "\\)*")
"Regexp matching a dot-separated sequence of typescript names.")
(defconst typescript--plain-method-re
(concat "^\\s-*?\\(" typescript--dotted-name-re "\\)\\.prototype"
"\\.\\(" typescript--name-re "\\)\\s-*?=\\s-*?\\(function\\)\\_>")
"Regexp matching an explicit typescript prototype \"method\" declaration.
Group 1 is a (possibly-dotted) class name, group 2 is a method name,
and group 3 is the 'function' keyword.")
(defconst typescript--plain-class-re
(concat "^\\s-*\\(" typescript--dotted-name-re "\\)\\.prototype"
"\\s-*=\\s-*{")
"Regexp matching a typescript explicit prototype \"class\" declaration.
An example of this is \"Class.prototype = { method1: ...}\".")
(defconst typescript--module-declaration-re
"^\\s-*\\(?:declare\\|\\(?:export\\(?:\\s-+default\\)?\\)\\)?"
"Regexp matching ambient declaration modifier or export declaration.")
;; var NewClass = BaseClass.extend(
(defconst typescript--mp-class-decl-re
(concat "^\\s-*var\\s-+"
"\\(" typescript--name-re "\\)"
"\\s-*=\\s-*"
"\\(" typescript--dotted-name-re
"\\)\\.extend\\(?:Final\\)?\\s-*(\\s-*{?\\s-*$"))
;; var NewClass = Class.create()
(defconst typescript--prototype-obsolete-class-decl-re
(concat "^\\s-*\\(?:var\\s-+\\)?"
"\\(" typescript--dotted-name-re "\\)"
"\\s-*=\\s-*Class\\.create()"))
(defconst typescript--prototype-objextend-class-decl-re-1
(concat "^\\s-*Object\\.extend\\s-*("
"\\(" typescript--dotted-name-re "\\)"
"\\s-*,\\s-*{"))
(defconst typescript--prototype-objextend-class-decl-re-2
(concat "^\\s-*\\(?:var\\s-+\\)?"
"\\(" typescript--dotted-name-re "\\)"
"\\s-*=\\s-*Object\\.extend\\s-*\("))
;; var NewClass = Class.create({
(defconst typescript--prototype-class-decl-re
(concat "^\\s-*\\(?:var\\s-+\\)?"
"\\(" typescript--name-re "\\)"
"\\s-*=\\s-*Class\\.create\\s-*(\\s-*"
"\\(?:\\(" typescript--dotted-name-re "\\)\\s-*,\\s-*\\)?{?"))
;; Parent class name(s) (yes, multiple inheritance in typescript) are
;; matched with dedicated font-lock matchers
(defconst typescript--dojo-class-decl-re
(concat "^\\s-*dojo\\.declare\\s-*(\"\\(" typescript--dotted-name-re "\\)"))
(defconst typescript--exttypescript-class-decl-re-1
(concat "^\\s-*Ext\\.extend\\s-*("
"\\s-*\\(" typescript--dotted-name-re "\\)"
"\\s-*,\\s-*\\(" typescript--dotted-name-re "\\)")
"Regexp matching an ExtTYPESCRIPT class declaration (style 1).")
(defconst typescript--exttypescript-class-decl-re-2
(concat "^\\s-*\\(?:var\\s-+\\)?"
"\\(" typescript--name-re "\\)"
"\\s-*=\\s-*Ext\\.extend\\s-*(\\s-*"
"\\(" typescript--dotted-name-re "\\)")
"Regexp matching an ExtTYPESCRIPT class declaration (style 2).")
(defconst typescript--mochikit-class-re
(concat "^\\s-*MochiKit\\.Base\\.update\\s-*(\\s-*"
"\\(" typescript--dotted-name-re "\\)")
"Regexp matching a MochiKit class declaration.")
(defconst typescript--dummy-class-style
'(:name "[Automatically Generated Class]"))
(defconst typescript--class-styles
`((:name "Plain"
:class-decl ,typescript--plain-class-re
:prototype t
:contexts (toplevel)
:framework typescript)
(:name "MochiKit"
:class-decl ,typescript--mochikit-class-re
:prototype t
:contexts (toplevel)
:framework mochikit)
(:name "Prototype (Obsolete)"
:class-decl ,typescript--prototype-obsolete-class-decl-re
:contexts (toplevel)
:framework prototype)
(:name "Prototype (Modern)"
:class-decl ,typescript--prototype-class-decl-re
:contexts (toplevel)
:framework prototype)
(:name "Prototype (Object.extend)"
:class-decl ,typescript--prototype-objextend-class-decl-re-1
:prototype t
:contexts (toplevel)
:framework prototype)
(:name "Prototype (Object.extend) 2"
:class-decl ,typescript--prototype-objextend-class-decl-re-2
:prototype t
:contexts (toplevel)
:framework prototype)
(:name "Dojo"
:class-decl ,typescript--dojo-class-decl-re
:contexts (toplevel)
:framework dojo)
(:name "ExtTYPESCRIPT (style 1)"
:class-decl ,typescript--exttypescript-class-decl-re-1
:prototype t
:contexts (toplevel)
:framework exttypescript)
(:name "ExtTYPESCRIPT (style 2)"
:class-decl ,typescript--exttypescript-class-decl-re-2
:contexts (toplevel)
:framework exttypescript)
(:name "Merrill Press"
:class-decl ,typescript--mp-class-decl-re
:contexts (toplevel)
:framework merrillpress))
"List of typescript class definition styles.
A class definition style is a plist with the following keys:
:name is a human-readable name of the class type
:class-decl is a regular expression giving the start of the
class. Its first group must match the name of its class. If there
is a parent class, the second group should match, and it should be
the name of the class.
If :prototype is present and non-nil, the parser will merge
declarations for this constructs with others at the same lexical
level that have the same name. Otherwise, multiple definitions
will create multiple top-level entries. Don't use :prototype
unnecessarily: it has an associated cost in performance.
If :strip-prototype is present and non-nil, then if the class
name as matched contains")
(defconst typescript--available-frameworks
(cl-loop with available-frameworks
for style in typescript--class-styles
for framework = (plist-get style :framework)
unless (memq framework available-frameworks)
collect framework into available-frameworks
finally return available-frameworks)
"List of available typescript frameworks symbols.")
(defconst typescript--function-heading-1-re
(concat
typescript--module-declaration-re
"\\s-*function\\s-+\\(" typescript--name-re "\\)")
"Regexp matching the start of a typescript function header.
Match group 1 is the name of the function.")
(defconst typescript--function-heading-2-re
(concat
"^\\s-*\\(" typescript--name-re "\\)\\s-*:\\s-*function\\_>")
"Regexp matching the start of a function entry in an associative array.
Match group 1 is the name of the function.")
(defconst typescript--function-heading-3-re
(concat
"^\\s-*\\(?:var\\s-+\\)?\\(" typescript--dotted-name-re "\\)"
"\\s-*=\\s-*function\\_>")
"Regexp matching a line in the typescript form \"var MUMBLE = function\".
Match group 1 is MUMBLE.")
(defun typescript--regexp-opt-symbol (list)
"Like `regexp-opt', but surround the result with `\\\\_<' and `\\\\_>'."
(concat "\\_<" (regexp-opt list t) "\\_>"))
(defconst typescript--keyword-re
(typescript--regexp-opt-symbol
'("abstract" "any" "as" "async" "await" "boolean" "bigint" "break" "case" "catch" "class" "const"
"constructor" "continue" "debugger" "declare" "default" "delete" "do" "else"
"enum" "export" "extends" "extern" "false" "finally" "for"
"function" "from" "get" "goto" "if" "implements" "import" "in" "infer" "instanceof"
"interface" "keyof" "let" "module" "namespace" "never" "new" "null" "number" "object" "of"
"override" "private" "protected" "public" "readonly" "return" "satisfies" "set" "static"
"string" "super" "switch" "this" "throw" "true"
"try" "type" "typeof" "unknown" "var" "void"
"while")) ; yield is handled separately
"Regexp matching any typescript keyword.")
(defconst typescript--basic-type-re
(typescript--regexp-opt-symbol
'("any" "bool" "boolean" "bigint" "never" "number" "string" "unknown" "void"))
"Regular expression matching any predefined type in typescript.")
(defconst typescript--access-modifier-re
(typescript--regexp-opt-symbol
'("private" "protected" "public" "readonly" "static" "extends" "implements"))
"Regular expression matching access modifiers.")
(defconst typescript--decorator-re
(concat "\\(@" typescript--name-re "\\)"))
(defconst typescript--constant-re
(typescript--regexp-opt-symbol '("false" "null" "undefined"
"Infinity" "NaN"
"true" "arguments" "this"))
"Regular expression matching any future reserved words in typescript.")
(defconst typescript--builtin-re
(typescript--regexp-opt-symbol
'("console"))
"Regular expression matching builtins.")
(defconst typescript--function-call-re "\\(\\(?:\\w\\|\\s_\\)+\\)\\(<.+>\\)?\s*("
"Regular expression matching function calls.")
(defconst typescript--font-lock-keywords-1
(list
"\\_<import\\_>"
(list typescript--function-heading-1-re 1 font-lock-function-name-face)
(list typescript--function-heading-2-re 1 font-lock-function-name-face))
"Level one font lock keywords for `typescript-mode'.")
(defconst typescript--font-lock-keywords-2
(append typescript--font-lock-keywords-1
(list (cons typescript--constant-re font-lock-constant-face)
(cons typescript--basic-type-re font-lock-type-face)
(list typescript--keyword-re 1 font-lock-keyword-face)
(list "\\_<for\\_>"
"\\s-+\\(each\\)\\_>" nil nil
(list 1 'font-lock-keyword-face))
(cons "\\_<yield\\(\\*\\|\\_>\\)" 'font-lock-keyword-face)))
"Level two font lock keywords for `typescript-mode'.")
;; typescript--pitem is the basic building block of the lexical
;; database. When one refers to a real part of the buffer, the region
;; of text to which it refers is split into a conceptual header and
;; body. Consider the (very short) block described by a hypothetical
;; typescript--pitem:
;;
;; function foo(a,b,c) { return 42; }
;; ^ ^ ^
;; | | |
;; +- h-begin +- h-end +- b-end
;;
;; (Remember that these are buffer positions, and therefore point
;; between characters, not at them. An arrow drawn to a character
;; indicates the corresponding position is between that character and
;; the one immediately preceding it.)
;;
;; The header is the region of text [h-begin, h-end], and is
;; the text needed to unambiguously recognize the start of the
;; construct. If the entire header is not present, the construct is
;; not recognized at all. No other pitems may be nested inside the
;; header.
;;
;; The body is the region [h-end, b-end]. It may contain nested
;; typescript--pitem instances. The body of a pitem may be empty: in
;; that case, b-end is equal to header-end.
;;
;; The three points obey the following relationship:
;;
;; h-begin < h-end <= b-end
;;
;; We put a text property in the buffer on the character *before*
;; h-end, and if we see it, on the character *before* b-end.
;;
;; The text property for h-end, typescript--pstate, is actually a list
;; of all typescript--pitem instances open after the marked character.
;;
;; The text property for b-end, typescript--pend, is simply the
;; typescript--pitem that ends after the marked character. (Because
;; pitems always end when the paren-depth drops below a critical
;; value, and because we can only drop one level per character, only
;; one pitem may end at a given character.)
;;
;; In the structure below, we only store h-begin and (sometimes)
;; b-end. We can trivially and quickly find h-end by going to h-begin
;; and searching for an typescript--pstate text property. Since no other
;; typescript--pitem instances can be nested inside the header of a
;; pitem, the location after the character with this text property
;; must be h-end.
;;
;; typescript--pitem instances are never modified (with the exception
;; of the b-end field). Instead, modified copies are added at subseqnce parse points.
;; (The exception for b-end and its caveats is described below.)
;;
(cl-defstruct (typescript--pitem (:type list))
;; IMPORTANT: Do not alter the position of fields within the list.
;; Various bits of code depend on their positions, particularly
;; anything that manipulates the list of children.
;; List of children inside this pitem's body
(children nil :read-only t)
;; When we reach this paren depth after h-end, the pitem ends
(paren-depth nil :read-only t)
;; Symbol or class-style plist if this is a class
(type nil :read-only t)
;; See above
(h-begin nil :read-only t)
;; List of strings giving the parts of the name of this pitem (e.g.,
;; '("MyClass" "myMethod"), or t if this pitem is anonymous
(name nil :read-only t)
;; THIS FIELD IS MUTATED, and its value is shared by all copies of
;; this pitem: when we copy-and-modify pitem instances, we share
;; their tail structures, so all the copies actually have the same
;; terminating cons cell. We modify that shared cons cell directly.
;;
;; The field value is either a number (buffer location) or nil if
;; unknown.
;;
;; If the field's value is greater than `typescript--cache-end', the
;; value is stale and must be treated as if it were nil. Conversely,
;; if this field is nil, it is guaranteed that this pitem is open up
;; to at least `typescript--cache-end'. (This property is handy when
;; computing whether we're inside a given pitem.)
;;
(b-end nil))
;; The pitem we start parsing with.
(defconst typescript--initial-pitem
(make-typescript--pitem
:paren-depth most-negative-fixnum
:type 'toplevel))
;; When we say "jsdoc" here, we mean "jsdoc 3". There exist multiple dialects of
;; "jsdoc documentation".
;; Note that all typedoc/jsdoc regexp by themselves would match occurrences that appear outside
;; documentation comments. The logic that uses these regexps must guard against it.
(defconst typescript-typedoc-link-tag-regexp
"\\[\\[.*?\\]\\]"
"Matches a typedoc link.")
(defconst typescript-typedoc-literal-markup-regexp
"\\(`+\\).*?\\1"
"Matches a typedoc keyword markup.")
(defconst typescript-jsdoc-before-tag-regexp
"\\(?:^\\s-*\\*+\\|/\\*\\*\\)\\s-*"
"Matches everything we allow before the @ of a jsdoc tag.")
;; This was taken from js2-mode.
(defconst typescript-jsdoc-param-tag-regexp
(concat typescript-jsdoc-before-tag-regexp
"\\(@"
(regexp-opt
'("arg"
"argument"
"param"
"prop"
"property"
"typedef"))
"\\)"
"\\s-*\\({[^}]+}\\)?" ; optional type
"\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
"\\_>")
"Matches jsdoc tags with optional type and optional param name.")
;; This was taken from js2-mode.
;; and extended with tags in http://usejsdoc.org/
(defconst typescript-jsdoc-typed-tag-regexp
(concat typescript-jsdoc-before-tag-regexp
"\\(@"
(regexp-opt
'("enum"
"extends"
"field"
"id"
"implements"
"lends"
"mods"
"requires"
"return"
"returns"
"throw"
"throws"
"type"
"yield"
"yields"))
"\\)\\s-*\\({[^}]+}\\)?")
"Matches jsdoc tags with optional type.")
;; This was taken from js2-mode.
;; and extended with tags in http://usejsdoc.org/
(defconst typescript-jsdoc-arg-tag-regexp
(concat typescript-jsdoc-before-tag-regexp
"\\(@"
(regexp-opt
'("access"
"alias"
"augments"
"base"
"borrows"
"bug"
"callback"
"config"
"default"
"define"
"emits"
"exception"
"extends"
"external"
"fires"
"func"
"function"
"host"
"kind"
"listens"
"member"
"memberof"
"method"
"mixes"
"module"
"name"
"namespace"
"requires"
"since"
"suppress"
"this"
"throws"
"var"
"variation"
"version"))
"\\)\\s-+\\([^ \t]+\\)")
"Matches jsdoc tags with a single argument.")
;; This was taken from js2-mode
;; and extended with tags in http://usejsdoc.org/
(defconst typescript-jsdoc-empty-tag-regexp
(concat typescript-jsdoc-before-tag-regexp
"\\(@"
(regexp-opt
'("abstract"
"addon"
"async"
"author"
"class"
"classdesc"
"const"
"constant"
"constructor"
"constructs"
"copyright"
"default"
"defaultvalue"
"deprecated"
"desc"
"description"
"event"
"example"
"exec"
"export"
"exports"
"file"
"fileoverview"
"final"
"func"
"function"
"generator"
"global"
"hidden"
"hideconstructor"
"ignore"
"implicitcast"
"inheritdoc"
"inner"
"instance"
"interface"
"license"
"method"
"mixin"
"noalias"
"noshadow"
"notypecheck"
"override"
"overview"
"owner"
"package"
"preserve"
"preservetry"
"private"
"protected"
"public"
"readonly"
"static"
"summary"
"supported"
"todo"
"tutorial"
"virtual"))
"\\)\\s-*")
"Matches empty jsdoc tags.")
;; Note that this regexp by itself would match tslint flags that appear inside
;; strings. The logic using this regexp must guard against it.
(defconst typescript-tslint-flag-regexp
"\\(?://\\|/\\*\\)\\s-*\\(tslint:.*?\\)\\(?:\\*/\\|$\\)"
"Matches tslint flags.")
;;; Faces
(defface typescript-jsdoc-tag
'((t :foreground "SlateGray"))
"Face used to highlight @whatever tags in jsdoc comments."
:group 'typescript)
(defface typescript-jsdoc-type
'((t :foreground "SteelBlue"))
"Face used to highlight {FooBar} types in jsdoc comments."
:group 'typescript)
(defface typescript-jsdoc-value
'((t :foreground "gold4"))
"Face used to highlight tag values in jsdoc comments."
:group 'typescript)
(defface typescript-access-modifier-face
'((t (:inherit font-lock-keyword-face)))
"Face used to highlight access modifiers."
:group 'typescript)
(defface typescript-this-face
'((t (:inherit font-lock-keyword-face)))
"Face used to highlight 'this' keyword."
:group 'typescript)
(defface typescript-primitive-face
'((t (:inherit font-lock-keyword-face)))
"Face used to highlight builtin types."
:group 'typescript)
;;; User Customization
(defgroup typescript nil
"Customization variables for typescript mode."
:tag "typescript"
:group 'languages)
(defcustom typescript-indent-level 4
"Number of spaces for each indentation step in `typescript-mode'."
:type 'integer
:safe 'integerp
:group 'typescript)
;;;###autoload(put 'typescript-indent-level 'safe-local-variable #'integerp)
(defcustom typescript-expr-indent-offset 0
"Number of additional spaces used for indentation of continued expressions.
The value must be no less than minus `typescript-indent-level'."
:type 'integer
:safe 'integerp
:group 'typescript)
(defcustom typescript-indent-switch-clauses t
"Enable indenting of switch case and default clauses to
replicate tsserver behaviour. Indent level is taken to be
`typescript-indent-level'."
:type 'boolean
:group 'typescript)
(defcustom typescript-indent-list-items t
"Enable indenting of list items, useful for certain code styles."
:type 'boolean
:group 'typescript)
(defcustom typescript-auto-indent-flag t
"Whether to automatically indent when typing punctuation characters.
If non-nil, the characters {}();,: also indent the current line
in typescript mode."
:type 'boolean
:group 'typescript)
(defcustom typescript-flat-functions nil
"Treat nested functions as top-level functions in `typescript-mode'.
This applies to function movement, marking, and so on."
:type 'boolean
:group 'typescript)
(defcustom typescript-comment-lineup-func #'c-lineup-C-comments
"Lineup function for `cc-mode-style', for C comments in `typescript-mode'."
:type 'function
:group 'typescript)
(defcustom typescript-enabled-frameworks typescript--available-frameworks
"Frameworks recognized by `typescript-mode'.
To improve performance, you may turn off some frameworks you
seldom use, either globally or on a per-buffer basis."
:type (cons 'set (mapcar (lambda (x)
(list 'const x))
typescript--available-frameworks))
:group 'typescript)
(defcustom typescript-mode-hook nil
"*Hook called by `typescript-mode'."
:type 'hook
:group 'typescript)
(defcustom typescript-autoconvert-to-template-flag nil
"Non-nil means automatically convert plain strings to templates.
When the flag is non-nil the `typescript-autoconvert-to-template'
is called whenever a plain string delimiter is typed in the buffer."
:type 'boolean
:group 'typescript)
;;; Public utilities
(defun typescript-convert-to-template ()
"Convert the string at point to a template string."
(interactive)
(save-restriction
(widen)
(save-excursion
(let* ((syntax (syntax-ppss))
(str-terminator (nth 3 syntax))
(string-start (or (and str-terminator (nth 8 syntax))
;; We have to consider the case that we're on the start delimiter of a string.
;; We tentatively take (point) as string-start. If it turns out we're
;; wrong, then typescript--move-to-end-of-plain-string will fail anyway,
;; and we won't use the bogus value.
(progn
(forward-char)
(point)))))
(when (typescript--move-to-end-of-plain-string)
(let ((end-start (or (nth 8 (syntax-ppss)) -1)))
(undo-boundary)
(when (= end-start string-start)
(delete-char 1)
(insert "`")))
(goto-char string-start)
(delete-char 1)
(insert "`"))))))
(defun typescript-autoconvert-to-template ()
"Automatically convert a plain string to a teplate string, if needed.
This function is meant to be automatically invoked when the user
enters plain string delimiters. It checks whether the character
before point is the end of a string. If it is, then it checks
whether the string contains ${...}. If it does, then it converts
the string from a plain string to a template."
(interactive)
(save-restriction
(widen)
(save-excursion
(backward-char)
(when (and (memq (char-after) '(?' ?\"))
(not (eq (char-before) ?\\)))
(let* ((string-start (nth 8 (syntax-ppss))))
(when (and string-start
(save-excursion
(re-search-backward "\\${.*?}" string-start t)))
(typescript-convert-to-template)))))))
;;; KeyMap
(defvar typescript-mode-map
(let ((keymap (make-sparse-keymap)))
(define-key keymap (kbd "C-c '") #'typescript-convert-to-template)
keymap)
"Keymap for `typescript-mode'.")
(defun typescript--post-self-insert-function ()
(when (and (derived-mode-p 'typescript-mode)
typescript-autoconvert-to-template-flag
(or (eq last-command-event ?\')
(eq last-command-event ?\")))
(typescript-autoconvert-to-template)))
;;; Syntax table and parsing
(defvar typescript-mode-syntax-table
(let ((table (make-syntax-table)))
(c-populate-syntax-table table)
(modify-syntax-entry ?$ "_" table)
(modify-syntax-entry ?` "\"" table)
table)
"Syntax table for `typescript-mode'.")
(defvar typescript--quick-match-re nil
"Autogenerated regexp used by `typescript-mode' to match buffer constructs.")
(defvar typescript--quick-match-re-func nil
"Autogenerated regexp used by `typescript-mode' to match constructs and functions.")
(make-variable-buffer-local 'typescript--quick-match-re)
(make-variable-buffer-local 'typescript--quick-match-re-func)
(defvar typescript--cache-end 1
"Last valid buffer position for the `typescript-mode' function cache.")
(make-variable-buffer-local 'typescript--cache-end)
(defvar typescript--last-parse-pos nil
"Latest parse position reached by `typescript--ensure-cache'.")
(make-variable-buffer-local 'typescript--last-parse-pos)
(defvar typescript--state-at-last-parse-pos nil
"Parse state at `typescript--last-parse-pos'.")
(make-variable-buffer-local 'typescript--state-at-last-parse-pos)
(defun typescript--flatten-list (list)
(cl-loop for item in list
nconc (cond ((consp item)
(typescript--flatten-list item))
(item (list item)))))
(defun typescript--maybe-join (prefix separator suffix &rest list)
"Helper function for `typescript--update-quick-match-re'.
If LIST contains any element that is not nil, return its non-nil
elements, separated by SEPARATOR, prefixed by PREFIX, and ended
with SUFFIX as with `concat'. Otherwise, if LIST is empty, return
nil. If any element in LIST is itself a list, flatten that
element."
(setq list (typescript--flatten-list list))
(when list
(concat prefix (mapconcat #'identity list separator) suffix)))
(defun typescript--update-quick-match-re ()
"Internal function used by `typescript-mode' for caching buffer constructs.
This updates `typescript--quick-match-re', based on the current set of
enabled frameworks."
(setq typescript--quick-match-re
(typescript--maybe-join
"^[ \t]*\\(?:" "\\|" "\\)"
;; #define mumble
"#define[ \t]+[a-zA-Z_]"
(when (memq 'exttypescript typescript-enabled-frameworks)
"Ext\\.extend")
(when (memq 'prototype typescript-enabled-frameworks)
"Object\\.extend")
;; var mumble = THING (
(typescript--maybe-join
"\\(?:var[ \t]+\\)?[a-zA-Z_$0-9.]+[ \t]*=[ \t]*\\(?:"
"\\|"
"\\)[ \t]*\("
(when (memq 'prototype typescript-enabled-frameworks)
"Class\\.create")
(when (memq 'exttypescript typescript-enabled-frameworks)
"Ext\\.extend")
(when (memq 'merrillpress typescript-enabled-frameworks)
"[a-zA-Z_$0-9]+\\.extend\\(?:Final\\)?"))
(when (memq 'dojo typescript-enabled-frameworks)
"dojo\\.declare[ \t]*\(")
(when (memq 'mochikit typescript-enabled-frameworks)
"MochiKit\\.Base\\.update[ \t]*\(")
;; mumble.prototypeTHING
(typescript--maybe-join
"[a-zA-Z_$0-9.]+\\.prototype\\(?:" "\\|" "\\)"
(when (memq 'typescript typescript-enabled-frameworks)
'( ;; foo.prototype.bar = function(
"\\.[a-zA-Z_$0-9]+[ \t]*=[ \t]*function[ \t]*\("
;; mumble.prototype = {
"[ \t]*=[ \t]*{")))))
(setq typescript--quick-match-re-func
(concat "function\\|" typescript--quick-match-re)))
(defun typescript--forward-text-property (propname)
"Move over the next value of PROPNAME in the buffer.
If found, return that value and leave point after the character
having that value; otherwise, return nil and leave point at EOB."
(let ((next-value (get-text-property (point) propname)))
(if next-value
(forward-char)
(goto-char (next-single-property-change
(point) propname nil (point-max)))
(unless (eobp)
(setq next-value (get-text-property (point) propname))
(forward-char)))
next-value))
(defun typescript--backward-text-property (propname)
"Move over the previous value of PROPNAME in the buffer.
If found, return that value and leave point just before the
character that has that value, otherwise return nil and leave
point at BOB."
(unless (bobp)
(let ((prev-value (get-text-property (1- (point)) propname)))
(if prev-value
(backward-char)
(goto-char (previous-single-property-change
(point) propname nil (point-min)))
(unless (bobp)
(backward-char)
(setq prev-value (get-text-property (point) propname))))
prev-value)))
(defsubst typescript--forward-pstate ()
(typescript--forward-text-property 'typescript--pstate))
(defsubst typescript--backward-pstate ()
(typescript--backward-text-property 'typescript--pstate))
(defun typescript--pitem-goto-h-end (pitem)
(goto-char (typescript--pitem-h-begin pitem))
(typescript--forward-pstate))
(defun typescript--re-search-forward-inner (regexp &optional bound count)
"Helper function for `typescript--re-search-forward'."
(let ((parse)
str-terminator)
(while (> count 0)
(re-search-forward regexp bound)
(setq parse (syntax-ppss))
(cond ((setq str-terminator (nth 3 parse))
(when (eq str-terminator t)
(setq str-terminator ?/))
(re-search-forward
(concat "\\([^\\]\\|^\\)" (string str-terminator))
(save-excursion (end-of-line) (point)) t))
((nth 7 parse)
(forward-line))
((or (nth 4 parse)
(and (eq (char-before) ?\/) (eq (char-after) ?\*)))
(re-search-forward "\\*/"))
(t
(setq count (1- count))))))
(point))
(defun typescript--re-search-forward (regexp &optional bound noerror count)
"Search forward, ignoring strings and comments.
This function invokes `re-search-forward', but treats the buffer
as if strings and comments have been removed."
(let ((saved-point (point))
(search-expr
(cond ((null count)
'(typescript--re-search-forward-inner regexp bound 1))
((< count 0)
'(typescript--re-search-backward-inner regexp bound (- count)))
((> count 0)
'(typescript--re-search-forward-inner regexp bound count)))))
(condition-case err
(eval search-expr)
(search-failed
(goto-char saved-point)
(unless noerror
(error (error-message-string err)))))))
(defun typescript--re-search-backward-inner (regexp &optional bound count)
"Auxiliary function for `typescript--re-search-backward'."
(let ((parse))
(while (> count 0)
(re-search-backward regexp bound)
(when (and (> (point) (point-min))
(save-excursion (backward-char) (looking-at "/[/*]")))
(forward-char))
(setq parse (syntax-ppss))
(cond
;; If we are in a comment or a string, jump back to the start
;; of the comment or string.
((nth 8 parse)
(goto-char (nth 8 parse)))
((and (eq (char-before) ?/) (eq (char-after) ?*))
(re-search-backward "/\\*"))
(t
(setq count (1- count))))))
(point))
(defun typescript--re-search-backward (regexp &optional bound noerror count)
"Search backward, ignoring strings, and comments.
This function invokes `re-search-backward' but treats the buffer
as if strings and comments have been removed.
IMPORTANT NOTE: searching for \"\\n\" with this function to find
line breaks will generally not work, because the final newline of
a one-line comment is considered to be part of the comment and
will be skipped. Take the following code:
let a = 1;
let b = 2; // Foo
let c = 3;
If the point is in the last line, searching back for \"\\n\" will
skip over the line with \"let b\". The newline found will be the
one at the end of the line with \"let a\"."
(let ((saved-point (point))
(search-expr
(cond ((null count)
`(typescript--re-search-backward-inner ,regexp ,bound 1))
((< count 0)
`(typescript--re-search-forward-inner ,regexp ,bound (- ,count)))
((> count 0)
`(typescript--re-search-backward-inner ,regexp ,bound ,count)))))
(condition-case err