forked from joaotavora/eglot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
eglot.el
2792 lines (2553 loc) · 127 KB
/
eglot.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
;;; eglot.el --- Client for Language Server Protocol (LSP) servers -*- lexical-binding: t; -*-
;; Copyright (C) 2018-2020 Free Software Foundation, Inc.
;; Version: 1.7
;; Author: João Távora <joaotavora@gmail.com>
;; Maintainer: João Távora <joaotavora@gmail.com>
;; URL: https://github.com/joaotavora/eglot
;; Keywords: convenience, languages
;; Package-Requires: ((emacs "26.1") (jsonrpc "1.0.14") (flymake "1.0.9") (project "0.3.0") (xref "1.0.1") (eldoc "1.11.0"))
;; 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/>.
;;; Commentary:
;; Simply M-x eglot should be enough to get you started, but here's a
;; little info (see the accompanying README.md or the URL for more).
;;
;; M-x eglot starts a server via a shell-command guessed from
;; `eglot-server-programs', using the current major-mode (for whatever
;; language you're programming in) as a hint. If it can't guess, it
;; prompts you in the mini-buffer for these things. Actually, the
;; server needen't be locally started: you can connect to a running
;; server via TCP by entering a <host:port> syntax.
;;
;; Anyway, if the connection is successful, you should see an `eglot'
;; indicator pop up in your mode-line. More importantly, this means
;; current *and future* file buffers of that major mode *inside your
;; current project* automatically become \"managed\" by the LSP
;; server, i.e. information about their contents is exchanged
;; periodically to provide enhanced code analysis via
;; `xref-find-definitions', `flymake-mode', `eldoc-mode',
;; `completion-at-point', among others.
;;
;; To "unmanage" these buffers, shutdown the server with M-x
;; eglot-shutdown.
;;
;; You can also do:
;;
;; (add-hook 'foo-mode-hook 'eglot-ensure)
;;
;; To attempt to start an eglot session automatically everytime a
;; foo-mode buffer is visited.
;;
;;; Code:
(require 'json)
(require 'imenu)
(require 'cl-lib)
(require 'project)
(require 'url-parse)
(require 'url-util)
(require 'pcase)
(require 'compile) ; for some faces
(require 'warnings)
(require 'flymake)
(require 'xref)
(eval-when-compile
(require 'subr-x))
(require 'jsonrpc)
(require 'filenotify)
(require 'ert)
(require 'array)
;; ElDoc is preloaded in Emacs, so `require'-ing won't guarantee we are
;; using the latest version from GNU Elpa when we load eglot.el. Use an
;; heuristic to see if we need to `load' it in Emacs < 28.
(if (and (< emacs-major-version 28)
(not (boundp 'eldoc-documentation-strategy)))
(load "eldoc")
(require 'eldoc))
;; forward-declare, but don't require (Emacs 28 doesn't seem to care)
(defvar markdown-fontify-code-blocks-natively)
(defvar company-backends)
(defvar company-tooltip-align-annotations)
;;; User tweakable stuff
(defgroup eglot nil
"Interaction with Language Server Protocol servers"
:prefix "eglot-"
:group 'applications)
(defvar eglot-server-programs '((rust-mode . (eglot-rls "rls"))
(python-mode . ("pyls"))
((js-mode
typescript-mode)
. ("javascript-typescript-stdio"))
(sh-mode . ("bash-language-server" "start"))
(php-mode
. ("php" "vendor/felixfbecker/\
language-server/bin/php-language-server.php"))
((c++-mode c-mode) . ("ccls"))
((caml-mode tuareg-mode reason-mode)
. ("ocaml-language-server" "--stdio"))
(ruby-mode
. ("solargraph" "socket" "--port" :autoport))
(haskell-mode
. ("haskell-language-server-wrapper" "--lsp"))
(elm-mode . ("elm-language-server"))
(kotlin-mode . ("kotlin-language-server"))
(go-mode . ("gopls"))
((R-mode ess-r-mode) . ("R" "--slave" "-e"
"languageserver::run()"))
(java-mode . eglot--eclipse-jdt-contact)
(dart-mode . ("dart_language_server"))
(elixir-mode . ("language_server.sh"))
(ada-mode . ("ada_language_server"))
(scala-mode . ("metals-emacs"))
((tex-mode context-mode texinfo-mode bibtex-mode)
. ("digestif"))
(erlang-mode . ("erlang_ls" "--transport" "stdio"))
(nix-mode . ("rnix-lsp"))
(gdscript-mode . ("localhost" 6008))
(f90-mode . ("fortls")))
"How the command `eglot' guesses the server to start.
An association list of (MAJOR-MODE . CONTACT) pairs. MAJOR-MODE
is a mode symbol, or a list of mode symbols. The associated
CONTACT specifies how to connect to a server for managing buffers
of those modes. CONTACT can be:
* In the most common case, a list of strings (PROGRAM [ARGS...]).
PROGRAM is called with ARGS and is expected to serve LSP requests
over the standard input/output channels.
* A list (HOST PORT [TCP-ARGS...]) where HOST is a string and
PORT is a positive integer for connecting to a server via TCP.
Remaining ARGS are passed to `open-network-stream' for
upgrading the connection with encryption or other capabilities.
* A list (PROGRAM [ARGS...] :autoport [MOREARGS...]), whereupon a
combination of the two previous options is used. First, an
attempt is made to find an available server port, then PROGRAM
is launched with ARGS; the `:autoport' keyword substituted for
that number; and MOREARGS. Eglot then attempts to establish a
TCP connection to that port number on the localhost.
* A cons (CLASS-NAME . INITARGS) where CLASS-NAME is a symbol
designating a subclass of `eglot-lsp-server', for representing
experimental LSP servers. INITARGS is a keyword-value plist
used to initialize the object of CLASS-NAME, or a plain list
interpreted as the previous descriptions of CONTACT. In the
latter case that plain list is used to produce a plist with a
suitable :PROCESS initarg to CLASS-NAME. The class
`eglot-lsp-server' descends from `jsonrpc-process-connection',
which you should see for the semantics of the mandatory
:PROCESS argument.
* A function of a single argument producing any of the above
values for CONTACT. The argument's value is non-nil if the
connection was requested interactively (e.g. from the `eglot'
command), and nil if it wasn't (e.g. from `eglot-ensure'). If
the call is interactive, the function can ask the user for
hints on finding the required programs, etc. Otherwise, it
should not ask the user for any input, and return nil or signal
an error if it can't produce a valid CONTACT.")
(defface eglot-highlight-symbol-face
'((t (:inherit bold)))
"Face used to highlight the symbol at point.")
(defface eglot-mode-line
'((t (:inherit font-lock-constant-face :weight bold)))
"Face for package-name in EGLOT's mode line.")
(defcustom eglot-autoreconnect 3
"Control ability to reconnect automatically to the LSP server.
If t, always reconnect automatically (not recommended). If nil,
never reconnect automatically after unexpected server shutdowns,
crashes or network failures. A positive integer number says to
only autoreconnect if the previous successful connection attempt
lasted more than that many seconds."
:type '(choice (boolean :tag "Whether to inhibit autoreconnection")
(integer :tag "Number of seconds")))
(defcustom eglot-connect-timeout 30
"Number of seconds before timing out LSP connection attempts.
If nil, never time out."
:type 'number)
(defcustom eglot-sync-connect 3
"Control blocking of LSP connection attempts.
If t, block for `eglot-connect-timeout' seconds. A positive
integer number means block for that many seconds, and then wait
for the connection in the background. nil has the same meaning
as 0, i.e. don't block at all."
:type '(choice (boolean :tag "Whether to inhibit autoreconnection")
(integer :tag "Number of seconds")))
(defcustom eglot-autoshutdown nil
"If non-nil, shut down server after killing last managed buffer."
:type 'boolean)
(defcustom eglot-send-changes-idle-time 0.5
"Don't tell server of changes before Emacs's been idle for this many seconds."
:type 'number)
(defcustom eglot-events-buffer-size 2000000
"Control the size of the Eglot events buffer.
If a number, don't let the buffer grow larger than that many
characters. If 0, don't use an event's buffer at all. If nil,
let the buffer grow forever."
:type '(choice (const :tag "No limit" nil)
(integer :tag "Number of characters")))
(defcustom eglot-confirm-server-initiated-edits 'confirm
"Non-nil if server-initiated edits should be confirmed with user."
:type '(choice (const :tag "Don't show confirmation prompt" nil)
(symbol :tag "Show confirmation prompt" 'confirm)))
;;; Constants
;;;
(defconst eglot--symbol-kind-names
`((1 . "File") (2 . "Module")
(3 . "Namespace") (4 . "Package") (5 . "Class")
(6 . "Method") (7 . "Property") (8 . "Field")
(9 . "Constructor") (10 . "Enum") (11 . "Interface")
(12 . "Function") (13 . "Variable") (14 . "Constant")
(15 . "String") (16 . "Number") (17 . "Boolean")
(18 . "Array") (19 . "Object") (20 . "Key")
(21 . "Null") (22 . "EnumMember") (23 . "Struct")
(24 . "Event") (25 . "Operator") (26 . "TypeParameter")))
(defconst eglot--kind-names
`((1 . "Text") (2 . "Method") (3 . "Function") (4 . "Constructor")
(5 . "Field") (6 . "Variable") (7 . "Class") (8 . "Interface")
(9 . "Module") (10 . "Property") (11 . "Unit") (12 . "Value")
(13 . "Enum") (14 . "Keyword") (15 . "Snippet") (16 . "Color")
(17 . "File") (18 . "Reference")))
(defconst eglot--{} (make-hash-table) "The empty JSON object.")
;;; Message verification helpers
;;;
(eval-and-compile
(defvar eglot--lsp-interface-alist
`(
(CodeAction (:title) (:kind :diagnostics :edit :command :isPreferred))
(ConfigurationItem () (:scopeUri :section))
(Command ((:title . string) (:command . string)) (:arguments))
(CompletionItem (:label)
(:kind :detail :documentation :deprecated :preselect
:sortText :filterText :insertText :insertTextFormat
:textEdit :additionalTextEdits :commitCharacters
:command :data))
(Diagnostic (:range :message) (:severity :code :source :relatedInformation))
(DocumentHighlight (:range) (:kind))
(FileSystemWatcher (:globPattern) (:kind))
(Hover (:contents) (:range))
(InitializeResult (:capabilities) (:serverInfo))
(Location (:uri :range))
(LogMessageParams (:type :message))
(MarkupContent (:kind :value))
(ParameterInformation (:label) (:documentation))
(Position (:line :character))
(Range (:start :end))
(Registration (:id :method) (:registerOptions))
(Registration (:id :method) (:registerOptions))
(ResponseError (:code :message) (:data))
(ShowMessageParams (:type :message))
(ShowMessageRequestParams (:type :message) (:actions))
(SignatureHelp (:signatures) (:activeSignature :activeParameter))
(SignatureInformation (:label) (:documentation :parameters))
(SymbolInformation (:name :kind :location)
(:deprecated :containerName))
(DocumentSymbol (:name :range :selectionRange :kind)
;; `:containerName' isn't really allowed , but
;; it simplifies the impl of `eglot-imenu'.
(:detail :deprecated :children :containerName))
(TextDocumentEdit (:textDocument :edits) ())
(TextEdit (:range :newText))
(VersionedTextDocumentIdentifier (:uri :version) ())
(WorkspaceEdit () (:changes :documentChanges))
)
"Alist (INTERFACE-NAME . INTERFACE) of known external LSP interfaces.
INTERFACE-NAME is a symbol designated by the spec as
\"interface\". INTERFACE is a list (REQUIRED OPTIONAL) where
REQUIRED and OPTIONAL are lists of KEYWORD designating field
names that must be, or may be, respectively, present in a message
adhering to that interface. KEY can be a keyword or a cons (SYM
TYPE), where type is used by `cl-typep' to check types at
runtime.
Here's what an element of this alist might look like:
(Command ((:title . string) (:command . string)) (:arguments))"))
(eval-and-compile
(defvar eglot-strict-mode (if load-file-name '()
'(disallow-non-standard-keys
;; Uncomment these two for fun at
;; compile-time or with flymake-mode.
;;
;; enforce-required-keys
;; enforce-optional-keys
))
"How strictly to check LSP interfaces at compile- and run-time.
Value is a list of symbols (if the list is empty, no checks are
performed).
If the symbol `disallow-non-standard-keys' is present, an error
is raised if any extraneous fields are sent by the server. At
compile-time, a warning is raised if a destructuring spec
includes such a field.
If the symbol `enforce-required-keys' is present, an error is
raised if any required fields are missing from the message sent
from the server. At compile-time, a warning is raised if a
destructuring spec doesn't use such a field.
If the symbol `enforce-optional-keys' is present, nothing special
happens at run-time. At compile-time, a warning is raised if a
destructuring spec doesn't use all optional fields.
If the symbol `disallow-unknown-methods' is present, Eglot warns
on unknown notifications and errors on unknown requests.
"))
(defun eglot--plist-keys (plist)
(cl-loop for (k _v) on plist by #'cddr collect k))
(cl-defun eglot--check-object (interface-name
object
&optional
(enforce-required t)
(disallow-non-standard t)
(check-types t))
"Check that OBJECT conforms to INTERFACE. Error otherwise."
(cl-destructuring-bind
(&key types required-keys optional-keys &allow-other-keys)
(eglot--interface interface-name)
(when-let ((missing (and enforce-required
(cl-set-difference required-keys
(eglot--plist-keys object)))))
(eglot--error "A `%s' must have %s" interface-name missing))
(when-let ((excess (and disallow-non-standard
(cl-set-difference
(eglot--plist-keys object)
(append required-keys optional-keys)))))
(eglot--error "A `%s' mustn't have %s" interface-name excess))
(when check-types
(cl-loop
for (k v) on object by #'cddr
for type = (or (cdr (assoc k types)) t) ;; FIXME: enforce nil type?
unless (cl-typep v type)
do (eglot--error "A `%s' must have a %s as %s, but has %s"
interface-name )))
t))
(eval-and-compile
(defun eglot--keywordize-vars (vars)
(mapcar (lambda (var) (intern (format ":%s" var))) vars))
(defun eglot--ensure-type (k) (if (consp k) k (cons k t)))
(defun eglot--interface (interface-name)
(let* ((interface (assoc interface-name eglot--lsp-interface-alist))
(required (mapcar #'eglot--ensure-type (car (cdr interface))))
(optional (mapcar #'eglot--ensure-type (cadr (cdr interface)))))
(list :types (append required optional)
:required-keys (mapcar #'car required)
:optional-keys (mapcar #'car optional))))
(defun eglot--check-dspec (interface-name dspec)
"Check destructuring spec DSPEC against INTERFACE-NAME."
(cl-destructuring-bind (&key required-keys optional-keys &allow-other-keys)
(eglot--interface interface-name)
(cond ((or required-keys optional-keys)
(let ((too-many
(and
(memq 'disallow-non-standard-keys eglot-strict-mode)
(cl-set-difference
(eglot--keywordize-vars dspec)
(append required-keys optional-keys))))
(ignored-required
(and
(memq 'enforce-required-keys eglot-strict-mode)
(cl-set-difference
required-keys (eglot--keywordize-vars dspec))))
(missing-out
(and
(memq 'enforce-optional-keys eglot-strict-mode)
(cl-set-difference
optional-keys (eglot--keywordize-vars dspec)))))
(when too-many (byte-compile-warn
"Destructuring for %s has extraneous %s"
interface-name too-many))
(when ignored-required (byte-compile-warn
"Destructuring for %s ignores required %s"
interface-name ignored-required))
(when missing-out (byte-compile-warn
"Destructuring for %s is missing out on %s"
interface-name missing-out))))
(t
(byte-compile-warn "Unknown LSP interface %s" interface-name))))))
(cl-defmacro eglot--dbind (vars object &body body)
"Destructure OBJECT, binding VARS in BODY.
VARS is ([(INTERFACE)] SYMS...)
Honour `eglot-strict-mode'."
(declare (indent 2) (debug (sexp sexp &rest form)))
(let ((interface-name (if (consp (car vars))
(car (pop vars))))
(object-once (make-symbol "object-once"))
(fn-once (make-symbol "fn-once")))
(cond (interface-name
(eglot--check-dspec interface-name vars)
`(let ((,object-once ,object))
(cl-destructuring-bind (&key ,@vars &allow-other-keys) ,object-once
(eglot--check-object ',interface-name ,object-once
(memq 'enforce-required-keys eglot-strict-mode)
(memq 'disallow-non-standard-keys eglot-strict-mode)
(memq 'check-types eglot-strict-mode))
,@body)))
(t
`(let ((,object-once ,object)
(,fn-once (lambda (,@vars) ,@body)))
(if (memq 'disallow-non-standard-keys eglot-strict-mode)
(cl-destructuring-bind (&key ,@vars) ,object-once
(funcall ,fn-once ,@vars))
(cl-destructuring-bind (&key ,@vars &allow-other-keys) ,object-once
(funcall ,fn-once ,@vars))))))))
(cl-defmacro eglot--lambda (cl-lambda-list &body body)
"Function of args CL-LAMBDA-LIST for processing INTERFACE objects.
Honour `eglot-strict-mode'."
(declare (indent 1) (debug (sexp &rest form)))
(let ((e (cl-gensym "jsonrpc-lambda-elem")))
`(lambda (,e) (eglot--dbind ,cl-lambda-list ,e ,@body))))
(cl-defmacro eglot--dcase (obj &rest clauses)
"Like `pcase', but for the LSP object OBJ.
CLAUSES is a list (DESTRUCTURE FORMS...) where DESTRUCTURE is
treated as in `eglot-dbind'."
(declare (indent 1) (debug (sexp &rest (sexp &rest form))))
(let ((obj-once (make-symbol "obj-once")))
`(let ((,obj-once ,obj))
(cond
,@(cl-loop
for (vars . body) in clauses
for vars-as-keywords = (eglot--keywordize-vars vars)
for interface-name = (if (consp (car vars))
(car (pop vars)))
for condition =
(cond (interface-name
(eglot--check-dspec interface-name vars)
;; In this mode, in runtime, we assume
;; `eglot-strict-mode' is partially on, otherwise we
;; can't disambiguate between certain types.
`(ignore-errors
(eglot--check-object
',interface-name ,obj-once
t
(memq 'disallow-non-standard-keys eglot-strict-mode)
t)))
(t
;; In this interface-less mode we don't check
;; `eglot-strict-mode' at all: just check that the object
;; has all the keys the user wants to destructure.
`(null (cl-set-difference
',vars-as-keywords
(eglot--plist-keys ,obj-once)))))
collect `(,condition
(cl-destructuring-bind (&key ,@vars &allow-other-keys)
,obj-once
,@body)))
(t
(eglot--error "%S didn't match any of %S"
,obj-once
',(mapcar #'car clauses)))))))
;;; API (WORK-IN-PROGRESS!)
;;;
(cl-defmacro eglot--when-live-buffer (buf &rest body)
"Check BUF live, then do BODY in it." (declare (indent 1) (debug t))
(let ((b (cl-gensym)))
`(let ((,b ,buf)) (if (buffer-live-p ,b) (with-current-buffer ,b ,@body)))))
(cl-defmacro eglot--when-buffer-window (buf &body body)
"Check BUF showing somewhere, then do BODY in it" (declare (indent 1) (debug t))
(let ((b (cl-gensym)))
`(let ((,b ,buf))
;;notice the exception when testing with `ert'
(when (or (get-buffer-window ,b) (ert-running-test))
(with-current-buffer ,b ,@body)))))
(cl-defmacro eglot--widening (&rest body)
"Save excursion and restriction. Widen. Then run BODY." (declare (debug t))
`(save-excursion (save-restriction (widen) ,@body)))
(cl-defgeneric eglot-handle-request (server method &rest params)
"Handle SERVER's METHOD request with PARAMS.")
(cl-defgeneric eglot-handle-notification (server method &rest params)
"Handle SERVER's METHOD notification with PARAMS.")
(cl-defgeneric eglot-execute-command (server command arguments)
"Ask SERVER to execute COMMAND with ARGUMENTS.")
(cl-defgeneric eglot-initialization-options (server)
"JSON object to send under `initializationOptions'"
(:method (_s) eglot--{})) ; blank default
(cl-defgeneric eglot-register-capability (server method id &rest params)
"Ask SERVER to register capability METHOD marked with ID."
(:method
(_s method _id &rest _params)
(eglot--warn "Server tried to register unsupported capability `%s'"
method)))
(cl-defgeneric eglot-unregister-capability (server method id &rest params)
"Ask SERVER to register capability METHOD marked with ID."
(:method
(_s method _id &rest _params)
(eglot--warn "Server tried to unregister unsupported capability `%s'"
method)))
(cl-defgeneric eglot-client-capabilities (server)
"What the EGLOT LSP client supports for SERVER."
(:method (_s)
(list
:workspace (list
:applyEdit t
:executeCommand `(:dynamicRegistration :json-false)
:workspaceEdit `(:documentChanges :json-false)
:didChangeWatchedFiles `(:dynamicRegistration t)
:symbol `(:dynamicRegistration :json-false)
:configuration t)
:textDocument
(list
:synchronization (list
:dynamicRegistration :json-false
:willSave t :willSaveWaitUntil t :didSave t)
:completion (list :dynamicRegistration :json-false
:completionItem
`(:snippetSupport
,(if (eglot--snippet-expansion-fn)
t
:json-false))
:contextSupport t)
:hover (list :dynamicRegistration :json-false
:contentFormat
(if (fboundp 'gfm-view-mode)
["markdown" "plaintext"]
["plaintext"]))
:signatureHelp (list :dynamicRegistration :json-false
:signatureInformation
`(:parameterInformation
(:labelOffsetSupport t)))
:references `(:dynamicRegistration :json-false)
:definition `(:dynamicRegistration :json-false)
:declaration `(:dynamicRegistration :json-false)
:implementation `(:dynamicRegistration :json-false)
:typeDefinition `(:dynamicRegistration :json-false)
:documentSymbol (list
:dynamicRegistration :json-false
:hierarchicalDocumentSymbolSupport t
:symbolKind `(:valueSet
[,@(mapcar
#'car eglot--symbol-kind-names)]))
:documentHighlight `(:dynamicRegistration :json-false)
:codeAction (list
:dynamicRegistration :json-false
:codeActionLiteralSupport
'(:codeActionKind
(:valueSet
["quickfix"
"refactor" "refactor.extract"
"refactor.inline" "refactor.rewrite"
"source" "source.organizeImports"]))
:isPreferredSupport t)
:formatting `(:dynamicRegistration :json-false)
:rangeFormatting `(:dynamicRegistration :json-false)
:rename `(:dynamicRegistration :json-false)
:publishDiagnostics `(:relatedInformation :json-false))
:experimental eglot--{})))
(defclass eglot-lsp-server (jsonrpc-process-connection)
((project-nickname
:documentation "Short nickname for the associated project."
:accessor eglot--project-nickname
:reader eglot-project-nickname)
(major-mode
:documentation "Major mode symbol."
:accessor eglot--major-mode)
(capabilities
:documentation "JSON object containing server capabilities."
:accessor eglot--capabilities)
(server-info
:documentation "JSON object containing server info."
:accessor eglot--server-info)
(shutdown-requested
:documentation "Flag set when server is shutting down."
:accessor eglot--shutdown-requested)
(project
:documentation "Project associated with server."
:accessor eglot--project)
(spinner
:documentation "List (ID DOING-WHAT DONE-P) representing server progress."
:initform `(nil nil t) :accessor eglot--spinner)
(inhibit-autoreconnect
:initform t
:documentation "Generalized boolean inhibiting auto-reconnection if true."
:accessor eglot--inhibit-autoreconnect)
(file-watches
:documentation "Map ID to list of WATCHES for `didChangeWatchedFiles'."
:initform (make-hash-table :test #'equal) :accessor eglot--file-watches)
(managed-buffers
:documentation "List of buffers managed by server."
:accessor eglot--managed-buffers)
(saved-initargs
:documentation "Saved initargs for reconnection purposes."
:accessor eglot--saved-initargs)
(inferior-process
:documentation "Server subprocess started automatically."
:accessor eglot--inferior-process))
:documentation
"Represents a server. Wraps a process for LSP communication.")
;;; Process management
(defvar eglot--servers-by-project (make-hash-table :test #'equal)
"Keys are projects. Values are lists of processes.")
(defun eglot-shutdown (server &optional _interactive timeout preserve-buffers)
"Politely ask SERVER to quit.
Interactively, read SERVER from the minibuffer unless there is
only one and it's managing the current buffer.
Forcefully quit it if it doesn't respond within TIMEOUT seconds.
Don't leave this function with the server still running.
If PRESERVE-BUFFERS is non-nil (interactively, when called with a
prefix argument), do not kill events and output buffers of
SERVER. ."
(interactive (list (eglot--read-server "Shutdown which server"
(eglot-current-server))
t nil current-prefix-arg))
(eglot--message "Asking %s politely to terminate" (jsonrpc-name server))
(unwind-protect
(progn
(setf (eglot--shutdown-requested server) t)
(jsonrpc-request server :shutdown nil :timeout (or timeout 1.5))
(jsonrpc-notify server :exit nil))
;; Now ask jsonrpc.el to shut down the server.
(jsonrpc-shutdown server (not preserve-buffers))
(unless preserve-buffers (kill-buffer (jsonrpc-events-buffer server)))))
(defun eglot--on-shutdown (server)
"Called by jsonrpc.el when SERVER is already dead."
;; Turn off `eglot--managed-mode' where appropriate.
(dolist (buffer (eglot--managed-buffers server))
(let (;; Avoid duplicate shutdowns (github#389)
(eglot-autoshutdown nil))
(eglot--when-live-buffer buffer (eglot--managed-mode-off))))
;; Kill any expensive watches
(maphash (lambda (_id watches)
(mapcar #'file-notify-rm-watch watches))
(eglot--file-watches server))
;; Kill any autostarted inferior processes
(when-let (proc (eglot--inferior-process server))
(delete-process proc))
;; Sever the project/server relationship for `server'
(setf (gethash (eglot--project server) eglot--servers-by-project)
(delq server
(gethash (eglot--project server) eglot--servers-by-project)))
(cond ((eglot--shutdown-requested server)
t)
((not (eglot--inhibit-autoreconnect server))
(eglot--warn "Reconnecting after unexpected server exit.")
(eglot-reconnect server))
((timerp (eglot--inhibit-autoreconnect server))
(eglot--warn "Not auto-reconnecting, last one didn't last long."))))
(defun eglot--all-major-modes ()
"Return all known major modes."
(let ((retval))
(mapatoms (lambda (sym)
(when (plist-member (symbol-plist sym) 'derived-mode-parent)
(push sym retval))))
retval))
(defvar eglot--command-history nil
"History of CONTACT arguments to `eglot'.")
(defun eglot--guess-contact (&optional interactive)
"Helper for `eglot'.
Return (MANAGED-MODE PROJECT CLASS CONTACT). If INTERACTIVE is
non-nil, maybe prompt user, else error as soon as something can't
be guessed."
(let* ((guessed-mode (if buffer-file-name major-mode))
(managed-mode
(cond
((and interactive
(or (>= (prefix-numeric-value current-prefix-arg) 16)
(not guessed-mode)))
(intern
(completing-read
"[eglot] Start a server to manage buffers of what major mode? "
(mapcar #'symbol-name (eglot--all-major-modes)) nil t
(symbol-name guessed-mode) nil (symbol-name guessed-mode) nil)))
((not guessed-mode)
(eglot--error "Can't guess mode to manage for `%s'" (current-buffer)))
(t guessed-mode)))
(project (or (project-current) `(transient . ,default-directory)))
(guess (cdr (assoc managed-mode eglot-server-programs
(lambda (m1 m2)
(cl-find
m2 (if (listp m1) m1 (list m1))
:test #'provided-mode-derived-p)))))
(guess (if (functionp guess)
(funcall guess interactive)
guess))
(class (or (and (consp guess) (symbolp (car guess))
(prog1 (unless current-prefix-arg (car guess))
(setq guess (cdr guess))))
'eglot-lsp-server))
(program (and (listp guess)
(stringp (car guess))
;; A second element might be the port of a (host, port)
;; pair, but in that case it is not a string.
(or (null (cdr guess)) (stringp (cadr guess)))
(car guess)))
(base-prompt
(and interactive
"Enter program to execute (or <host>:<port>): "))
(program-guess
(and program
(combine-and-quote-strings (cl-subst ":autoport:"
:autoport guess))))
(prompt
(and base-prompt
(cond (current-prefix-arg base-prompt)
((null guess)
(format "[eglot] Sorry, couldn't guess for `%s'!\n%s"
managed-mode base-prompt))
((and program (not (executable-find program)))
(concat (format "[eglot] I guess you want to run `%s'"
program-guess)
(format ", but I can't find `%s' in PATH!" program)
"\n" base-prompt)))))
(contact
(or (and prompt
(let ((s (read-shell-command
prompt
program-guess
'eglot-command-history)))
(if (string-match "^\\([^\s\t]+\\):\\([[:digit:]]+\\)$"
(string-trim s))
(list (match-string 1 s)
(string-to-number (match-string 2 s)))
(cl-subst
:autoport ":autoport:" (split-string-and-unquote s)
:test #'equal))))
guess
(eglot--error "Couldn't guess for `%s'!" managed-mode))))
(list managed-mode project class contact)))
;;;###autoload
(defun eglot (managed-major-mode project class contact &optional interactive)
"Manage a project with a Language Server Protocol (LSP) server.
The LSP server of CLASS is started (or contacted) via CONTACT.
If this operation is successful, current *and future* file
buffers of MANAGED-MAJOR-MODE inside PROJECT become \"managed\"
by the LSP server, meaning information about their contents is
exchanged periodically to provide enhanced code-analysis via
`xref-find-definitions', `flymake-mode', `eldoc-mode',
`completion-at-point', among others.
Interactively, the command attempts to guess MANAGED-MAJOR-MODE
from current buffer, CLASS and CONTACT from
`eglot-server-programs' and PROJECT from `project-current'. If
it can't guess, the user is prompted. With a single
\\[universal-argument] prefix arg, it always prompt for COMMAND.
With two \\[universal-argument] prefix args, also prompts for
MANAGED-MAJOR-MODE.
PROJECT is a project instance as returned by `project-current'.
CLASS is a subclass of `eglot-lsp-server'.
CONTACT specifies how to contact the server. It is a
keyword-value plist used to initialize CLASS or a plain list as
described in `eglot-server-programs', which see.
INTERACTIVE is t if called interactively."
(interactive (append (eglot--guess-contact t) '(t)))
(let* ((current-server (eglot-current-server))
(live-p (and current-server (jsonrpc-running-p current-server))))
(if (and live-p
interactive
(y-or-n-p "[eglot] Live process found, reconnect instead? "))
(eglot-reconnect current-server interactive)
(when live-p (ignore-errors (eglot-shutdown current-server)))
(eglot--connect managed-major-mode project class contact))))
(defun eglot-reconnect (server &optional interactive)
"Reconnect to SERVER.
INTERACTIVE is t if called interactively."
(interactive (list (eglot--current-server-or-lose) t))
(when (jsonrpc-running-p server)
(ignore-errors (eglot-shutdown server interactive nil 'preserve-buffers)))
(eglot--connect (eglot--major-mode server)
(eglot--project server)
(eieio-object-class-name server)
(eglot--saved-initargs server))
(eglot--message "Reconnected!"))
(defvar eglot--managed-mode) ; forward decl
;;;###autoload
(defun eglot-ensure ()
"Start Eglot session for current buffer if there isn't one."
(let ((buffer (current-buffer)))
(cl-labels
((maybe-connect
()
(remove-hook 'post-command-hook #'maybe-connect nil)
(eglot--when-live-buffer buffer
(unless eglot--managed-mode
(apply #'eglot--connect (eglot--guess-contact))))))
(when buffer-file-name
(add-hook 'post-command-hook #'maybe-connect 'append nil)))))
(defun eglot-events-buffer (server)
"Display events buffer for SERVER.
Use current server's or first available Eglot events buffer."
(interactive (list (eglot-current-server)))
(let ((buffer (if server (jsonrpc-events-buffer server)
(cl-find "\\*EGLOT.*events\\*"
(buffer-list)
:key #'buffer-name :test #'string-match))))
(if buffer (display-buffer buffer)
(eglot--error "Can't find an Eglot events buffer!"))))
(defun eglot-stderr-buffer (server)
"Display stderr buffer for SERVER."
(interactive (list (eglot--current-server-or-lose)))
(display-buffer (jsonrpc-stderr-buffer server)))
(defun eglot-forget-pending-continuations (server)
"Forget pending requests for SERVER."
(interactive (list (eglot--current-server-or-lose)))
(jsonrpc-forget-pending-continuations server))
(defvar eglot-connect-hook
'(eglot-signal-didChangeConfiguration)
"Hook run after connecting in `eglot--connect'.")
(defvar eglot-server-initialized-hook
'()
"Hook run after a `eglot-lsp-server' instance is created.
That is before a connection was established. Use
`eglot-connect-hook' to hook into when a connection was
successfully established and the server on the other side has
received the initializing configuration.
Each function is passed the server as an argument")
(defun eglot--connect (managed-major-mode project class contact)
"Connect to MANAGED-MAJOR-MODE, PROJECT, CLASS and CONTACT.
This docstring appeases checkdoc, that's all."
(let* ((default-directory (project-root project))
(nickname (file-name-base (directory-file-name default-directory)))
(readable-name (format "EGLOT (%s/%s)" nickname managed-major-mode))
autostart-inferior-process
(contact (if (functionp contact) (funcall contact) contact))
(initargs
(cond ((keywordp (car contact)) contact)
((integerp (cadr contact))
`(:process ,(lambda ()
(apply #'open-network-stream
readable-name nil
(car contact) (cadr contact)
(cddr contact)))))
((and (stringp (car contact)) (memq :autoport contact))
`(:process ,(lambda ()
(pcase-let ((`(,connection . ,inferior)
(eglot--inferior-bootstrap
readable-name
contact)))
(setq autostart-inferior-process inferior)
connection))))
((stringp (car contact))
`(:process
,(lambda ()
(let ((default-directory default-directory))
(make-process
:name readable-name
:command contact
:connection-type 'pipe
:coding 'utf-8-emacs-unix
:noquery t
:stderr (get-buffer-create
(format "*%s stderr*" readable-name)))))))))
(spread (lambda (fn) (lambda (server method params)
(apply fn server method (append params nil)))))
(server
(apply
#'make-instance class
:name readable-name
:events-buffer-scrollback-size eglot-events-buffer-size
:notification-dispatcher (funcall spread #'eglot-handle-notification)
:request-dispatcher (funcall spread #'eglot-handle-request)
:on-shutdown #'eglot--on-shutdown
initargs))
(cancelled nil)
(tag (make-symbol "connected-catch-tag")))
(setf (eglot--saved-initargs server) initargs)
(setf (eglot--project server) project)
(setf (eglot--project-nickname server) nickname)
(setf (eglot--major-mode server) managed-major-mode)
(setf (eglot--inferior-process server) autostart-inferior-process)
(run-hook-with-args 'eglot-server-initialized-hook server)
;; Now start the handshake. To honour `eglot-sync-connect'
;; maybe-sync-maybe-async semantics we use `jsonrpc-async-request'
;; and mimic most of `jsonrpc-request'.
(unwind-protect
(condition-case _quit
(let ((retval
(catch tag
(jsonrpc-async-request
server
:initialize
(list :processId (unless (eq (jsonrpc-process-type server)
'network)
(emacs-pid))
:rootPath (expand-file-name default-directory)
:rootUri (eglot--path-to-uri default-directory)
:initializationOptions (eglot-initialization-options
server)
:capabilities (eglot-client-capabilities server))
:success-fn
(eglot--lambda ((InitializeResult) capabilities serverInfo)
(unless cancelled
(push server
(gethash project eglot--servers-by-project))
(setf (eglot--capabilities server) capabilities)
(setf (eglot--server-info server) serverInfo)
(jsonrpc-notify server :initialized eglot--{})
(dolist (buffer (buffer-list))
(with-current-buffer buffer
;; No need to pass SERVER as an argument: it has
;; been registered in `eglot--servers-by-project',
;; so that it can be found (and cached) from
;; `eglot--maybe-activate-editing-mode' in any
;; managed buffer.
(eglot--maybe-activate-editing-mode)))
(setf (eglot--inhibit-autoreconnect server)
(cond
((booleanp eglot-autoreconnect)
(not eglot-autoreconnect))
((cl-plusp eglot-autoreconnect)
(run-with-timer
eglot-autoreconnect nil
(lambda ()
(setf (eglot--inhibit-autoreconnect server)
(null eglot-autoreconnect)))))))
(let ((default-directory (project-root project))
(major-mode managed-major-mode))
(hack-dir-local-variables-non-file-buffer)
(run-hook-with-args 'eglot-connect-hook server))
(eglot--message
"Connected! Server `%s' now managing `%s' buffers \
in project `%s'."
(or (plist-get serverInfo :name)
(jsonrpc-name server))
managed-major-mode
(eglot-project-nickname server))
(when tag (throw tag t))))
:timeout eglot-connect-timeout
:error-fn (eglot--lambda ((ResponseError) code message)
(unless cancelled
(jsonrpc-shutdown server)
(let ((msg (format "%s: %s" code message)))
(if tag (throw tag `(error . ,msg))
(eglot--error msg)))))
:timeout-fn (lambda ()