forked from ananthakumaran/tide
-
Notifications
You must be signed in to change notification settings - Fork 1
/
tide.el
1996 lines (1684 loc) · 73.5 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 <[email protected]>
;; URL: http://github.com/ananthakumaran/tide
;; Version: 2.6.1
;; Keywords: typescript
;; Package-Requires: ((dash "2.10.0") (s "1.11.0") (flycheck "27") (typescript-mode "0.1") (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 'typescript-mode)
(require 'etags)
(require 'json)
(require 'cl-lib)
(require 'eldoc)
(require 'dash)
(require 's)
(require 'flycheck)
(require 'imenu)
(require 'thingatpt)
(require 'tide-lv)
;; 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-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-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-node-executable "node"
"Name or path of the node executable binary file."
:type '(choice (const nil) string)
:group 'tide)
(defcustom tide-post-code-edit-hook nil
"Hook run after code edits are applied in a buffer."
:type 'hook
:group 'tide)
(defvar tide-format-options '()
"Format options plist.")
(defvar tide-completion-ignore-case nil
"CASE will be ignored in completion if set to non-nil.")
(defvar tide-completion-detailed nil
"Completion dropdown will contain detailed method information if set to non-nil.")
(defface tide-file
'((t (:inherit dired-header)))
"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)
(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 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 "Reponse 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)
(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))))
;;; 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))))))
;;; Helpers
(defun tide-safe-json-read-file (filename)
(condition-case nil
(let ((json-object-type 'plist))
(json-read-file filename))
(error '())))
(defun tide-plist-get (list &rest args)
(cl-reduce
(lambda (object key)
(when object
(plist-get object key)))
args
:initial-value list))
(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-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 ignore-empty-response &rest body)
(declare (indent 2))
`(if (tide-response-success-p ,response)
(progn
,@body)
(-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 ignore-empty-response &rest body)
(declare (indent 2))
`(lambda (,response)
(tide-on-response-success ,response ,ignore-empty-response
,@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-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-column (line offset)
"Return column number corresponds to the LINE and OFFSET.
LINE is one based, OFFSET is one based and column is zero based"
(save-excursion
(save-restriction
(widen)
(goto-char (point-min))
(forward-line (1- line))
(beginning-of-line)
(while (> offset 1)
(forward-char)
(cl-decf offset))
(1+ (current-column)))))
(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-doc-buffer (string)
(with-current-buffer (get-buffer-create "*tide-documentation*")
(setq buffer-read-only t)
(let ((inhibit-read-only t))
(erase-buffer)
(when string
(save-excursion
(tide-insert string))))
(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))))
;;; 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)
(when (not (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 (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-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 (> (cadr (time-subtract (current-time) 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--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)
(process
(start-file-process "tsserver" buf tide-node-executable tsserverjs)))
(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))
(puthash (tide-project-name) process tide-servers)
(message "(%s) tsserver server started successfully." (tide-project-name))))
(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)))
(remhash project-name tide-servers)
(remhash project-name tide-tsserver-unsupported-commands)
(remhash project-name tide-project-configs))
(defun tide-start-server-if-required ()
(when (not (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))
(json-object-type 'plist)
(json-array-type 'list))
(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)
(when seq
`(:success :json-false :type "response" :message ,tide-max-response-length-error-message :request_seq ,seq)))
(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)
(`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 ,buffer-file-name :formatOptions ,(tide-file-format-options))))
(defun tide-command:projectInfo (cb &optional need-file-name-list)
(tide-send-command "projectInfo" `(:file ,buffer-file-name :needFileNameList ,need-file-name-list) cb))
(defun tide-command:openfile ()
(tide-send-command "open"
(append `(:file ,buffer-file-name)
(let ((extension (upcase (file-name-extension buffer-file-name))))
(if (member extension '("TS" "JS" "TSX" "JSX"))
`(:scriptKindName ,extension)
nil)))))
(defun tide-command:closefile ()
(tide-send-command "close" `(:file ,buffer-file-name)))
;;; Jump to definition
(defun tide-command:definition (cb)
(tide-send-command
"definition"
`(:file ,buffer-file-name :line ,(tide-line-number-at-pos) :offset ,(tide-current-offset))
cb))
(defun tide-command:typeDefinition (cb)
(tide-send-command
"typeDefinition"
`(:file ,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 nil
(-when-let (filespan (car (plist-get response :body)))
;; if we're still at the same location...
;; maybe we're a abstract member which has impementations?
(if (and (not arg)
(tide-filespan-is-current-location-p filespan))
(tide-jump-to-implementation)
(tide-jump-to-filespan filespan tide-jump-to-definition-reuse-window)))))))
(if arg
(tide-command:typeDefinition cb)
(tide-command:definition cb))))
(defun tide-filespan-is-current-location-p (filespan)
(let* ((location (plist-get filespan :start))
(new-file-name (plist-get filespan :file)))
(and (string-equal new-file-name buffer-file-name)
(equal (tide-location-to-point location) (point)))))
(defun tide-move-to-location (location)
(let* ((line (plist-get location :line))
(offset (plist-get location :offset)))
(save-restriction
(widen)
(goto-char (point-min))
(forward-line (1- line)))
(forward-char (1- offset))))
(defun tide-location-to-point (location)
(save-excursion
(tide-move-to-location location)
(point)))
(defun tide-jump-to-filespan (filespan &optional reuse-window no-marker)
(let ((file (plist-get filespan :file)))
(unless no-marker
(ring-insert find-tag-marker-ring (point-marker)))
(if reuse-window
(pop-to-buffer (find-file-noselect file) '((display-buffer-reuse-window display-buffer-same-window)))
(pop-to-buffer (find-file-noselect file)))
(tide-move-to-location (plist-get filespan :start))))
(defalias 'tide-jump-back 'pop-tag-mark)
;;; Jump to implementation
(defun tide-command:implementation ()
(tide-send-command-sync "implementation" `(:file ,buffer-file-name :line ,(tide-line-number-at-pos) :offset ,(tide-current-offset))))
(defun tide-jump-to-implementation-format-item (item)
(let* ((file-name (plist-get item :file))
(line (save-excursion
(with-current-buffer (find-file-noselect file-name)
(tide-move-to-location (plist-get item :start))
(replace-regexp-in-string "\n" "" (thing-at-point 'line)))))
(file-pos (concat
(propertize (file-name-nondirectory file-name)
'face 'tide-file)
":"
(propertize (number-to-string (tide-plist-get item :start :line))
'face 'tide-line-number))))
(concat
line
" "
file-pos)))
(defun tide-jump-to-implementation ()
"Jump to a implementation of the symbol at point."
(interactive)
(let ((response (tide-command:implementation)))
(tide-on-response-success response nil
(let ((impls (plist-get response :body)))
(cond ((= 0 (length impls)) (message "No implementations available."))
((= 1 (length impls)) (tide-jump-to-filespan (car impls)))
(t (tide-jump-to-filespan
(tide-select-item-from-list "Select implementation: " impls #'tide-jump-to-implementation-format-item (tide-can-use-popup-p 'jump-to-implementation)))))))))
;;; Navigate to named member
(defun tide-in-string-p ()
(nth 3 (syntax-ppss)))
(defun tide-get-symbol-at-point ()
"Returns the symbol found at point, if not deemed 'noise'.
Noise can be anything like braces, reserved keywords, etc."
(when (not (or (tide-in-string-p)
(member (face-at-point) '(font-lock-keyword-face))))
;; we could have used symbol-at-point here, but that leaves us unable to
;; differentiate between a symbol named nil and no symbol at all.
;; thing-at-point returns a string OR nil, which means we don't get this problem.
(let ((symbol (thing-at-point 'symbol)))
(substring-no-properties (if (equal nil symbol) "" symbol)))))
(defun tide-nav (arg)
"Search and navigate to named types."
(interactive "P")
(let ((completion-ignore-case t)
(last-completions nil)
(default (when arg (tide-get-symbol-at-point))))
(-when-let (completion
(completing-read-default
"Search: "
(completion-table-dynamic
(lambda (prefix)
(let ((response (tide-command:navto prefix)))
(tide-on-response-success response nil
(-when-let (navto-items (plist-get response :body))
(setq navto-items
(-filter
(lambda (navto-item) (member (plist-get navto-item :kind) '("class" "interface" "type" "enum")))
navto-items))
(setq last-completions navto-items)
(-map (lambda (navto-item) (plist-get navto-item :name))
navto-items)))))
t) nil t default))
(let ((navto-item (-find (lambda (navto-item) (string-equal completion (plist-get navto-item :name))) last-completions)))
(tide-jump-to-filespan navto-item)))))
(defun tide-command:navto (type)
(tide-send-command-sync "navto" `(:file ,buffer-file-name :searchValue ,type :maxResultCount 100)))
;;; Eldoc
(defun tide-annotate-display-part (display-part &optional highlight)
(let ((text (plist-get display-part :text))
(face (pcase (plist-get display-part :kind)
("aliasName" 'font-lock-type-face)
("className" 'font-lock-type-face)
("enumName" 'font-lock-type-face)
("fieldName" nil)
("interfaceName" 'font-lock-type-face)
("keyword" 'font-lock-keyword-face)
("lineBreak" nil)
("numericLiteral" nil)
("stringLiteral" 'font-lock-string-face)
("localName" 'font-lock-variable-name-face)
("methodName" nil)
("moduleName" nil)
("operator" nil)
("parameterName" (and highlight 'eldoc-highlight-function-argument))
("propertyName" nil)
("punctuation" nil)
("space" nil)
("text" nil)
("typeParameterName" 'font-lock-variable-name-face)
("enumMemberName" 'font-lock-constant-face)
("functionName" 'font-lock-function-name-face)
("regularExpressionLiteral" 'font-lock-string-face))))
(if face
(propertize text 'face face)
text)))
(defun tide-annotate-display-parts (display-parts &optional highlight)
(tide-join (-map (lambda (part) (tide-annotate-display-part part highlight)) display-parts)))
(defun tide-annotate-signature-parameter (parameter highlight)
(tide-join
(-map
(lambda (part) (tide-annotate-display-part part highlight))
(plist-get parameter :displayParts))))
(defun tide-annotate-signature (signature selected-arg-index)
(let ((separator (tide-join (-map #'tide-annotate-display-part (plist-get signature :separatorDisplayParts)))))
(tide-join
(-concat
(-map #'tide-annotate-display-part (plist-get signature :prefixDisplayParts))
(list
(mapconcat
#'identity
(-map-indexed
(lambda (i parameter)
(tide-annotate-signature-parameter parameter (eq i selected-arg-index)))
(plist-get signature :parameters))
separator))
(-map #'tide-annotate-display-part (plist-get signature :suffixDisplayParts))))))
(defun tide-annotate-signatures (body)
(let ((selected-index (plist-get body :selectedItemIndex))
(selected-arg-index (plist-get body :argumentIndex)))
(tide-annotate-signature
(nth selected-index (plist-get body :items))
selected-arg-index)))
(defun tide-command:signatureHelp (cb)
(tide-send-command
"signatureHelp"
`(:file ,buffer-file-name :line ,(tide-line-number-at-pos) :offset ,(tide-current-offset))
(tide-on-response-success-callback response t
(funcall cb (tide-annotate-signatures (plist-get response :body))))))
(defun tide-method-call-p ()
(or (looking-at "[(,]") (and (not (looking-at "\\sw")) (looking-back "[(,]\n?\\s-*"))))
(defun tide-doc-text (quickinfo-or-completion-detail)
(or (plist-get quickinfo-or-completion-detail :displayString) ;; old
(tide-annotate-display-parts
(plist-get quickinfo-or-completion-detail :displayParts))))
(defun tide-doc-documentation (quickinfo-or-completion-detail)
(let ((documentation (plist-get quickinfo-or-completion-detail :documentation)))
(if (stringp documentation) ;; old
documentation
(tide-annotate-display-parts documentation))))
(defun tide-format-jsdoc (name text)
(setq text (s-trim (or text "")))
(concat (propertize (concat "@" name) 'face 'font-lock-keyword-face)
(if (s-contains? "\n" text) "\n" " ")
text
"\n"))
(defun tide-doc-jsdoc (quickinfo-or-completion-detail)
(tide-join
(-map
(lambda (tag)
(tide-format-jsdoc (plist-get tag :name) (plist-get tag :text)))
(plist-get quickinfo-or-completion-detail :tags))))
(defun tide-construct-documentation (quickinfo-or-completion-detail)
(when quickinfo-or-completion-detail
(let* ((display-string (tide-doc-text quickinfo-or-completion-detail))
(documentation (tide-doc-documentation quickinfo-or-completion-detail))
(jsdoc (tide-doc-jsdoc quickinfo-or-completion-detail)))
(when (or (or (not (s-blank? documentation))
(not (s-blank? jsdoc)))
tide-always-show-documentation)
(tide-doc-buffer
(tide-join
(-concat (list display-string "\n\n")
(if (not (s-blank? documentation)) (list documentation "\n\n") '())
(list jsdoc))))))))
(defun tide-command:quickinfo-old (cb)
(tide-send-command "quickinfo" `(:file ,buffer-file-name :line ,(tide-line-number-at-pos) :offset ,(tide-current-offset)) cb))
(defun tide-command:quickinfo-full (cb)
(tide-send-command "quickinfo-full" `(:file ,buffer-file-name :line ,(tide-line-number-at-pos) :offset ,(tide-current-offset)) cb))
(defun tide-command:quickinfo (cb)
(tide-fallback-if-not-supported "quickinfo-full" tide-command:quickinfo-full tide-command:quickinfo-old cb))
(defun tide-eldoc-function ()
(when (not (member last-command '(next-error previous-error)))
(if (tide-method-call-p)
(tide-command:signatureHelp #'tide-eldoc-maybe-show)
(when (looking-at "\\s_\\|\\sw")
(tide-command:quickinfo
(tide-on-response-success-callback response t
(tide-eldoc-maybe-show (tide-doc-text (plist-get response :body))))))))
nil)
;;; Copied from eldoc.el
(defun tide-eldoc-maybe-show (text)
(with-demoted-errors "eldoc error: %s"
(and (or (eldoc-display-message-p)
;; Erase the last message if we won't display a new one.
(when eldoc-last-message
(eldoc-message nil)
nil))
(eldoc-message text))))
(defun tide-documentation-at-point ()
"Show documentation of the symbol at point."
(interactive)
(tide-command:quickinfo
(tide-on-response-success-callback response nil
(-if-let (buffer (tide-construct-documentation (plist-get response :body)))
(display-buffer buffer t)
(message "No documentation available.")))))
;;; Buffer Sync
(defun tide-remove-tmp-file ()
(when tide-buffer-tmp-file
(delete-file tide-buffer-tmp-file)
(setq tide-buffer-tmp-file nil)))
(defun tide-command:reloadfile ()
(tide-send-command "reload" `(:file ,buffer-file-name :tmpfile ,buffer-file-name)))
(defun tide-handle-change (_beg _end _len)
(setq tide-buffer-dirty t))
(defun tide-sync-buffer-contents ()
;; The real file that backs a buffer could be changed in various
;; ways, one common example is the rename operation. Ensure that we
;; send the open command for the new file before using it as an
;; argument for any other command.
(unless (string-equal tide-active-buffer-file-name buffer-file-name)
(tide-configure-buffer))
(when tide-buffer-dirty
(setq tide-buffer-dirty nil)
(when (not tide-buffer-tmp-file)
(setq tide-buffer-tmp-file (make-temp-file "tide")))
(write-region (point-min) (point-max) tide-buffer-tmp-file nil 'no-message)
(tide-send-command "reload" `(:file ,buffer-file-name :tmpfile ,tide-buffer-tmp-file))))
;;; Code-fixes
(defun tide-apply-code-edits (file-code-edits)
(save-excursion
(dolist (file-code-edit file-code-edits)
(with-current-buffer (find-file-noselect (plist-get file-code-edit :fileName))
(tide-format-regions (tide-apply-edits (plist-get file-code-edit :textChanges)))
(basic-save-buffer)
(run-hooks 'tide-post-code-edit-hook)))))
(defun tide-get-flycheck-errors-ids-at-point ()
(-map #'flycheck-error-id (flycheck-overlay-errors-at (point))))
(defun tide-command:getCodeFixes ()
(tide-send-command-sync "getCodeFixes" `(:file ,(buffer-file-name) :startLine ,(tide-line-number-at-pos) :startOffset ,(tide-current-offset) :endLine ,(tide-line-number-at-pos) :endOffset ,(+ 1 (tide-current-offset)) :errorCodes ,(tide-get-flycheck-errors-ids-at-point))))
(defun tide-get-fix-description (fix)
(plist-get fix :description))
(defun tide-apply-codefix (fix)
"Apply a single `FIX', which may apply to several files."
(tide-apply-code-edits (plist-get fix :changes)))
(defun tide-apply-codefixes (fixes)
(cond ((= 0 (length fixes)) (message "No code-fixes available."))
((= 1 (length fixes)) (tide-apply-codefix (car fixes)))
(t (tide-apply-codefix
(tide-select-item-from-list "Select fix: " fixes #'tide-get-fix-description (tide-can-use-popup-p 'code-fix))))))
(defun tide-fix ()
"Apply code fix for the error at point."
(interactive)
(unless (tide-get-flycheck-errors-ids-at-point)
(error "No errors available at current point."))
(let ((response (tide-command:getCodeFixes)))
(tide-on-response-success response nil
(let ((fixes (plist-get response :body)))
(tide-apply-codefixes fixes)))))
;;; Refactor
(defun tide-location-or-range ()
(if (use-region-p)
(let ((start (region-beginning))
(end (region-end)))
`(:startLine ,(tide-line-number-at-pos start) :startOffset ,(tide-offset start)
:endLine ,(tide-line-number-at-pos end) :endOffset ,(tide-offset end)))