-
Notifications
You must be signed in to change notification settings - Fork 110
/
tide.el
3160 lines (2723 loc) · 122 KB
/
tide.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
;;; tide.el --- Typescript Interactive Development Environment -*- lexical-binding: t -*-
;; Copyright (C) 2015 Anantha Kumaran.
;; Author: Anantha kumaran <ananthakumaran@gmail.com>
;; URL: http://github.com/ananthakumaran/tide
;; Version: 5.1.3
;; Keywords: typescript
;; Package-Requires: ((emacs "25.1") (dash "2.10.0") (s "1.11.0") (flycheck "27") (cl-lib "0.5"))
;; 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/>.
;; This file is not part of GNU Emacs.
;;; Commentary:
;;; Code:
(require 'etags)
(require 'json)
(require 'cl-lib)
(require 'eldoc)
(require 'dash)
(require 's)
(require 'flycheck)
(require 'imenu)
(require 'thingatpt)
(require 'tide-lv)
(require 'tabulated-list)
(require 'xref)
;; Silence compiler warnings
(defvar js2-basic-offset)
(defvar js-indent-level)
(defvar js3-indent-level)
(defvar web-mode-code-indent-offset)
(defvar sgml-basic-offset)
(defvar company-backends)
(declare-function company-grab "company.el" (regexp &optional expression limit))
(declare-function company-grab-symbol-cons "company.el" (idle-begin-after-re &optional max-len))
(declare-function company-begin-backend "company.el" (backend &optional callback))
(declare-function company-in-string-or-comment "company.el" nil)
(defgroup tide nil
"TypeScript Interactive Development Environment."
:prefix "tide-"
:group 'tools)
(defcustom tide-sync-request-timeout 2
"The number of seconds to wait for a sync response."
:type 'integer
:group 'tide)
(defcustom tide-tsserver-flags nil
"List of additional flags to provide when starting tsserver."
:type '(repeat string)
:group 'tide)
(defcustom tide-tsserver-process-environment '()
"List of extra environment variables to use when starting tsserver."
:type '(repeat string)
:group 'tide)
(defcustom tide-tsserver-executable nil
"Name of tsserver executable to run instead of the bundled tsserver.
This may either be an absolute path or a relative path. Relative
paths are resolved against the project root directory.
Note that this option only works with TypeScript version 2.0 and
above."
:type '(choice (const nil) string)
:group 'tide)
(defcustom tide-tscompiler-executable nil
"Name of tsc executable.
This may either be an absolute path or a relative path. Relative
paths are resolved against the project root directory."
:type '(choice (const nil) string)
:group 'tide)
(defcustom tide-node-executable "node"
"Name or path of the node executable binary file."
:type '(choice (const nil) string)
:group 'tide)
(defcustom tide-node-flags nil
"List of flags to provide to node when starting tsserver.
Useful for large TypeScript codebases which need to set
max-old-space-size to a higher value."
:type '(repeat string)
:group 'tide)
(defcustom tide-post-code-edit-hook nil
"Hook run after code edits are applied in a buffer."
:type 'hook
:group 'tide)
(defcustom tide-sort-completions-by-kind nil
"Whether completions should be sorted by kind."
:type 'boolean
:group 'tide)
(defcustom tide-format-options '()
"Format options plist."
:type '(plist :value-type sexp)
:group 'tide)
(defcustom tide-user-preferences
'(:includeCompletionsForModuleExports t :includeCompletionsWithInsertText t :allowTextChangesInNewFiles t :generateReturnInDocTemplate t)
"User preference plist used on the configure request.
Check https://github.com/Microsoft/TypeScript/blob/17eaf50b/src/server/protocol.ts#L2684
for the full list of available options."
:type '(plist :value-type sexp)
:group 'tide)
(defcustom tide-disable-suggestions nil
"Disable suggestions.
If set to non-nil, suggestions will not be shown in flycheck
errors and tide-project-errors buffer."
:type 'boolean
:group 'tide)
(defcustom tide-completion-setup-company-backend t
"Add `company-tide' to `company-backends'."
:type 'boolean
:group 'tide)
(defcustom tide-completion-ignore-case nil
"CASE will be ignored in completion if set to non-nil."
:type 'boolean
:group 'tide)
(defcustom tide-completion-show-source nil
"Completion dropdown will contain completion source if set to non-nil."
:type 'boolean
:group 'tide)
(defcustom tide-completion-fuzzy nil
"Allow fuzzy completion.
By default only candidates with exact prefix match are shown. If
set to non-nil, candidates with match anywhere inside the name
are shown."
:type 'boolean
:group 'tide)
(defcustom tide-completion-detailed nil
"Completion dropdown will contain detailed method information if set to non-nil."
:type 'boolean
:group 'tide)
(defcustom tide-completion-enable-autoimport-suggestions t
"Whether to include external module exports in completions."
:type 'boolean
:group 'tide)
(defcustom tide-enable-xref t
"Whether to enable xref integration."
:type 'boolean
:group 'tide)
(defcustom tide-navto-item-filter #'tide-navto-item-filter-default
"The filter for items returned by tide-nav. Defaults to class, interface, type, enum"
:type 'function
:group 'tide)
(defface tide-file
'((t (:inherit font-lock-type-face)))
"Face for file names in references output."
:group 'tide)
(defface tide-line-number
'((t (:inherit compilation-line-number)))
"Face for line numbers in references output."
:group 'tide)
(defface tide-match
'((t (:inherit match)))
"Face for matched symbol in references output."
:group 'tide)
(defface tide-imenu-type-face
'((t (:inherit font-lock-type-face)))
"Face for type in imenu list."
:group 'tide)
(defface tide-choice-face
'((t (:inherit font-lock-warning-face)))
"Face for choices used in popup window."
:group 'tide)
(defcustom tide-jump-to-definition-reuse-window t
"Reuse existing window when jumping to definition."
:type 'boolean
:group 'tide)
(defcustom tide-imenu-flatten nil
"Imenu index will be flattened if set to non-nil."
:type 'boolean
:group 'tide)
(defcustom tide-allow-popup-select '(code-fix refactor)
"The list of commands where popup selection is allowed."
:type '(set (const code-fix) (const jump-to-implementation) (const refactor))
:group 'tide)
(defcustom tide-always-show-documentation nil
"Show the documentation window even if only type information is available."
:type 'boolean
:group 'tide)
(defcustom tide-server-max-response-length 102400
"Maximum allowed response length from tsserver. Any response greater than this would be ignored."
:type 'integer
:group 'tide)
(defcustom tide-tsserver-locator-function #'tide-tsserver-locater-npmlocal-projectile-npmglobal
"Function used by tide to locate tsserver."
:type 'function
:group 'tide)
(defcustom tide-project-cleanup-delay 60
"The number of idle seconds to wait before cleaning up unused tsservers.
Use `nil` to disable automatic cleanups. See also `tide-do-cleanups`."
:type '(choice (const nil) integer)
:group 'tide)
(defcustom tide-tsserver-start-method 'immediate
"The method by which tide starts tsserver. `immediate' causes tide to start a tsserver instance
as soon as `tide-mode' is turned on. `manual' means that tide will start a tsserver only when the
user manually starts one."
:type '(choice (const :tag "Start immediately." immediate)
(const :tag "Require manual start." manual))
:group 'tide)
(defcustom tide-default-mode "TS"
"The default mode to open buffers not backed by files (e.g. Org
source blocks) in."
:type '(choice (const "TS") (const "TSX") (const "JS")(const "JSX"))
:group 'tide)
(defcustom tide-recenter-after-jump t
"Recenter buffer after jumping to definition"
:type 'boolean
:group 'tide)
(defcustom tide-jump-to-fallback #'tide-jump-to-fallback-not-given
"The fallback jump function to use when implementations aren't available."
:type 'function
:group 'tide)
(defcustom tide-filter-out-warning-completions nil
"Completions whose `:kind' property is \"warning\" will be filtered out if set to non-nil.
This option is useful for Javascript code completion, because tsserver often returns a lot of irrelevant
completions whose `:kind' property is \"warning\" for Javascript code. You can fix this behavior by setting
this variable to non-nil value for Javascript buffers using `setq-local' macro."
:type 'boolean
:group 'tide
:safe #'booleanp)
(defcustom tide-native-json-parsing (and (>= emacs-major-version 27)
(functionp 'json-serialize)
(functionp 'json-parse-buffer)
(functionp 'json-parse-string))
"Use native JSON parsing (only emacs >= 27)."
:type 'boolean
:group 'tide)
(defcustom tide-save-buffer-after-code-edit t
"Save the buffer after applying code edits."
:type 'boolean
:group 'tide)
(defconst tide--minimal-emacs
"25.1"
"This is the oldest version of Emacs that tide supports.")
(defmacro tide-def-permanent-buffer-local (name &optional init-value)
"Declare NAME as buffer local variable."
`(progn
(defvar ,name ,init-value)
(make-variable-buffer-local ',name)
(put ',name 'permanent-local t)))
(defvar tide-supported-modes '(typescript-mode typescript-ts-mode tsx-ts-mode web-mode js-mode js2-mode js2-jsx-mode js3-mode rjsx-mode))
(defvar tide-server-buffer-name "*tide-server*")
(defvar tide-request-counter 0)
(defvar tide-project-configs (make-hash-table :test 'equal))
(defvar tide-max-response-length-error-message
"Response length from tsserver is greater than maximum allowed response.")
(tide-def-permanent-buffer-local tide-project-root nil)
(tide-def-permanent-buffer-local tide-buffer-dirty nil)
(tide-def-permanent-buffer-local tide-buffer-tmp-file nil)
(tide-def-permanent-buffer-local tide-active-buffer-file-name nil)
(tide-def-permanent-buffer-local tide-require-manual-setup nil)
(defvar tide-servers (make-hash-table :test 'equal))
(defvar tide-response-callbacks (make-hash-table :test 'equal))
(defvar tide-source-root-directory (file-name-directory (or load-file-name buffer-file-name)))
(defvar tide-tsserver-directory (expand-file-name "tsserver" tide-source-root-directory))
(defun tide-project-root ()
"Project root folder determined based on the presence of tsconfig.json."
(or
tide-project-root
(let ((root (or (locate-dominating-file default-directory "tsconfig.json")
(locate-dominating-file default-directory "jsconfig.json"))))
(unless root
(message (tide-join (list "Couldn't locate project root folder with"
" a tsconfig.json or jsconfig.json file. Using '"
default-directory "' as project root.")))
(setq root default-directory))
(let ((full-path (expand-file-name root)))
(setq tide-project-root full-path)
full-path))))
(defun tide-project-name ()
(let ((full-path (directory-file-name (tide-project-root))))
(concat (file-name-nondirectory full-path) "-" (substring (md5 full-path) 0 10))))
(defun tide-buffer-file-name ()
"Returns the path to either the currently open file or the
current buffer's parent. This is needed to support indirect
buffers, as they don't set `buffer-file-name' correctly."
(buffer-file-name (or (and (bound-and-true-p edit-indirect--overlay)
(overlay-buffer edit-indirect--overlay))
(and (bound-and-true-p org-src--overlay)
(overlay-buffer org-src--overlay))
;; Needed for org-mode 8.x compatibility
(and (bound-and-true-p org-edit-src-overlay)
(overlay-buffer org-edit-src-overlay))
(buffer-base-buffer))))
;;; Compatibility
(defvar tide-tsserver-unsupported-commands (make-hash-table :test 'equal))
(defun tide-mark-as-unsupported (command)
(puthash
(tide-project-name)
(cl-pushnew
command
(gethash (tide-project-name) tide-tsserver-unsupported-commands '()))
tide-tsserver-unsupported-commands))
(defun tide-unsupported-p (command)
(member command (gethash (tide-project-name) tide-tsserver-unsupported-commands '())))
(defmacro tide-fallback-if-not-supported (new-command new old cb)
`(if (tide-unsupported-p ,new-command)
(,old ,cb)
(,new
(lambda (response)
(if (tide-command-unknown-p response)
(progn
(tide-mark-as-unsupported ,new-command)
(,old ,cb))
(funcall ,cb response))))))
(defun tide--emacs-at-least (version)
"Return t if Emacs is at least at version VERSION. Return nil, otherwise."
(not (version< emacs-version version)))
;;; Helpers
(defun tide-safe-json-read-file (filename)
(condition-case nil
(if tide-native-json-parsing
(with-temp-buffer
(insert-file-contents filename)
(goto-char (point-min))
(json-parse-buffer :object-type 'plist :null-object json-null :false-object json-false))
(let ((json-object-type 'plist))
(json-read-file filename)))
(error '())))
(defun tide-safe-json-read-string (string)
(condition-case nil
(if tide-native-json-parsing
(json-parse-string string :object-type 'plist :null-object json-null :false-object json-false)
(let ((json-object-type 'plist))
(json-read-from-string string)))
(error '())))
(defun tide-json-read-object ()
(if tide-native-json-parsing
(json-parse-buffer :object-type 'plist :null-object json-null :false-object json-false :array-type 'list)
(let ((json-object-type 'plist)
(json-array-type 'list))
(json-read-object))))
(defun tide-json-encode (obj)
"Encode OBJ into a JSON string. JSON arrays must be represented with vectors."
(if tide-native-json-parsing
(json-serialize obj :null-object json-null :false-object json-false)
(json-encode obj)))
(defun tide-plist-get (list &rest args)
(cl-reduce
(lambda (object key)
(when object
(plist-get object key)))
args
:initial-value list))
(eval-and-compile
(defun tide-plist-map (fn plist)
(when (and plist (not (cl-evenp (length plist))))
(error "Invalid plist %S" plist))
(-map (-lambda ((key value)) (funcall fn key value)) (-partition 2 plist))))
(defun tide-combine-plists (&rest plists)
"Create a single property list from all plists in PLISTS.
The process starts by copying the first list, and then setting properties
from the other lists. Settings in the last list are the most significant
ones and overrule settings in the other lists."
(let ((rtn (copy-sequence (pop plists)))
p v ls)
(while plists
(setq ls (pop plists))
(while ls
(setq p (pop ls) v (pop ls))
(setq rtn (plist-put rtn p v))))
rtn))
(defun tide-get-file-buffer (file &optional new-file)
"Returns a buffer associated with a file. This will return the
current buffer if it matches `file'. This way we can support
temporary and indirect buffers."
(cond
((equal file (tide-buffer-file-name)) (current-buffer))
((file-exists-p file) (find-file-noselect file))
(new-file (let ((buffer (create-file-buffer file)))
(with-current-buffer buffer
(set-visited-file-name file)
(basic-save-buffer)
(display-buffer buffer t))
buffer))
(t (error "Invalid file %S" file))))
(defun tide-response-success-p (response)
(and response (equal (plist-get response :success) t)))
(defun tide-command-unknown-p (response)
(and response (string-equal (plist-get response :command) "unknown")))
(defun tide-tsserver-version-not-supported ()
(error "Only tsserver 2.0 or greater is supported. Upgrade your tsserver or use older version of tide."))
(defun tide-tsserver-feature-not-supported (min-version)
(error "tsserver %S or greater is required for this feature." min-version))
(defmacro tide-on-response-success (response &optional options &rest body)
"BODY must be a single expression if OPTIONS is not passed."
(declare (indent 2))
(unless body
(setq body `(,options))
(setq options '()))
(tide-plist-map
(lambda (key _value)
(unless (member key '(:ignore-empty :min-version))
(error "Invalid options %S" options)))
options)
(let ((ignore-empty-response (plist-get options :ignore-empty))
(min-version (plist-get options :min-version)))
`(cond ((and ,min-version (tide-command-unknown-p ,response)) (tide-tsserver-feature-not-supported ,min-version))
((tide-response-success-p ,response)
(progn
,@body))
(t
(-when-let (msg (plist-get ,response :message))
(unless (and ,ignore-empty-response (string-equal msg "No content available."))
(message "%s" msg))
nil)))))
(defmacro tide-on-response-success-callback (response &optional options &rest body)
(declare (indent 2))
`(lambda (,response)
(tide-on-response-success ,response ,options
,@body)))
(defun tide-join (list)
(mapconcat 'identity list ""))
(defun tide-each-buffer (project-name fn)
"Callback FN for each buffer within PROJECT-NAME with tide-mode enabled."
(-each (buffer-list)
(lambda (buffer)
(with-current-buffer buffer
(when (and (bound-and-true-p tide-mode)
(equal (tide-project-name) project-name))
(funcall fn))))))
(defun tide-first-buffer (project-name fn)
"Callback FN for the first buffer within PROJECT-NAME with tide-mode enabled."
(-when-let (buffer (-first (lambda (buffer)
(with-current-buffer buffer
(and (bound-and-true-p tide-mode)
(equal (tide-project-name) project-name))))
(buffer-list)))
(with-current-buffer buffer
(funcall fn))))
(defun tide-line-number-at-pos (&optional pos)
(let ((p (or pos (point))))
(if (= (point-min) 1)
(line-number-at-pos p)
(save-excursion
(save-restriction
(widen)
(line-number-at-pos p))))))
(defun tide-current-offset ()
"Number of characters present from the begining of line to cursor in current line.
Offset is one based."
(1+ (- (point) (line-beginning-position))))
(defun tide-offset (pos)
(save-excursion
(save-restriction
(widen)
(goto-char pos)
(tide-current-offset))))
(defun tide-span-to-position (span)
(save-excursion
(save-restriction
(widen)
(goto-char (point-min))
(forward-line (1- (plist-get span :line)))
(beginning-of-line)
(forward-char (1- (plist-get span :offset)))
(point))))
(defun tide-file-span-first-line-text (file-span &optional string)
(let (end-offset text)
(save-excursion
(with-current-buffer (tide-get-file-buffer (plist-get file-span :file))
(tide-move-to-location (plist-get file-span :start))
(when string
(search-forward string (tide-location-to-point (plist-get file-span :end)))
(setq end-offset (current-column)))
(setq text (substring-no-properties (replace-regexp-in-string "\n" "" (thing-at-point 'line))))
(when string
(put-text-property (- end-offset (length string)) end-offset 'face 'tide-match text))
text))))
(defun tide-display-help-buffer (feature body)
(let ((buffer (tide-make-help-buffer feature body)))
(display-buffer buffer t)
(if help-window-select
(progn
(pop-to-buffer buffer)
(message "Type \"q\" to restore previous buffer"))
(message (concat "Type \"q\" in the " feature " buffer to close it")))))
(defun tide-make-help-buffer (feature body)
(with-current-buffer (get-buffer-create (concat "*tide-" feature "*"))
(setq buffer-read-only t)
(let ((inhibit-read-only t))
(erase-buffer)
(when body
(save-excursion
(tide-insert body))))
(local-set-key (kbd "q") #'quit-window)
(current-buffer)))
(defvar tide-alphabets '(?a ?s ?d ?f ?j ?k ?l))
(defun tide-popup-select-item (prompt list)
(let ((hints (-map-indexed
(lambda (i item)
(concat (propertize (char-to-string (nth i tide-alphabets)) 'face 'tide-choice-face)
" "
item))
list)))
(unwind-protect
(progn
(tide-lv-message (mapconcat 'identity hints "\n"))
(let ((selected (read-char-choice prompt (-take (length list) tide-alphabets))))
(nth (-find-index (lambda (char) (eql selected char)) tide-alphabets) list)))
(tide-lv-delete-window))))
(defun tide-completing-read-select-item (prompt list)
(completing-read prompt list nil t))
(defun tide-can-use-popup-p (feature)
(member feature tide-allow-popup-select))
(defun tide-select-item-from-list (prompt list label-fn allow-popup)
(let ((collection (make-hash-table :test 'equal)))
(dolist (item list)
(puthash (funcall label-fn item) item collection))
(let ((selected-text
(if (and (<= (length list) (length tide-alphabets)) allow-popup)
(tide-popup-select-item prompt (hash-table-keys collection))
(tide-completing-read-select-item prompt (hash-table-keys collection)))))
(gethash selected-text collection))))
(defun tide-command-to-string (program args)
(with-temp-buffer
(apply #'process-file (-concat (list program nil t nil) args))
(buffer-string)))
;;; Events
(defvar tide-event-listeners (make-hash-table :test 'equal))
(defun tide-set-event-listener (listener)
(puthash (tide-project-name) (cons (current-buffer) listener) tide-event-listeners))
(defun tide-clear-event-listener ()
(remhash (tide-project-name) tide-event-listeners))
;;; Server
(defun tide-current-server ()
(gethash (tide-project-name) tide-servers))
(defun tide-next-request-id ()
(number-to-string (cl-incf tide-request-counter)))
(defun tide-dispatch-response (response)
(let* ((request-id (plist-get response :request_seq))
(callback (gethash request-id tide-response-callbacks)))
(when callback
(let ((buffer (car callback)))
(when (buffer-live-p buffer)
(with-current-buffer buffer
(apply (cdr callback) (list response)))))
(remhash request-id tide-response-callbacks))))
(defun tide-dispatch-event (event)
(-when-let (listener (gethash (tide-project-name) tide-event-listeners))
(with-current-buffer (car listener)
(apply (cdr listener) (list event)))))
(defun tide-dispatch (response)
(cl-case (intern (plist-get response :type))
((response) (tide-dispatch-response response))
((event) (tide-dispatch-event response))))
(defun tide-send-command (name args &optional callback)
(unless (tide-current-server)
(error "Server does not exist. Run M-x tide-restart-server to start it again"))
(tide-sync-buffer-contents)
(let* ((request-id (tide-next-request-id))
(command `(:command ,name :seq ,request-id :arguments ,args))
(json-encoding-pretty-print nil)
(encoded-command (tide-json-encode command))
(payload (concat encoded-command "\n")))
(process-send-string (tide-current-server) payload)
(when callback
(puthash request-id (cons (current-buffer) callback) tide-response-callbacks))))
(defun tide-seconds-elapsed-since (time)
(time-to-seconds (time-subtract (current-time) time)))
(defun tide-send-command-sync (name args)
(let* ((start-time (current-time))
(response nil))
(tide-send-command name args (lambda (resp) (setq response resp)))
(while (not response)
(accept-process-output nil 0.01)
(when (> (tide-seconds-elapsed-since start-time) tide-sync-request-timeout)
(error "Sync request timed out %s" name)))
response))
(defun tide-net-filter (process data)
(with-current-buffer (process-buffer process)
(goto-char (point-max))
(insert data))
(tide-decode-response process))
(defun tide-net-sentinel (process message)
(let ((project-name (process-get process 'project-name)))
(message "(%s) tsserver exits: %s." project-name (string-trim message))
(ignore-errors
(kill-buffer (process-buffer process)))
(tide-cleanup-project project-name)))
(defun tide--npm-local ()
"Return a single path to the package-local typescript package directory or nil."
(-when-let (packages-folder (locate-dominating-file default-directory "package.json"))
(concat packages-folder "node_modules/typescript/lib/")))
(defun tide--npm-global ()
"Return a single path to the global typescript package directory or nil."
(if (eq system-type 'windows-nt)
(concat (getenv "appdata") "\\npm\\node_modules")
"/usr/lib/node_modules/typescript/lib/"))
(defun tide--npm-global-usrlocal ()
"Return a single path to the global typescript package directory or nil."
;; this check does not apply to windows.
(if (eq system-type 'windows-nt)
nil
"/usr/local/lib/node_modules/typescript/lib/"))
(defun tide--project-package ()
"Return the package's node_module bin directory using projectile's project root or nil."
(when (and (functionp 'projectile-project-p)
(functionp 'projectile-project-root)
(projectile-project-p))
(concat (projectile-project-root) "node_modules/typescript/lib")))
(defconst tide--tscompiler "tsc.js"
"File-name of the typescript compiler.")
(defun tide--locate-tscompiler (path)
"Locate the typescript compiler in PATH.
Return a string representing the existing full path or nil."
(let ((exe (expand-file-name tide--tscompiler path)))
(when (file-exists-p exe) exe)))
(defun tide-tscompiler-locater-npmlocal-projectile-npmglobal ()
"Locate tsserver through project-local or global system settings."
(or
(tide--locate-tscompiler (tide--npm-local))
(tide--locate-tscompiler (tide--project-package))
(tide--locate-tscompiler (tide--npm-global))
(tide--locate-tscompiler (tide--npm-global-usrlocal))))
(defun tide-locate-tscompiler-executable ()
"Locate the typescript compiler executable.
If TIDE-TSCOMPILER-EXECUTABLE is set by the user use it. Otherwise check in the
npm local package directory, in the project root as defined by projectile, and
in the npm global installation."
(or
(and tide-tscompiler-executable (expand-file-name tide-tscompiler-executable))
(tide-tscompiler-locater-npmlocal-projectile-npmglobal)))
(defconst tide--tsserver "tsserver.js"
"File-name of the file that node executes to start the typescript server.")
(defun tide--locate-tsserver (path)
"Locate the typescript server in PATH.
Return a string representing the existing full path or nil."
(let ((exe (expand-file-name tide--tsserver path)))
(when (file-exists-p exe) exe)))
(defun tide-tsserver-locater-npmlocal-projectile-npmglobal ()
"Locate tsserver through project-local or global system settings."
(or
(tide--locate-tsserver (tide--npm-local))
(tide--locate-tsserver (tide--project-package))
(tide--locate-tsserver (tide--npm-global))
(tide--locate-tsserver (tide--npm-global-usrlocal))))
(defun tide-locate-tsserver-executable ()
"Locate the typescript server executable.
If TIDE-TSSERVER-EXECUTABLE is set by the user use it. Otherwise check in the
npm local package directory, in the project root as defined by projectile, and
in the npm global installation. If nothing is found use the bundled version."
(or
(and tide-tsserver-executable (expand-file-name tide-tsserver-executable))
(funcall tide-tsserver-locator-function)
(expand-file-name tide--tsserver tide-tsserver-directory)))
(defun tide-start-server ()
(when (tide-current-server)
(error "Server already exist"))
(message "(%s) Starting tsserver..." (tide-project-name))
(let* ((default-directory (tide-project-root))
(process-environment (append tide-tsserver-process-environment process-environment))
(buf (generate-new-buffer tide-server-buffer-name))
(tsserverjs (tide-locate-tsserver-executable))
;; Use a pipe to communicate with the subprocess. This fixes a hang
;; when a >1k message is sent on macOS.
(process-connection-type nil)
(node-process-arguments (append tide-node-flags (list tsserverjs) tide-tsserver-flags))
(process
(apply #'start-file-process "tsserver" buf tide-node-executable node-process-arguments)))
(set-process-coding-system process 'utf-8-unix 'utf-8-unix)
(set-process-filter process #'tide-net-filter)
(set-process-sentinel process #'tide-net-sentinel)
(set-process-query-on-exit-flag process nil)
(with-current-buffer (process-buffer process)
(buffer-disable-undo))
(process-put process 'project-name (tide-project-name))
(process-put process 'project-root default-directory)
(puthash (tide-project-name) process tide-servers)
(message "(%s) tsserver server started successfully." (tide-project-name))
(tide-each-buffer (tide-project-name) #'tide-configure-buffer)))
(defun tide-cleanup-buffer-callbacks ()
(let ((error-response `(:success ,nil)))
(maphash
(lambda (id callback)
(when (equal (current-buffer) (car callback))
(funcall (cdr callback) error-response)
(remhash id tide-response-callbacks)))
tide-response-callbacks)))
(defun tide-cleanup-project (project-name)
(tide-each-buffer project-name
(lambda ()
(tide-cleanup-buffer-callbacks)))
(tide-cleanup-project-data project-name))
(defun tide-cleanup-project-data (project-name)
(remhash project-name tide-servers)
(remhash project-name tide-tsserver-unsupported-commands)
(remhash project-name tide-project-configs))
(defvar tide--cleanup-timer nil)
(defvar tide--cleanup-kinds nil)
(defun tide-schedule-cleanup (kind)
(cl-pushnew kind tide--cleanup-kinds)
(when (and tide-project-cleanup-delay (not tide--cleanup-timer))
(setq tide--cleanup-timer
(run-with-idle-timer tide-project-cleanup-delay nil
#'tide-do-cleanups))))
(defun tide-schedule-dead-projects-cleanup ()
(tide-schedule-cleanup 'dead-projects))
(defun tide-schedule-tmp-file-cleanup ()
(tide-schedule-cleanup 'tmp-file))
(defun tide-do-cleanups (&optional interactivep)
"Perform some cleanups.
This function is used when Emacs is idle (see `tide-project-cleanup-delay'),
and you can also call it interactively (e.g., if you disable the automatic
behavior).
Currently, two kinds of cleanups are done:
* Remove projects that don't have any associated live buffers, and kill their
tsserver processes.
* Remove tmp files for buffers that are saved."
(interactive '(t))
(let ((kinds (if interactivep '(dead-projects tmp-file) tide--cleanup-kinds))
(live-projects '())
(buffers-w/tmp '()))
(dolist (b (buffer-list))
(with-current-buffer b
(when (bound-and-true-p tide-mode)
(cl-pushnew (tide-project-name) live-projects))
(when (bound-and-true-p tide-buffer-tmp-file)
(cl-pushnew b buffers-w/tmp))))
(setq tide--cleanup-timer nil tide--cleanup-kinds nil)
(when (memq 'dead-projects kinds)
(-when-let (to-kill (-difference (hash-table-keys tide-servers) live-projects))
(message "Cleaning up %d projects..." (length to-kill))
(dolist (proj to-kill)
(delete-process (process-buffer (gethash proj tide-servers)))
(tide-cleanup-project-data proj))))
(when (and (consp buffers-w/tmp) (memq 'tmp-file kinds))
(message "Cleaning up %d tmp files..." (length buffers-w/tmp))
(dolist (b buffers-w/tmp)
(with-current-buffer b (tide-remove-tmp-file))))
(unless interactivep
(sit-for 5)
(message nil))))
(defun tide-start-server-if-nonexistent ()
"Start a tsserver instance if there is not one already running."
(unless (tide-current-server)
(tide-start-server)))
(defun tide-decode-response-legth ()
(goto-char (point-min))
(when (re-search-forward "Content-Length: \\([0-9]+\\)" nil t)
(string-to-number (match-string 1))))
(defun tide-enough-response-p (length)
(save-excursion
(when (search-forward "{" nil t)
(backward-char 1)
(>= (- (position-bytes (point-max)) (position-bytes (point))) (1- length)))))
(defun tide-decode-response (process)
(with-current-buffer (process-buffer process)
(let ((length (tide-decode-response-legth)))
(when (and length (tide-enough-response-p length))
(search-forward "{")
(backward-char 1)
(let ((response (if (> length tide-server-max-response-length)
(let ((seq (when (re-search-forward "\"request_seq\":\"\\([0-9]+\\)\"" nil t)
(match-string 1))))
(forward-line 1)
(and seq
`(:success :json-false :type "response"
:message ,tide-max-response-length-error-message
:request_seq ,seq)))
(tide-json-read-object))))
(delete-region (point-min) (point))
(when response
(tide-dispatch response)))
(when (>= (buffer-size) 16)
(tide-decode-response process))))))
;;; Initialization
(defun tide-file-format-options ()
(tide-combine-plists
`(:tabSize ,tab-width :indentSize ,(tide-current-indentsize))
tide-format-options
(tide-tsfmt-options)))
(defun tide-tsfmt-options ()
(let ((config-file (expand-file-name "tsfmt.json" (tide-project-root))))
(when (file-exists-p config-file)
(tide-safe-json-read-file config-file))))
(defun tide-current-indentsize ()
(pcase major-mode
(`typescript-mode typescript-indent-level)
(`typescript-ts-mode typescript-ts-mode-indent-offset)
(`js2-mode js2-basic-offset)
(`js-mode js-indent-level)
(`js3-mode js3-indent-level)
(`web-mode web-mode-code-indent-offset)
(`js2-jsx-mode sgml-basic-offset)
(`rjsx-mode sgml-basic-offset)
(_ standard-indent)))
(defun tide-command:configure ()
(tide-send-command
"configure"
`(:hostInfo ,(emacs-version) :file ,(tide-buffer-file-name)
:formatOptions ,(tide-file-format-options) :preferences ,tide-user-preferences)))
(defun tide-command:projectInfo (cb &optional need-file-name-list file)
(tide-send-command "projectInfo" `(:file ,(or file (tide-buffer-file-name)) :needFileNameList ,need-file-name-list) cb))
(defun tide-command:openfile ()
(tide-send-command "open"
(if tide-require-manual-setup
`(:file
,(tide-buffer-file-name)
:scriptKindName ,tide-default-mode
:fileContent ,(buffer-string))
(append `(:file ,(tide-buffer-file-name))
(let ((extension (upcase (or (file-name-extension (tide-buffer-file-name)) ""))))
(when (member extension '("TS" "JS" "TSX" "JSX"))
`(:scriptKindName ,extension)))))))
(defun tide-command:closefile ()
(tide-send-command "close" `(:file ,(tide-buffer-file-name))))
;;; Jump to definition
(defun tide-command:definition (&optional cb location)
(let ((location (or location
`(:file ,(tide-buffer-file-name)
:line ,(tide-line-number-at-pos)
:offset ,(tide-current-offset)))))
(if cb
(tide-send-command "definition" location cb)
(tide-send-command-sync "definition" location))))
(defun tide-command:typeDefinition (cb)
(tide-send-command
"typeDefinition"
`(:file ,(tide-buffer-file-name) :line ,(tide-line-number-at-pos) :offset ,(tide-current-offset))
cb))
(defun tide-jump-to-definition (&optional arg)
"Jump to the definition of the symbol at point.
If pointed at an abstract member-declaration, will proceed to look for
implementations. When invoked with a prefix arg, jump to the type definition."
(interactive "P")
(let ((cb (lambda (response)
(tide-on-response-success response
(-when-let (filespan (car (plist-get response :body)))
;; if we're still at the same location...
;; maybe we're a abstract member which has implementations?
(if (and (not arg)
(tide-filespan-is-current-location-p filespan))