forked from joaotavora/eglot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
eglot.el
3179 lines (2903 loc) · 145 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-2022 Free Software Foundation, Inc.
;; Version: 1.8
;; Author: João Távora <[email protected]>
;; Maintainer: João Távora <[email protected]>
;; URL: https://github.com/joaotavora/eglot
;; Keywords: convenience, languages
;; Package-Requires: ((emacs "26.1") (jsonrpc "1.0.14") (flymake "1.2.1") (project "0.3.0") (xref "1.0.1") (eldoc "1.11.0") (seq "2.23"))
;; This file is part of GNU Emacs.
;; GNU Emacs 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.
;; GNU Emacs 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 GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;; Eglot ("Emacs Polyglot") is an Emacs LSP client that stays out of
;; your way.
;;
;; Typing 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 minibuffer for these things. Actually, the
;; server does not need to be running locally: you can connect to a
;; running server via TCP by entering a <host:port> syntax.
;;
;; If the connection is successful, you should see an `eglot'
;; indicator pop up in your mode-line. More importantly, this means
;; that current *and future* file buffers of that major mode *inside
;; your current project* automatically become \"managed\" by the LSP
;; server. In other words, information about their content is
;; exchanged periodically to provide enhanced code analysis using
;; `xref-find-definitions', `flymake-mode', `eldoc-mode',
;; `completion-at-point', among others.
;;
;; To "unmanage" these buffers, shutdown the server with
;; M-x eglot-shutdown.
;;
;; To start an eglot session automatically when a foo-mode buffer is
;; visited, you can put this in your init file:
;;
;; (add-hook 'foo-mode-hook 'eglot-ensure)
;;; 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))
;; Similar issue as above for Emacs 26.3 and seq.el.
(if (< emacs-major-version 27)
(load "seq")
(require 'seq))
;; 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)
(defun eglot-alternatives (alternatives)
"Compute server-choosing function for `eglot-server-programs'.
Each element of ALTERNATIVES is a string PROGRAM or a list of
strings (PROGRAM ARGS...) where program names an LSP server
program to start with ARGS. Returns a function of one argument.
When invoked, that function will return a list (ABSPATH ARGS),
where ABSPATH is the absolute path of the PROGRAM that was
chosen (interactively or automatically)."
(lambda (&optional interactive)
;; JT@2021-06-13: This function is way more complicated than it
;; could be because it accounts for the fact that
;; `eglot--executable-find' may take much longer to execute on
;; remote files.
(let* ((listified (cl-loop for a in alternatives
collect (if (listp a) a (list a))))
(err (lambda ()
(error "None of '%s' are valid executables"
(mapconcat #'car listified ", ")))))
(cond (interactive
(let* ((augmented (mapcar (lambda (a)
(let ((found (eglot--executable-find
(car a) t)))
(and found
(cons (car a) (cons found (cdr a))))))
listified))
(available (remove nil augmented)))
(cond ((cdr available)
(cdr (assoc
(completing-read
"[eglot] More than one server executable available:"
(mapcar #'car available)
nil t nil nil (car (car available)))
available #'equal)))
((cdr (car available)))
(t
;; Don't error when used interactively, let the
;; Eglot prompt the user for alternative (github#719)
nil))))
(t
(cl-loop for (p . args) in listified
for probe = (eglot--executable-find p t)
when probe return (cons probe args)
finally (funcall err)))))))
(defvar eglot-server-programs `((rust-mode . ,(eglot-alternatives '("rust-analyzer" "rls")))
(cmake-mode . ("cmake-language-server"))
(vimrc-mode . ("vim-language-server" "--stdio"))
(python-mode
. ,(eglot-alternatives
'("pylsp" "pyls" ("pyright-langserver" "--stdio"))))
((js-mode typescript-mode)
. ("typescript-language-server" "--stdio"))
(sh-mode . ("bash-language-server" "start"))
((php-mode phps-mode)
. ("php" "vendor/felixfbecker/\
language-server/bin/php-language-server.php"))
((c++-mode c-mode) . ,(eglot-alternatives
'("clangd" "ccls")))
(((caml-mode :language-id "ocaml")
(tuareg-mode :language-id "ocaml") reason-mode)
. ("ocamllsp"))
(ruby-mode
. ("solargraph" "socket" "--port" :autoport))
(haskell-mode
. ("haskell-language-server-wrapper" "--lsp"))
(elm-mode . ("elm-language-server"))
(mint-mode . ("mint" "ls"))
(kotlin-mode . ("kotlin-language-server"))
(go-mode . ("gopls"))
((R-mode ess-r-mode) . ("R" "--slave" "-e"
"languageserver::run()"))
(java-mode . ("jdtls"))
(dart-mode . ("dart" "language-server"
"--client-id" "emacs.eglot-dart"))
(elixir-mode . ("language_server.sh"))
(ada-mode . ("ada_language_server"))
(scala-mode . ("metals-emacs"))
(racket-mode . ("racket" "-l" "racket-langserver"))
((tex-mode context-mode texinfo-mode bibtex-mode)
. ("digestif"))
(erlang-mode . ("erlang_ls" "--transport" "stdio"))
(yaml-mode . ("yaml-language-server" "--stdio"))
(nix-mode . ("rnix-lsp"))
(gdscript-mode . ("localhost" 6008))
((fortran-mode f90-mode) . ("fortls"))
(futhark-mode . ("futhark" "lsp"))
(lua-mode . ("lua-lsp"))
(zig-mode . ("zls"))
(css-mode . ,(eglot-alternatives '(("vscode-css-language-server" "--stdio") ("css-languageserver" "--stdio"))))
(html-mode . ,(eglot-alternatives '(("vscode-html-language-server" "--stdio") ("html-languageserver" "--stdio"))))
(json-mode . ,(eglot-alternatives '(("vscode-json-language-server" "--stdio") ("json-languageserver" "--stdio"))))
(dockerfile-mode . ("docker-langserver" "--stdio"))
(clojure-mode . ("clojure-lsp"))
(csharp-mode . ("omnisharp" "-lsp"))
(purescript-mode . ("purescript-language-server" "--stdio")))
"How the command `eglot' guesses the server to start.
An association list of (MAJOR-MODE . CONTACT) pairs. MAJOR-MODE
identifies the buffers that are to be managed by a specific
language server. The associated CONTACT specifies how to connect
to a server for those buffers.
MAJOR-MODE can be:
* In the most common case, a symbol such as `c-mode';
* A list (MAJOR-MODE-SYMBOL :LANGUAGE-ID ID) where
MAJOR-MODE-SYMBOL is the aforementioned symbol and ID is a
string identifying the language to the server;
* A list combining the previous two alternatives, meaning
multiple major modes will be associated with a single server
program.
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 (PROGRAM [ARGS...] :initializationOptions OPTIONS),
whereupon PROGRAM is called with ARGS as in the first option,
and the LSP \"initializationOptions\" JSON object is
constructed from OPTIONS. If OPTIONS is a unary function, it
is called with the server instance and should return a JSON
object.
* 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 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.")
(defface eglot-diagnostic-tag-unnecessary-face
'((t (:inherit shadow)))
"Face used to render unused or unnecessary code.")
(defface eglot-diagnostic-tag-deprecated-face
'((t . (:inherit shadow :strike-through t)))
"Face used to render deprecated or obsolete code.")
(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)))
(defcustom eglot-extend-to-xref nil
"If non-nil, activate Eglot in cross-referenced non-project files."
:type 'boolean)
(defcustom eglot-menu-string "eglot"
"String displayed in mode line when Eglot is active."
:type 'string)
(defvar eglot-withhold-process-id nil
"If non-nil, Eglot will not send the Emacs process id to the language server.
This can be useful when using docker to run a language server.")
;; Customizable via `completion-category-overrides'.
(when (assoc 'flex completion-styles-alist)
(add-to-list 'completion-category-defaults '(eglot (styles flex basic))))
;;; 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") (19 . "Folder") (20 . "EnumMember")
(21 . "Constant") (22 . "Struct") (23 . "Event") (24 . "Operator")
(25 . "TypeParameter")))
(defconst eglot--tag-faces
`((1 . eglot-diagnostic-tag-unnecessary-face)
(2 . eglot-diagnostic-tag-deprecated-face)))
(defconst eglot--{} (make-hash-table) "The empty JSON object.")
(defun eglot--executable-find (command &optional remote)
"Like Emacs 27's `executable-find', ignore REMOTE on Emacs 26."
(if (>= emacs-major-version 27) (executable-find command remote)
(executable-find command)))
;;; 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 :tags))
(Diagnostic (:range :message) (:severity :code :source :relatedInformation :codeDescription :tags))
(DocumentHighlight (:range) (:kind))
(FileSystemWatcher (:globPattern) (:kind))
(Hover (:contents) (:range))
(InitializeResult (:capabilities) (:serverInfo))
(Location (:uri :range))
(LocationLink (:targetUri :targetRange :targetSelectionRange) (:originSelectionRange))
(LogMessageParams (:type :message))
(MarkupContent (:kind :value))
(ParameterInformation (:label) (:documentation))
(Position (:line :character))
(Range (:start :end))
(Registration (:id :method) (:registerOptions))
(ResponseError (:code :message) (:data))
(ShowMessageParams (:type :message))
(ShowMessageRequestParams (:type :message) (:actions))
(SignatureHelp (:signatures) (:activeSignature :activeParameter))
(SignatureInformation (:label) (:documentation :parameters :activeParameter))
(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."))
(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)
(let ((probe (plist-get (eglot--saved-initargs s) :initializationOptions)))
(cond ((functionp probe) (funcall probe s))
(probe)
(t eglot--{})))))
(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 t)
:didChangeWatchedFiles
`(:dynamicRegistration
,(if (eglot--trampish-p s) :json-false t))
:symbol `(:dynamicRegistration :json-false)
:configuration t
:workspaceFolders 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)
:deprecatedSupport t
:tagSupport (:valueSet [1]))
: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)
:activeParameterSupport t))
:references `(:dynamicRegistration :json-false)
:definition (list :dynamicRegistration :json-false
:linkSupport t)
:declaration (list :dynamicRegistration :json-false
:linkSupport t)
:implementation (list :dynamicRegistration :json-false
:linkSupport t)
:typeDefinition (list :dynamicRegistration :json-false
:linkSupport t)
: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 (list :relatedInformation :json-false
;; TODO: We can support :codeDescription after
;; adding an appropriate UI to
;; Flymake.
:codeDescriptionSupport :json-false
:tagSupport
`(:valueSet
[,@(mapcar
#'car eglot--tag-faces)])))
:experimental eglot--{})))
(cl-defgeneric eglot-workspace-folders (server)
"Return workspaceFolders for SERVER."
(let ((project (eglot--project server)))
(vconcat
(mapcar (lambda (dir)
(list :uri (eglot--path-to-uri dir)
:name (abbreviate-file-name dir)))
`(,(project-root project) ,@(project-external-roots project))))))
(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)
(language-id
:documentation "Language ID string for the mode."
:accessor eglot--language-id)
(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.
TIMEOUT defaults to 1.5 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-shutdown-all (&optional preserve-buffers)
"Politely ask all language servers to quit, in order.
PRESERVE-BUFFERS as in `eglot-shutdown', which see."
(interactive (list current-prefix-arg))
(cl-loop for ss being the hash-values of eglot--servers-by-project
do (cl-loop for s in ss do (eglot-shutdown s nil preserve-buffers))))
(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--lookup-mode (mode)
"Lookup `eglot-server-programs' for MODE.
Return (LANGUAGE-ID . CONTACT-PROXY). If not specified,
LANGUAGE-ID is determined from MODE."
(cl-loop
for (modes . contact) in eglot-server-programs
thereis (cl-some
(lambda (spec)
(cl-destructuring-bind (probe &key language-id &allow-other-keys)
(if (consp spec) spec (list spec))
(and (provided-mode-derived-p mode probe)
(cons
(or language-id
(or (get mode 'eglot-language-id)
(get spec 'eglot-language-id)
(string-remove-suffix "-mode" (symbol-name mode))))
contact))))
(if (or (symbolp modes) (keywordp (cadr modes)))
(list modes) modes))))
(defun eglot--guess-contact (&optional interactive)
"Helper for `eglot'.
Return (MANAGED-MODE PROJECT CLASS CONTACT LANG-ID). 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)))
(lang-id-and-guess (eglot--lookup-mode guessed-mode))
(language-id (or (car lang-id-and-guess)
(string-remove-suffix "-mode" (symbol-name guessed-mode))))
(guess (cdr lang-id-and-guess))
(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 (file-name-absolute-p program))
(not (eglot--executable-find program t)))
(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 (eglot--current-project) class contact language-id)))
(defvar eglot-lsp-context)
(put 'eglot-lsp-context 'variable-documentation
"Dynamically non-nil when searching for projects in LSP context.")
(defvar eglot--servers-by-xrefed-file
(make-hash-table :test 'equal :weakness 'value))
(defun eglot--current-project ()
"Return a project object for Eglot's LSP purposes.
This relies on `project-current' and thus on
`project-find-functions'. Functions in the latter
variable (which see) can query the value `eglot-lsp-context' to
decide whether a given directory is a project containing a
suitable root directory for a given LSP server's purposes."
(let ((eglot-lsp-context t))
(or (project-current) `(transient . ,default-directory))))
;;;###autoload
(defun eglot (managed-major-mode project class contact language-id
&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-find-functions'. The search for active projects in this
context binds `eglot-lsp-context' (which see).
If it can't guess, the user is prompted. With a single
\\[universal-argument] prefix arg, it always prompt for COMMAND.