forked from emacs-lsp/lsp-mode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lsp-methods.el
2007 lines (1743 loc) · 81 KB
/
lsp-methods.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
;; Copyright (C) 2016-2018 Vibhav Pant <vibhavp@gmail.com> -*- lexical-binding: t -*-
;; 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/>.
(require 'cl-lib)
(require 'json)
(require 'xref)
(require 'subr-x)
(require 'widget)
(require 'lsp-io)
(require 'lsp-common)
(require 'pcase)
(require 'inline)
;;; Code:
;; A ‘lsp--client’ object describes the client-side behavior of a language
;; server. It is used to start individual server processes, each of which is
;; represented by a ‘lsp--workspace’ object. Client objects are normally
;; created using ‘lsp-define-stdio-client’ or ‘lsp-define-tcp-client’. Each
;; workspace refers to exactly one client, but there can be multiple workspaces
;; for a single client.
(cl-defstruct lsp--client
;; ‘language-id’ is a function that receives a buffer as a single argument
;; and should return the language identifier for that buffer. See
;; https://microsoft.github.io/language-server-protocol/specification#textdocumentitem
;; for a list of language identifiers. Also consult the documentation for
;; the language server represented by this client to find out what language
;; identifiers it supports or expects.
(language-id nil :read-only t)
;; send-async and send-sync are unused field, but haven't been
;; removed so as to avoid breaking byte-compiled clients.
;; FIXME: We shouldn’t need to take binary compatibility into account,
;; especially since the ‘lsp--client’ structure is internal. These fields
;; should just be removed.
(send-sync nil :read-only t)
(send-async nil :read-only t)
;; FIXME: This field is apparently unused and should be removed.
(type nil :read-only t)
;; ‘new-connection’ is a function that should start a language server process
;; and return a cons (COMMAND-PROCESS . COMMUNICATION-PROCESS).
;; COMMAND-PROCESS must be a process object representing the server process
;; just started. COMMUNICATION-PROCESS must be a process (including pipe and
;; network processes) that ‘lsp-mode’ uses to communicate with the language
;; server using the language server protocol. COMMAND-PROCESS and
;; COMMUNICATION-PROCESS may be the same process; in that case
;; ‘new-connection’ may also return that process as a single
;; object. ‘new-connection’ is called with two arguments, FILTER and
;; SENTINEL. FILTER should be used as process filter for
;; COMMUNICATION-PROCESS, and SENTINEL should be used as process sentinel for
;; COMMAND-PROCESS.
(new-connection nil :read-only t)
;; ‘stderr’ is the name of a buffer to write the standard error to.
;; FIXME: ‘stderr’ should be the actual buffer, and it should be a field of
;; the ‘lsp--workspace’.
(stderr nil :read-only t)
;; ‘get-root’ is a function that should return the workspace root directory
;; for the current buffer. It may return either a directory name or a
;; directory file name. The ‘get-root’ function is called without arguments.
;; ‘lsp-mode’ will start one server process per client and root directory.
;; It passes the root directory to the ‘initialize’ method of the language
;; server; see
;; https://microsoft.github.io/language-server-protocol/specification#initialize.
;; Also consult the documentation of your language server for information
;; about what it expects as workspace root.
(get-root nil :read-only t)
;; ‘ignore-regexps’ is a list of regexps. When a data packet from the
;; language server matches any of these regexps, it will be ignored. This is
;; intended for dealing with language servers that output non-protocol data.
(ignore-regexps nil :read-only t)
;; ‘ignore-messages’ is a list of regexps. When a message from the language
;; server matches any of these regexps, it will be ignored. This is useful
;; for filtering out unwanted messages; such as servers that send nonstandard
;; message types, or extraneous log messages.
(ignore-messages nil :read-only t)
;; ‘notification-handlers’ is a hash table mapping notification method names
;; (strings) to functions handling the respective notifications. Upon
;; receiving a notification, ‘lsp-mode’ will call the associated handler
;; function passing two arguments, the ‘lsp--workspace’ object and the
;; deserialized notification parameters.
(notification-handlers (make-hash-table :test 'equal) :read-only t)
;; ‘notification-handlers’ is a hash table mapping request method names
;; (strings) to functions handling the respective notifications. Upon
;; receiving a request, ‘lsp-mode’ will call the associated handler function
;; passing two arguments, the ‘lsp--workspace’ object and the deserialized
;; request parameters.
(request-handlers (make-hash-table :test 'equal) :read-only t)
;; ‘response-handlers’ is a hash table mapping integral JSON-RPC request
;; identifiers for pending asynchronous requests to functions handling the
;; respective responses. Upon receiving a response from the language server,
;; ‘lsp-mode’ will call the associated response handler function with a
;; single argument, the deserialized response parameters.
(response-handlers (make-hash-table :test 'eql) :read-only t)
;; ‘string-renderers’ is an alist mapping MarkedString language identifiers
;; (see
;; https://microsoft.github.io/language-server-protocol/specification#textDocument_hover)
;; to functions that can render the respective languages. The rendering
;; functions are called with a single argument, the MarkedString value. They
;; should return a propertized string with the rendered output.
(string-renderers '())
;; ‘last-id’ is the last JSON-RPC identifier used.
;; FIXME: ‘last-id’ should be in ‘lsp--workspace’.
(last-id 0)
;; Function to enable the client for the current buffer, called without
;; arguments.
(enable-function nil :read-only t)
;; ‘prefix-function’ is called for getting the prefix for completion.
;; The function takes no parameter and returns a cons (start . end) representing
;; the start and end bounds of the prefix. If it's not set, the client uses a
;; default prefix function."
(prefix-function nil :read-only t)
;; Contains mapping of scheme to the function that is going to be used to load
;; the file.
(uri-handlers (make-hash-table :test #'equal) :read-only t))
(cl-defstruct lsp--registered-capability
(id "" :type string)
(method " " :type string)
(options nil))
;; A ‘lsp--workspace’ object represents exactly one language server process.
(cl-defstruct lsp--workspace
;; ‘parser’ is a ‘lsp--parser’ object used to parse messages for this
;; workspace. Parsers are not shared between workspaces.
(parser nil :read-only t)
;; ‘file-versions’ is a hashtable of files "owned" by the workspace. It maps
;; file names to file versions. See
;; https://microsoft.github.io/language-server-protocol/specification#versionedtextdocumentidentifier.
(file-versions nil :read-only t)
;; ‘server-capabilities’ is a hash table of the language server capabilities.
;; It is the hash table representation of a LSP ServerCapabilities structure;
;; cf. https://microsoft.github.io/language-server-protocol/specification#initialize.
(server-capabilities nil)
;; ‘registered-server-capabilities’ is a list of hash tables that represent
;; dynamically-registered Registration objects. See
;; https://microsoft.github.io/language-server-protocol/specification#client_registerCapability.
(registered-server-capabilities nil)
;; ‘root’ is a directory name or a directory file name for the workspace
;; root. ‘lsp-mode’ passes this directory to the ‘initialize’ method of the
;; language server; see
;; https://microsoft.github.io/language-server-protocol/specification#initialize.
(root nil :ready-only t)
;; ‘client’ is the ‘lsp--client’ object associated with this workspace.
(client nil :read-only t)
;; FIXME: ‘change-timer-disabled’ is unused and should be removed.
(change-timer-disabled nil)
;; ‘proc’ is a process object; it may represent a regular process, a pipe, or
;; a network connection. ‘lsp-mode’ communicates with ‘proc’ using the
;; language server protocol. ‘proc’ corresponds to the COMMUNICATION-PROCESS
;; element of the return value of the client’s ‘get-root’ field, which see.
(proc nil)
;; ‘proc’ is a process object; it must represent a regular process, not a
;; pipe or network process. It represents the actual server process that
;; corresponds to this workspace. ‘cmd-proc’ corresponds to the
;; COMMAND-PROCESS element of the return value of the client’s ‘get-root’
;; field, which see.
(cmd-proc nil)
;; ‘buffers’ is a list of buffers associated with this workspace.
(buffers nil)
;; ‘highlight-overlays’ is a hash table mapping buffers to a list of overlays
;; used for highlighting the symbol under point.
(highlight-overlays (make-hash-table :test 'eq) :read-only t)
;; Extra client capabilities provided by third-party packages using
;; `lsp-register-client-capabilities'. It's value is an alist of (PACKAGE-NAME
;; . CAPS), where PACKAGE-NAME is a symbol of the third-party package name,
;; and CAPS is either a plist of the client capabilities, or a function that
;; takes no argument and returns a plist of the client capabilities or nil.")
(extra-client-capabilities nil))
(defvar-local lsp--cur-workspace nil)
(defvar lsp--workspaces (make-hash-table :test #'equal)
"Table of known workspaces, indexed by the project root directory.")
(defvar lsp--ignored-workspace-roots (make-hash-table :test #'equal)
"Table of project roots which should not have a workspace,
indexed by the project root directory.
This is populated when the user declines to open a workspace
for a file in the workspace.")
(defcustom lsp-render-markdown-markup-content nil
"Function to be use for rendering MarkupContent.
It should take two arguments - a string denoting the type of markup content
and a string containing the text to be rendered. The returned value should
be a string that may be fontified/propertized.
When nil, MarkupContent is rendered as plain text."
:type 'function
:group 'lsp-mode)
(defcustom lsp-before-initialize-hook nil
"List of functions to be called before a Language Server has been initialized
for a new workspace."
:type 'hook
:group 'lsp-mode)
(defcustom lsp-after-initialize-hook nil
"List of functions to be called after a Language Server has been initialized
for a new workspace."
:type 'hook
:group 'lsp-mode)
(defcustom lsp-before-open-hook nil
"List of functions to be called before a new file with LSP support is opened."
:type 'hook
:group 'lsp-mode)
(defcustom lsp-after-open-hook nil
"List of functions to be called after a new file with LSP support is opened."
:type 'hook
:group 'lsp-mode)
(defvar lsp--sync-methods
'((0 . none)
(1 . full)
(2 . incremental)))
(defvar-local lsp--server-sync-method nil
"Sync method recommended by the server.")
;;;###autoload
(defgroup lsp-mode nil
"Customization group for ‘lsp-mode’."
:group 'tools)
;;;###autoload
(defgroup lsp-faces nil
"Faces for ‘lsp-mode’."
:group 'lsp-mode)
;;;###autoload
(defcustom lsp-document-sync-method nil
"How to sync the document with the language server."
:type '(choice (const :tag "Documents should not be synced at all." 'none)
(const :tag "Documents are synced by always sending the full content of the document." 'full)
(const :tag "Documents are synced by always sending incremental changes to the document." 'incremental)
(const :tag "Use the method recommended by the language server." nil))
:group 'lsp-mode)
;;;###autoload
(defcustom lsp-project-blacklist nil
"A list of project directory regexps for which LSP shouldn't be initialized.
LSP should be initialized if the given project root matches one pattern in the
whitelist, or does not match any pattern in the blacklist."
:type '(repeat regexp)
:group 'lsp-mode)
(defcustom lsp-project-whitelist nil
"A list of project directory regexps for which LSP should be initialized."
:type '(repeat regexp)
:group 'lsp-mode)
;;;###autoload
(defcustom lsp-enable-eldoc t
"Enable `eldoc-mode' integration."
:type 'boolean
:group 'lsp-mode)
;;;###autoload
(defcustom lsp-highlight-symbol-at-point t
"Highlight the symbol under the point."
:type 'boolean
:group 'lsp-mode)
;;;###autoload
(defcustom lsp-enable-codeaction t
"Enable code action processing."
:type 'boolean
:group 'lsp-mode)
;;;###autoload
(defcustom lsp-enable-completion-at-point t
"Enable `completion-at-point' integration."
:type 'boolean
:group 'lsp-mode)
;;;###autoload
(defcustom lsp-enable-xref t
"Enable xref integration."
:type 'boolean
:group 'lsp-mode)
;;;###autoload
(defcustom lsp-enable-indentation t
"Indent regions using the file formatting functionality provided by the language server."
:type 'boolean
:group 'lsp-mode)
;;;###autoload
(defcustom lsp-before-save-edits t
"If non-nil, `lsp-mode' will apply edits suggested by the language server
before saving a document."
:type 'boolean
:group 'lsp-mode)
;;;###autoload
(defcustom lsp-symbol-highlight-delay eldoc-idle-delay
"Seconds of idle time to wait before showing symbol highlight."
:type 'number
:group 'lsp-mode)
;;;###autoload
(defface lsp-face-highlight-textual
'((((background dark)) :background "saddle brown")
(((background light)) :background "yellow"))
"Face used for textual occurances of symbols."
:group 'lsp-faces)
;;;###autoload
(defface lsp-face-highlight-read
'((((background dark)) :background "firebrick")
(((background light)) :background "red"))
"Face used for highlighting symbols being read."
:group 'lsp-faces)
;;;###autoload
(defface lsp-face-highlight-write
'((((background dark)) :background "sea green")
(((background light)) :background "green"))
"Face used for highlighting symbols being written to."
:group 'lsp-faces)
(defun lsp-client-register-uri-handler (client scheme handler)
(cl-check-type client lsp--client)
(cl-check-type scheme string)
(cl-check-type handler function)
(puthash scheme handler (lsp--client-uri-handlers client)))
(defun lsp-client-on-notification (client method callback)
(cl-check-type client lsp--client)
(cl-check-type method string)
(cl-check-type callback function)
(puthash method callback (lsp--client-notification-handlers client)))
(defun lsp-client-on-request (client method callback)
(cl-check-type client lsp--client)
(cl-check-type method string)
(cl-check-type callback function)
(puthash method callback (lsp--client-request-handlers client)))
(define-inline lsp--make-request (method &optional params)
"Create request body for method METHOD and parameters PARAMS."
(inline-quote
(plist-put (lsp--make-notification ,method ,params)
:id (cl-incf (lsp--client-last-id (lsp--workspace-client lsp--cur-workspace))))))
(defun lsp-make-request (method &optional params)
"Create request body for method METHOD and parameters PARAMS."
(lsp--make-request method params))
(defun lsp--make-response-error (code message data)
(cl-check-type code number)
(cl-check-type message string)
`(:code ,code :message ,message :data ,data))
(defun lsp--make-response (id result error)
(cl-check-type error list)
`(:jsonrpc "2.0" :id ,id :result ,result :error ,error))
(define-inline lsp--make-notification (method &optional params)
"Create notification body for method METHOD and parameters PARAMS."
(inline-quote
(progn (cl-check-type ,method string)
(list :jsonrpc "2.0" :method ,method :params ,params))))
;; Define non-inline public aliases to avoid breaking binary compatibility.
(defun lsp-make-notification (method &optional params)
"Create notification body for method METHOD and parameters PARAMS."
(lsp--make-notification method params))
(define-inline lsp--make-message (params)
"Create a LSP message from PARAMS, after encoding it to a JSON string."
(inline-quote
(let* ((json-false :json-false)
(body (json-encode ,params)))
(format "Content-Length: %d\r\n\r\n%s" (string-bytes body) body))))
(define-inline lsp--send-notification (body)
"Send BODY as a notification to the language server."
(inline-quote
(lsp--send-no-wait
(lsp--make-message ,body)
(lsp--workspace-proc lsp--cur-workspace))))
(defun lsp-send-notification (body)
"Send BODY as a notification to the language server."
(lsp--send-notification body))
(define-inline lsp--cur-workspace-check ()
(inline-quote
(progn
(cl-assert lsp--cur-workspace nil
"No language server is associated with this buffer.")
(cl-assert (lsp--workspace-p lsp--cur-workspace)))))
(define-inline lsp--cur-parser ()
(inline-quote (lsp--workspace-parser lsp--cur-workspace)))
(defun lsp--send-request (body &optional no-wait)
"Send BODY as a request to the language server, get the response.
If NO-WAIT is non-nil, don't synchronously wait for a response."
(let* ((parser (lsp--cur-parser))
(message (lsp--make-message body))
(process (lsp--workspace-proc lsp--cur-workspace)))
(setf (lsp--parser-waiting-for-response parser) (not no-wait))
(if no-wait
(lsp--send-no-wait message process)
(lsp--send-wait message process parser))
(when (not no-wait)
(prog1 (lsp--parser-response-result parser)
(setf (lsp--parser-response-result parser) nil)))))
(defalias 'lsp-send-request 'lsp--send-request
"Send BODY as a request to the language server and return the response synchronously.
\n(fn BODY)")
(defun lsp--send-request-async (body callback)
"Send BODY as a request to the language server, and call CALLBACK with
the response recevied from the server asynchronously."
(let ((client (lsp--workspace-client lsp--cur-workspace))
(id (plist-get body :id)))
(cl-assert id nil "body missing id field")
(puthash id callback (lsp--client-response-handlers client))
(lsp--send-no-wait (lsp--make-message body)
(lsp--workspace-proc lsp--cur-workspace))
body))
(defalias 'lsp-send-request-async 'lsp--send-request-async)
(define-inline lsp--inc-cur-file-version ()
(inline-quote (cl-incf (gethash buffer-file-name
(lsp--workspace-file-versions lsp--cur-workspace)))))
(define-inline lsp--cur-file-version ()
"Return the file version number. If INC, increment it before."
(inline-quote
(gethash buffer-file-name (lsp--workspace-file-versions lsp--cur-workspace))))
(define-inline lsp--make-text-document-item ()
"Make TextDocumentItem for the currently opened file.
interface TextDocumentItem {
uri: string; // The text document's URI
languageId: string; // The text document's language identifier.
version: number;
text: string;
}"
(inline-quote
(let ((language-id-fn (lsp--client-language-id (lsp--workspace-client lsp--cur-workspace))))
(list :uri (lsp--buffer-uri)
:languageId (funcall language-id-fn (current-buffer))
:version (lsp--cur-file-version)
:text (buffer-substring-no-properties (point-min) (point-max))))))
;; Clean up the entire state of lsp mode when Emacs is killed, to get rid of any
;; pending language servers.
(add-hook 'kill-emacs-hook #'lsp--global-teardown)
(defun lsp--global-teardown ()
(with-demoted-errors "Error in ‘lsp--global-teardown’: %S"
(maphash (lambda (_k value) (lsp--teardown-workspace value)) lsp--workspaces)))
(defun lsp--teardown-workspace (workspace)
(setq lsp--cur-workspace workspace)
(lsp--shutdown-cur-workspace))
(defun lsp--shutdown-cur-workspace ()
"Shut down the language server process for ‘lsp--cur-workspace’."
(with-demoted-errors "LSP error: %S"
(lsp--send-request (lsp--make-request "shutdown" (make-hash-table)) t)
(lsp--send-notification (lsp--make-notification "exit" nil)))
(lsp--uninitialize-workspace))
(defun lsp--uninitialize-workspace ()
"When a workspace is shut down, by request or from just
disappearing, unset all the variables related to it."
(let (proc
(root (lsp--workspace-root lsp--cur-workspace)))
(with-current-buffer (current-buffer)
(setq proc (lsp--workspace-proc lsp--cur-workspace))
(if (process-live-p proc)
(kill-process (lsp--workspace-proc lsp--cur-workspace)))
(setq lsp--cur-workspace nil)
(lsp--unset-variables)
(kill-local-variable 'lsp--cur-workspace))
(remhash root lsp--workspaces)))
(defun lsp-restart-workspace ()
"Shut down and then restart the current workspace.
This involves uninitializing each of the buffers associated with
the workspace, closing the process managing communication with
the client, and then starting up again."
(interactive)
(when (and (lsp-mode) (buffer-file-name) lsp--cur-workspace)
(let ((old-buffers (lsp--workspace-buffers lsp--cur-workspace))
(restart (lsp--client-enable-function (lsp--workspace-client lsp--cur-workspace)))
(proc (lsp--workspace-proc lsp--cur-workspace)))
(lsp--remove-cur-overlays)
;; Shut down the LSP mode for each buffer in the workspace
(dolist (buffer old-buffers)
(with-current-buffer buffer
(lsp--text-document-did-close)
(setq lsp--cur-workspace nil)
(lsp-mode -1)))
;; Let the process actually shut down
(while (process-live-p proc)
(accept-process-output proc))
;; Re-enable LSP mode for each buffer
(dolist (buffer old-buffers)
(with-current-buffer buffer
(funcall restart))))))
;; NOTE: Possibly make this function subject to a setting, if older LSP servers
;; are unhappy
(defun lsp--client-capabilities ()
"Return the client capabilites."
(apply #'lsp--merge-plists
`(:workspace ,(lsp--client-workspace-capabilities)
:textDocument ,(lsp--client-textdocument-capabilities))
(seq-map (lambda (extra-capabilities-cons)
(let* ((package-name (car extra-capabilities-cons))
(value (cdr extra-capabilities-cons))
(capabilities (if (functionp value) (funcall value)
value)))
(if (and capabilities (not (listp capabilities)))
(progn
(message "Capabilities provided by %s are not a plist: %s" package-name value)
nil)
capabilities)))
(lsp--workspace-extra-client-capabilities lsp--cur-workspace))))
(defun lsp--merge-plists (first &rest rest)
"Deeply merge plists.
FIRST is the plist to be merged into. The rest of the arguments
can be either plists or nil. The non-nil plists in the rest of
the arguments will be merged into FIRST.
Return the merged plist."
(cl-check-type first list)
(seq-each
(lambda (pl) (setq first (lsp--merge-two-plists first pl)))
rest)
first)
(defun lsp--merge-two-plists (first second)
"Deeply merge two plists.
All values in SECOND are merged into FIRST. FIRST can be nil or
a plist. SECOND must be a plist.
Return the merged plist."
(when second
(if (not (listp second))
(warn "Cannot merge non-list value into a plist. The value is %s" second)
(cl-loop for (key second-value) on second
collect (progn
(let ((first-value (plist-get first key))
merged-value)
(cond
((null second-value)) ; do nothing
((null first-value)
(if (listp second-value)
;; Deep copy second-value so that the original value won't
;; be modified.
(setq merged-value
(lsp--merge-two-plists nil second-value)))
(setq merged-value second-value))
((and (listp first-value) (listp second-value))
(setq merged-value (lsp--merge-two-plists first-value second-value)))
;; Otherwise, the first value is a leaf entry and should
;; not be overridden.
)
(when merged-value
(setq first (plist-put first key merged-value))))))))
first)
(defun lsp--server-register-capability (reg)
(lsp--cur-workspace-check)
(let ((method (gethash "method" reg)))
(push
(make-lsp--registered-capability
:id (gethash "id" reg)
:method method
:options (gethash "registerOptions" reg))
(lsp--workspace-registered-server-capabilities lsp--cur-workspace))))
(defun lsp--server-unregister-capability (unreg)
(let* ((id (gethash "id" unreg))
(fn (lambda (e) (equal (lsp--registered-capability-id e) id))))
(setf (lsp--workspace-registered-server-capabilities lsp--cur-workspace)
(seq-remove fn
(lsp--workspace-registered-server-capabilities lsp--cur-workspace)))))
(defun lsp--client-workspace-capabilities ()
"Client Workspace capabilities according to LSP."
`(:applyEdit t
:executeCommand (:dynamicRegistration t)))
(defun lsp--client-textdocument-capabilities ()
"Client Text document capabilities according to LSP."
`(:synchronization (:willSave t :didSave t)
:symbol (:symbolKind (:valueSet ,(cl-loop for kind from 1 to 25 collect kind)))))
(defun lsp-register-client-capabilities (package-name caps)
"Register extra client capabilities for the current workspace.
This function must be called before the initialize request is
sent. It's recommended to to call it in the
`lsp-before-initialize-hook'.
PACKAGE name is the symbol of the name of the package that
registers the capabilities. CAPS is either a plist of the
capabilities, or a function that takes no argument and return a
plist of the client capabilties or nil.
Registered capabilities are merged into the default capabilities
before sending to the server via the initialize request. If two
packages provide different values for the same leaf capability
entry, the value is set to the one that registers later. Default
leaf capability entries can not be overwritten."
(lsp--cur-workspace-check)
(cl-check-type package-name symbolp)
(cl-check-type package-name (or list function))
(let ((extra-client-capabilities
(lsp--workspace-extra-client-capabilities lsp--cur-workspace)))
(if (alist-get package-name extra-client-capabilities)
(message "%s has already registered client capabilities" package-name)
(push `(,package-name . ,caps)
(lsp--workspace-extra-client-capabilities lsp--cur-workspace)))))
(defun lsp-unregister-client-capabilities (package-name)
"Unregister extra capabilities provided by PACKAGE-NAME for the current workspace.
PACKAGE-NAME is a symbol of the name of the package that has
registered client capabilities by calling
`lsp-register-client-capabilities'."
(lsp--cur-workspace-check)
(cl-check-type package-name symbol)
(let ((extra-client-capabilities
(lsp--workspace-extra-client-capabilities lsp--cur-workspace)))
(setf (lsp--workspace-extra-client-capabilities lsp--cur-workspace)
(assq-delete-all package-name extra-client-capabilities))))
(define-inline lsp--server-capabilities ()
"Return the capabilities of the language server associated with the buffer."
(inline-quote (lsp--workspace-server-capabilities lsp--cur-workspace)))
(defun lsp--server-has-sync-options-p ()
"Return whether the server has a TextDocumentSyncOptions object in
ServerCapabilities.textDocumentSync."
(hash-table-p (gethash "textDocumentSync" (lsp--server-capabilities))))
(defun lsp--send-open-close-p ()
"Return whether open and close notifications should be sent to the server."
(let ((sync (gethash "textDocumentSync" (lsp--server-capabilities))))
(and (hash-table-p sync)
(gethash "openClose" sync))))
(defun lsp--send-will-save-p ()
"Return whether will save notifications should be sent to the server."
(let ((sync (gethash "textDocumentSync" (lsp--server-capabilities))))
(and (hash-table-p sync)
(gethash "willSave" sync))))
(defun lsp--send-will-save-wait-until-p ()
"Return whether will save wait until notifications should be sent to the server."
(let ((sync (gethash "textDocumentSync" (lsp--server-capabilities))))
(and (hash-table-p sync)
(gethash "willSaveWaitUntil" sync))))
(defun lsp--save-include-text-p ()
"Return whether save notifications should include the text document's contents."
(let ((sync (gethash "textDocumentSync" (lsp--server-capabilities))))
(and (hash-table-p sync)
(hash-table-p (gethash "save" sync nil))
(gethash "includeText" (gethash "save" sync)))))
(defun lsp--set-sync-method ()
(let* ((sync (gethash "textDocumentSync" (lsp--server-capabilities)))
(kind (if (hash-table-p sync) (gethash "change" sync) sync))
(method (alist-get kind lsp--sync-methods)))
(setq lsp--server-sync-method (or lsp-document-sync-method
method))))
(defun lsp--workspace-apply-edit-handler (_workspace params)
(lsp--apply-workspace-edit (gethash "edit" params)))
(defun lsp--make-sentinel (workspace)
(cl-check-type workspace lsp--workspace)
(lambda (process exit-str)
(let ((status (process-status process)))
(when (memq status '(exit signal))
;; Server has exited. Uninitialize all buffer-local state for this
;; workspace.
(message "%s: %s has exited (%s)"
(lsp--workspace-root workspace)
(process-name (lsp--workspace-proc workspace))
(string-trim-right exit-str))
(dolist (buf (lsp--workspace-buffers workspace))
(with-current-buffer buf
(lsp--uninitialize-workspace)))
;; Kill standard error buffer only if the process exited normally.
;; Leave it intact otherwise for debugging purposes.
(when (and (eq status 'exit) (zerop (process-exit-status process)))
;; FIXME: The client structure should store the standard error
;; buffer, not its name.
;; FIXME: Probably the standard error buffer should be per workspace,
;; not per client.
(let ((stderr (get-buffer (lsp--client-stderr
(lsp--workspace-client workspace)))))
(when (buffer-live-p stderr)
(kill-buffer stderr))))))))
(defun lsp--should-start-p (root)
"Consult `lsp-project-blacklist' and `lsp-project-whitelist' to
determine if a server should be started for the given ROOT
directory."
(or
(cl-some (lambda (p) (string-match-p p root))
lsp-project-whitelist)
(cl-notany (lambda (p) (string-match-p p root))
lsp-project-blacklist)))
(defun lsp--start (client &optional extra-init-params)
(when lsp--cur-workspace
(user-error "LSP mode is already enabled for this buffer"))
(cl-assert client)
(let* ((root (file-truename (funcall (lsp--client-get-root client))))
(workspace (gethash root lsp--workspaces))
new-conn response init-params
parser proc cmd-proc)
(if workspace
(setq lsp--cur-workspace workspace)
(setf
parser (make-lsp--parser)
lsp--cur-workspace (make-lsp--workspace
:parser parser
:file-versions (make-hash-table :test 'equal)
:root root
:client client)
(lsp--parser-workspace parser) lsp--cur-workspace
new-conn (funcall
(lsp--client-new-connection client)
(lsp--parser-make-filter parser (lsp--client-ignore-regexps client))
(lsp--make-sentinel lsp--cur-workspace))
;; the command line process invoked
cmd-proc (if (consp new-conn) (car new-conn) new-conn)
;; the process we actually communicate with
proc (if (consp new-conn) (cdr new-conn) new-conn)
(lsp--workspace-proc lsp--cur-workspace) proc
(lsp--workspace-cmd-proc lsp--cur-workspace) cmd-proc)
(puthash root lsp--cur-workspace lsp--workspaces)
(run-hooks 'lsp-before-initialize-hook)
(setq init-params
`(:processId ,(emacs-pid)
:rootPath ,root
:rootUri ,(lsp--path-to-uri root)
:capabilities ,(lsp--client-capabilities)
:initializationOptions ,(if (functionp extra-init-params)
(funcall extra-init-params lsp--cur-workspace)
extra-init-params)))
(setf response (lsp--send-request
(lsp--make-request "initialize" init-params)))
(unless response
(signal 'lsp-empty-response-error (list "initialize")))
(setf (lsp--workspace-server-capabilities lsp--cur-workspace)
(gethash "capabilities" response))
;; Version 3.0 now sends an "initialized" notification to allow registration
;; of server capabilities
(lsp--send-notification (lsp--make-notification "initialized" (make-hash-table)))
(run-hooks 'lsp-after-initialize-hook))
(lsp--text-document-did-open)))
(defun lsp--text-document-did-open ()
(run-hooks 'lsp-before-open-hook)
(puthash buffer-file-name 0 (lsp--workspace-file-versions lsp--cur-workspace))
(push (current-buffer) (lsp--workspace-buffers lsp--cur-workspace))
(lsp--send-notification (lsp--make-notification
"textDocument/didOpen"
`(:textDocument ,(lsp--make-text-document-item))))
(add-hook 'after-save-hook #'lsp-on-save nil t)
(add-hook 'kill-buffer-hook #'lsp--text-document-did-close nil t)
(add-hook 'post-command-hook 'lsp--highlight nil t)
(when lsp-enable-eldoc
;; XXX: The documentation for `eldoc-documentation-function' suggests
;; using `add-function' for modifying its value, use that instead?
(setq-local eldoc-documentation-function #'lsp--on-hover)
(eldoc-mode 1))
(when (and lsp-enable-indentation
(lsp--capability "documentRangeFormattingProvider"))
(setq-local indent-region-function #'lsp-format-region))
(when lsp-enable-xref
(setq-local xref-backend-functions (list #'lsp--xref-backend)))
(when (and lsp-enable-completion-at-point (lsp--capability "completionProvider"))
(setq-local completion-at-point-functions nil)
(add-hook 'completion-at-point-functions #'lsp-completion-at-point nil t))
;; Make sure the hook is local (last param) otherwise we see all changes for all buffers
(add-hook 'before-change-functions #'lsp-before-change nil t)
(add-hook 'after-change-functions #'lsp-on-change nil t)
(add-hook 'before-save-hook #'lsp--before-save nil t)
(add-hook 'auto-save-hook #'lsp--on-auto-save nil t)
(lsp--set-sync-method)
(run-hooks 'lsp-after-open-hook))
(define-inline lsp--text-document-identifier ()
"Make TextDocumentIdentifier.
interface TextDocumentIdentifier {
uri: string;
}"
(inline-quote (list :uri (lsp--buffer-uri))))
(define-inline lsp--versioned-text-document-identifier ()
"Make VersionedTextDocumentIdentifier.
interface VersionedTextDocumentIdentifier extends TextDocumentIdentifier {
version: number;
}"
(inline-quote (plist-put (lsp--text-document-identifier)
:version (lsp--cur-file-version))))
(define-inline lsp--position (line char)
"Make a Position object for the given LINE and CHAR.
interface Position {
line: number;
character: number;
}"
(inline-quote (list :line ,line :character ,char)))
(define-inline lsp--cur-line ()
(inline-quote (1- (line-number-at-pos))))
(define-inline lsp--cur-column ()
(inline-quote (- (point) (line-beginning-position))))
(define-inline lsp--cur-position ()
"Make a Position object for the current point."
(inline-quote
(save-restriction
(widen)
(lsp--position (lsp--cur-line) (lsp--cur-column)))))
(defun lsp--point-to-position (point)
"Convert POINT to Position."
(save-excursion
(goto-char point)
(lsp--cur-position)))
(define-inline lsp--position-p (p)
(inline-quote
(and (numberp (plist-get ,p :line)) (numberp (plist-get ,p :character)))))
(define-inline lsp--range (start end)
"Make Range body from START and END.
interface Range {
start: Position;
end: Position;
}"
;; make sure start and end are Position objects
(inline-quote
(progn
(cl-check-type ,start (satisfies lsp--position-p))
(cl-check-type ,end (satisfies lsp--position-p))
(list :start ,start :end ,end))))
(define-inline lsp--region-to-range (start end)
"Make Range object for the current region."
(inline-quote (lsp--range (lsp--point-to-position ,start)
(lsp--point-to-position ,end))))
(defun lsp--current-region-or-pos ()
"If the region is active return that, else get the point."
(if (use-region-p)
(lsp--region-to-range (region-beginning) (region-end))
(lsp--region-to-range (point) (point))))
(defun lsp--get-start-position ()
"Get the start of the region if active, else current point."
(let ((pos (if (use-region-p)
(region-beginning)
(point))))
(lsp-point-to-position pos)))
(defun lsp--get-end-position ()
"Get the end of the region if active, else current point."
(let ((pos (if (use-region-p)
(region-end)
(point))))
(lsp-point-to-position pos)))
(define-inline lsp--range-start-line (range)
"Return the start line for a given LSP range, in LSP coordinates"
(inline-quote (plist-get (plist-get ,range :start) :line)))
(define-inline lsp--range-end-line (range)
"Return the end line for a given LSP range, in LSP coordinates"
(inline-quote (plist-get (plist-get ,range :end) :line)))
(defun lsp--apply-workspace-edit (edit)
"Apply the WorkspaceEdit object EDIT.
interface WorkspaceEdit {
changes?: { [uri: string]: TextEdit[]; };
documentChanges?: TextDocumentEdit[];
}"
(let ((changes (gethash "changes" edit))
(document-changes (gethash "documentChanges" edit)))
(if document-changes
(mapc #'lsp--apply-text-document-edit document-changes)
(when (hash-table-p changes)
(maphash
(lambda (uri text-edits)
(let ((filename (lsp--uri-to-path uri)))
(with-current-buffer (find-file-noselect filename)
(lsp--apply-text-edits text-edits))))
changes)))))
(defun lsp--apply-text-document-edit (edit)
"Apply the TextDocumentEdit object EDIT.
If the file is not being visited by any buffer, it is opened with
`find-file-noselect'.
Because lsp-mode does not store previous document versions, the edit is only
applied if the version of the textDocument matches the version of the
corresponding file.
interface TextDocumentEdit {
textDocument: VersionedTextDocumentIdentifier;
edits: TextEdit[];
}"
(let* ((ident (gethash "textDocument" edit))
(filename (lsp--uri-to-path (gethash "uri" ident)))
(version (gethash "version" ident)))
(with-current-buffer (find-file-noselect filename)
(when (= version (lsp--cur-file-version))
(lsp--apply-text-edits (gethash "edits" edit))))))
(defun lsp--text-edit-sort-predicate (e1 e2)
(let ((start1 (lsp--position-to-point (gethash "start" (gethash "range" e1))))
(start2 (lsp--position-to-point (gethash "start" (gethash "range" e2)))))
(if (= start1 start2)
(let ((end1 (lsp--position-to-point (gethash "end" (gethash "range" e1))))
(end2 (lsp--position-to-point (gethash "end" (gethash "range" e2)))))
(> end1 end2))
(> start1 start2))))
(define-inline lsp--apply-text-edits (edits)
"Apply the edits described in the TextEdit[] object in EDITS."
(inline-quote