-
Notifications
You must be signed in to change notification settings - Fork 200
/
eglot.el
4028 lines (3680 loc) · 186 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 --- The Emacs Client for LSP servers -*- lexical-binding: t; -*-
;; Copyright (C) 2018-2023 Free Software Foundation, Inc.
;; Version: 1.16
;; 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.3") (jsonrpc "1.0.23") (flymake "1.2.1") (project "0.9.8") (xref "1.6.2") (eldoc "1.14.0") (seq "2.23") (external-completion "0.1"))
;; This is a GNU ELPA :core package. Avoid adding functionality
;; that is not available in the version of Emacs recorded above or any
;; of the package dependencies.
;; 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 in some source file is often enough to get you
;; started, if the language server you're looking to use is installed
;; in your system. Please refer to the manual, available from
;; https://joaotavora.github.io/eglot/ or from M-x info for more usage
;; instructions.
;;
;; If you wish to contribute changes to Eglot, please do read the user
;; manual first. Additionally, take the following in consideration:
;; * Eglot's main job is to hook up the information that language
;; servers offer via LSP to Emacs's UI facilities: Xref for
;; definition-chasing, Flymake for diagnostics, Eldoc for at-point
;; documentation, etc. Eglot's job is generally *not* to provide
;; such a UI itself, though a small number of simple
;; counter-examples do exist, e.g. in the `eglot-rename' command or
;; the `eglot-inlay-hints-mode' minor mode. When a new UI is
;; evidently needed, consider adding a new package to Emacs, or
;; extending an existing one.
;;
;; * Eglot was designed to function with just the UI facilities found
;; in the latest Emacs core, as long as those facilities are also
;; available as GNU ELPA :core packages. Historically, a number of
;; :core packages were added or reworked in Emacs to make this
;; possible. This principle should be upheld when adding new LSP
;; features or tweaking existing ones. Design any new facilities in
;; a way that they could work in the absence of LSP or using some
;; different protocol, then make sure Eglot can link up LSP
;; information to it.
;; * There are few Eglot configuration variables. This principle
;; should also be upheld. If Eglot had these variables, it could be
;; duplicating configuration found elsewhere, bloating itself up,
;; and making it generally hard to integrate with the ever growing
;; set of LSP features and Emacs packages. For instance, this is
;; why one finds a single variable
;; `eglot-ignored-server-capabilities' instead of a number of
;; capability-specific flags, or why customizing the display of
;; LSP-provided documentation is done via ElDoc's variables, not
;; Eglot's.
;;
;; * Linking up LSP information to other libraries is generally done
;; in the `eglot--managed-mode' minor mode function, by
;; buffer-locally setting the other library's variables to
;; Eglot-specific versions. When deciding what to set the variable
;; to, the general idea is to choose a good default for beginners
;; that doesn't clash with Emacs's defaults. The settings are only
;; in place during Eglot's LSP-enriched tenure over a project. Even
;; so, some of those decisions will invariably aggravate a minority
;; of Emacs power users, but these users can use `eglot-stay-out-of'
;; and `eglot-managed-mode-hook' to adjust things to their
;; preferences.
;;
;; * On occasion, to enable new features, Eglot can have soft
;; dependencies on popular libraries that are not in Emacs core.
;; "Soft" means that the dependency doesn't impair any other use of
;; Eglot beyond that feature. Such is the case of the snippet
;; functionality, via the Yasnippet package, Markdown formatting of
;; at-point documentation via the markdown-mode package, and nicer
;; looking completions when the Company package is used.
;;; Code:
(require 'imenu)
(require 'cl-lib)
(require 'url-parse)
(require 'url-util)
(require 'pcase)
(require 'compile) ; for some faces
(require 'warnings)
(eval-when-compile
(require 'subr-x))
(require 'filenotify)
(require 'ert)
(require 'text-property-search nil t)
(require 'diff-mode)
(require 'diff)
;; These dependencies are also GNU ELPA core packages. Because of
;; bug#62576, since there is a risk that M-x package-install, despite
;; having installed them, didn't correctly re-load them over the
;; built-in versions.
(eval-and-compile
(load "project")
(load "eldoc")
(load "seq")
(load "flymake")
(load "xref")
(load "jsonrpc")
(load "external-completion"))
;; 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)
(defvar tramp-ssh-controlmaster-options)
(defvar tramp-use-ssh-controlmaster-options)
;;; Obsolete aliases
;;;
(make-obsolete-variable 'eglot--managed-mode-hook
'eglot-managed-mode-hook "1.6")
(define-obsolete-variable-alias 'eglot-confirm-server-initiated-edits
'eglot-confirm-server-edits "1.16")
(make-obsolete-variable 'eglot-events-buffer-size
'eglot-events-buffer-config "1.16")
(define-obsolete-function-alias 'eglot--uri-to-path 'eglot-uri-to-path "1.16")
(define-obsolete-function-alias 'eglot--path-to-uri 'eglot-path-to-uri "1.16")
(define-obsolete-function-alias 'eglot--range-region 'eglot-range-region "1.16")
(define-obsolete-function-alias 'eglot--server-capable 'eglot-server-capable "1.16")
(define-obsolete-function-alias 'eglot--server-capable-or-lose 'eglot-server-capable-or-lose "1.16")
(define-obsolete-function-alias
'eglot-lsp-abiding-column 'eglot-utf-16-linepos "1.12")
(define-obsolete-function-alias
'eglot-current-column 'eglot-utf-32-linepos "1.12")
(define-obsolete-variable-alias
'eglot-current-column-function 'eglot-current-linepos-function "1.12")
(define-obsolete-function-alias
'eglot-move-to-current-column 'eglot-move-to-utf-32-linepos "1.12")
(define-obsolete-function-alias
'eglot-move-to-lsp-abiding-column 'eglot-move-to-utf-16-linepos "1.12")
(define-obsolete-variable-alias
'eglot-move-to-column-function 'eglot-move-to-linepos-function "1.12")
(define-obsolete-variable-alias 'eglot-ignored-server-capabilites
'eglot-ignored-server-capabilities "1.8")
;;;###autoload
(define-obsolete-function-alias 'eglot-update 'eglot-upgrade-eglot "29.1")
;;; 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 to be invoked
automatically by Eglot on startup. 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 _project)
;; 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 ((and interactive current-prefix-arg)
;; A C-u always lets user input something manually,
nil)
(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-ts-mode rust-mode) . ("rust-analyzer"))
((cmake-mode cmake-ts-mode) . ("cmake-language-server"))
(vimrc-mode . ("vim-language-server" "--stdio"))
((python-mode python-ts-mode)
. ,(eglot-alternatives
'("pylsp" "pyls" ("pyright-langserver" "--stdio") "jedi-language-server" "ruff-lsp")))
((js-json-mode json-mode json-ts-mode)
. ,(eglot-alternatives '(("vscode-json-language-server" "--stdio")
("vscode-json-languageserver" "--stdio")
("json-languageserver" "--stdio"))))
(((js-mode :language-id "javascript")
(js-ts-mode :language-id "javascript")
(tsx-ts-mode :language-id "typescriptreact")
(typescript-ts-mode :language-id "typescript")
(typescript-mode :language-id "typescript"))
. ("typescript-language-server" "--stdio"))
((bash-ts-mode sh-mode) . ("bash-language-server" "start"))
((php-mode phps-mode)
. ,(eglot-alternatives
'(("phpactor" "language-server")
("php" "vendor/felixfbecker/language-server/bin/php-language-server.php"))))
((c-mode c-ts-mode c++-mode c++-ts-mode objc-mode)
. ,(eglot-alternatives
'("clangd" "ccls")))
(((caml-mode :language-id "ocaml")
(tuareg-mode :language-id "ocaml") reason-mode)
. ("ocamllsp"))
((ruby-mode ruby-ts-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 go-dot-mod-mode go-dot-work-mode go-ts-mode go-mod-ts-mode)
. ("gopls"))
((R-mode ess-r-mode) . ("R" "--slave" "-e"
"languageserver::run()"))
((java-mode java-ts-mode) . ("jdtls"))
((dart-mode dart-ts-mode)
. ("dart" "language-server"
"--client-id" "emacs.eglot-dart"))
((elixir-mode elixir-ts-mode heex-ts-mode)
. ,(if (and (fboundp 'w32-shell-dos-semantics)
(w32-shell-dos-semantics))
'("language_server.bat")
(eglot-alternatives
'("language_server.sh" "start_lexical.sh"))))
(ada-mode . ("ada_language_server"))
(scala-mode . ,(eglot-alternatives
'("metals" "metals-emacs")))
(racket-mode . ("racket" "-l" "racket-langserver"))
((tex-mode context-mode texinfo-mode bibtex-mode)
. ,(eglot-alternatives '("digestif" "texlab")))
(erlang-mode . ("erlang_ls" "--transport" "stdio"))
((yaml-ts-mode yaml-mode) . ("yaml-language-server" "--stdio"))
(nix-mode . ,(eglot-alternatives '("nil" "rnix-lsp" "nixd")))
(nickel-mode . ("nls"))
(gdscript-mode . ("localhost" 6008))
((fortran-mode f90-mode) . ("fortls"))
(futhark-mode . ("futhark" "lsp"))
((lua-mode lua-ts-mode) . ,(eglot-alternatives
'("lua-language-server" "lua-lsp")))
(zig-mode . ("zls"))
((css-mode css-ts-mode)
. ,(eglot-alternatives '(("vscode-css-language-server" "--stdio")
("css-languageserver" "--stdio"))))
(html-mode . ,(eglot-alternatives '(("vscode-html-language-server" "--stdio") ("html-languageserver" "--stdio"))))
((dockerfile-mode dockerfile-ts-mode) . ("docker-langserver" "--stdio"))
((clojure-mode clojurescript-mode clojurec-mode clojure-ts-mode)
. ("clojure-lsp"))
((csharp-mode csharp-ts-mode)
. ,(eglot-alternatives
'(("omnisharp" "-lsp")
("csharp-ls"))))
(purescript-mode . ("purescript-language-server" "--stdio"))
((perl-mode cperl-mode) . ("perl" "-MPerl::LanguageServer" "-e" "Perl::LanguageServer::run"))
(markdown-mode
. ,(eglot-alternatives
'(("marksman" "server")
("vscode-markdown-language-server" "--stdio"))))
(graphviz-dot-mode . ("dot-language-server" "--stdio"))
(terraform-mode . ("terraform-ls" "serve"))
((uiua-ts-mode uiua-mode) . ("uiua" "lsp")))
"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. This association is such that the same resulting
server process will manage buffers of different major 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 (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 two arguments (INTERACTIVE PROJECT) producing any
of the above values for CONTACT. INTERACTIVE will be t if an
interactive `M-x eglot' was used, and nil otherwise (e.g. from
`eglot-ensure'). Interactive calls may ask the user for hints
on finding the required programs, etc. PROJECT is whatever
project Eglot discovered via `project-find-functions' (which
see). The function should return nil or signal an error if it
can't produce a valid CONTACT. The helper function
`eglot-alternatives' (which see) can be used to produce a
function that offers more than one server for a given
MAJOR-MODE.")
(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 (const :tag "Reconnect automatically" t)
(const :tag "Never reconnect" nil)
(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 '(choice (number :tag "Number of seconds")
(const :tag "Never time out" nil)))
(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 (const :tag "Block for `eglot-connect-timeout' seconds" t)
(const :tag "Never block" nil)
(integer :tag "Number of seconds to block")))
(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-config
(list :size (or (bound-and-true-p eglot-events-buffer-size) 2000000)
:format 'full)
"Configure the Eglot events buffer.
Value is a plist accepting the keys `:size', which controls the
size in characters of the buffer (0 disables, nil means
infinite), and `:format', which controls the shape of each log
entry (`full' includes the original JSON, `lisp' uses
pretty-printed Lisp).
For changes on this variable to take effect, you need to restart
the LSP connection. That can be done by `eglot-reconnect'."
:type '(plist :key-type (symbol :tag "Keyword")
:options (((const :tag "Size" :size)
(choice
(const :tag "No limit" nil)
(integer :tag "Number of characters")))
((const :tag "Format" :format)
(choice
(const :tag "Full with original JSON" full)
(const :tag "Shortened" short)
(const :tag "Pretty-printed lisp" lisp))))))
(defcustom eglot-confirm-server-edits '((eglot-rename . nil)
(t . maybe-summary))
"Control if changes proposed by LSP should be confirmed with user.
If this variable's value is the symbol `diff', a diff buffer is
pops up, allowing the user to apply each change individually. If
the symbol `summary' or any other non-nil value, the user is
prompted in the minibuffer with aa short summary of changes. The
symbols `maybe-diff' and `maybe-summary' mean that the
confirmation is offered to the user only if the changes target
files visited in buffers. Finally, a nil value means all changes
are applied directly without any confirmation.
If this variable's value can also be an alist ((COMMAND . ACTION)
...) where COMMAND is a symbol designating a command, such as
`eglot-rename', `eglot-code-actions',
`eglot-code-action-quickfix', etc. ACTION is one of the symbols
described above. The value `t' for COMMAND is accepted and its
ACTION is the default value for commands not in the alist."
:type (let ((basic-choices
'((const :tag "Use diff" diff)
(const :tag "Summarize and prompt" summary)
(const :tag "Maybe use diff" maybe-diff)
(const :tag "Maybe summarize and prompt" maybe-summary)
(const :tag "Don't confirm" nil))))
`(choice ,@basic-choices
(alist :tag "Per-command alist"
:key-type (choice (function :tag "Command")
(const :tag "Default" t))
:value-type (choice . ,basic-choices)))))
(defcustom eglot-extend-to-xref nil
"If non-nil, activate Eglot in cross-referenced non-project files."
:type 'boolean)
(defcustom eglot-prefer-plaintext nil
"If non-nil, always request plaintext responses to hover requests."
:type 'boolean)
(defcustom eglot-menu-string "eglot"
"String displayed in mode line when Eglot is active."
:type 'string)
(defcustom eglot-report-progress t
"If non-nil, show progress of long running LSP server work.
If set to `messages', use *Messages* buffer, else use Eglot's
mode line indicator."
:type '(choice (const :tag "Don't show progress" nil)
(const :tag "Show progress in *Messages*" messages)
(const :tag "Show progress in Eglot's mode line indicator" t))
:version "1.10")
(defcustom eglot-ignored-server-capabilities (list)
"LSP server capabilities that Eglot could use, but won't.
You could add, for instance, the symbol
`:documentHighlightProvider' to prevent automatic highlighting
under cursor."
:type '(set
:tag "Tick the ones you're not interested in"
(const :tag "Documentation on hover" :hoverProvider)
(const :tag "Code completion" :completionProvider)
(const :tag "Function signature help" :signatureHelpProvider)
(const :tag "Go to definition" :definitionProvider)
(const :tag "Go to type definition" :typeDefinitionProvider)
(const :tag "Go to implementation" :implementationProvider)
(const :tag "Go to declaration" :declarationProvider)
(const :tag "Find references" :referencesProvider)
(const :tag "Highlight symbols automatically" :documentHighlightProvider)
(const :tag "List symbols in buffer" :documentSymbolProvider)
(const :tag "List symbols in workspace" :workspaceSymbolProvider)
(const :tag "Execute code actions" :codeActionProvider)
(const :tag "Code lens" :codeLensProvider)
(const :tag "Format buffer" :documentFormattingProvider)
(const :tag "Format portion of buffer" :documentRangeFormattingProvider)
(const :tag "On-type formatting" :documentOnTypeFormattingProvider)
(const :tag "Rename symbol" :renameProvider)
(const :tag "Highlight links in document" :documentLinkProvider)
(const :tag "Decorate color references" :colorProvider)
(const :tag "Fold regions of buffer" :foldingRangeProvider)
(const :tag "Execute custom commands" :executeCommandProvider)
(const :tag "Inlay hints" :inlayHintProvider)))
(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.")
;;; Constants
;;;
(defconst eglot--version
(eval-when-compile
(when byte-compile-current-file
(require 'lisp-mnt)
(lm-version byte-compile-current-file)))
"The version as a string of this version of Eglot.
It is nil if Eglot is not byte-complied.")
(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)))
(defvaralias 'eglot-{} 'eglot--{})
(defconst eglot--{} (make-hash-table :size 1) "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)))
(defun eglot--accepted-formats ()
(if (and (not eglot-prefer-plaintext) (fboundp 'gfm-view-mode))
["markdown" "plaintext"] ["plaintext"]))
(defconst eglot--uri-path-allowed-chars
(let ((vec (copy-sequence url-path-allowed-chars)))
(aset vec ?: nil) ;; see github#639
vec)
"Like `url-path-allows-chars' but more restrictive.")
;;; Message verification helpers
;;;
(eval-and-compile
(defvar eglot--lsp-interface-alist
`(
(CodeAction (:title) (:kind :diagnostics :edit :command :isPreferred :data))
(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)
(:detail :deprecated :children))
(TextDocumentEdit (:textDocument :edits) ())
(TextEdit (:range :newText))
(VersionedTextDocumentIdentifier (:uri :version) ())
(WorkDoneProgress (:kind) (:title :message :percentage :cancellable))
(WorkspaceEdit () (:changes :documentChanges))
(WorkspaceSymbol (:name :kind) (:containerName :location :data))
(InlayHint (:position :label) (:kind :textEdits :tooltip :paddingLeft
:paddingRight :data))
(InlayHintLabelPart (:value) (:tooltip :location :command)))
"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
'(;; Uncomment next lines for fun and debugging
;; disallow-non-standard-keys
;; enforce-required-keys
;; enforce-optional-keys
no-unknown-interfaces)
"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.
If the symbol `no-unknown-interfaces' is present, Eglot warns at
compile time if an undeclared LSP interface is used."))
(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))))
((memq 'no-unknown-interfaces eglot-strict-mode)
(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...)
Honor `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.
Honor `eglot-strict-mode'."
(declare (indent 1) (debug (sexp &rest form)))
(let ((e (cl-gensym "jsonrpc-lambda-elem")))
`(lambda (,e) (cl-block nil (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)))))))
(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)))
;;; Public Elisp API
;;;
(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 (_ _ _)
(declare (obsolete eglot-execute "30.1"))
(:method
(server command arguments)
(eglot--request server :workspace/executeCommand
`(:command ,(format "%s" command) :arguments ,arguments))))
(cl-defgeneric eglot-execute (server action)
"Ask SERVER to execute ACTION.
ACTION is an LSP object of either `CodeAction' or `Command' type."
(:method
(server action) "Default implementation."
(eglot--dcase action
(((Command)) (eglot--request server :workspace/executeCommand action))
(((CodeAction) edit command data)
(if (and (null edit) (null command) data
(eglot-server-capable :codeActionProvider :resolveProvider))
(eglot-execute server (eglot--request server :codeAction/resolve action))
(when edit (eglot--apply-workspace-edit edit this-command))
(when command (eglot--request server :workspace/executeCommand command)))))))
(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 (and
(not (eglot--stay-out-of-p 'yasnippet))
(eglot--snippet-expansion-fn))
t
:json-false)
:deprecatedSupport t
:resolveSupport (:properties
["documentation"
"details"
"additionalTextEdits"])
:tagSupport (:valueSet [1]))
:contextSupport t)
:hover (list :dynamicRegistration :json-false
:contentFormat (eglot--accepted-formats))
:signatureHelp (list :dynamicRegistration :json-false
:signatureInformation
`(:parameterInformation
(:labelOffsetSupport t)
:documentationFormat ,(eglot--accepted-formats)
: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
:resolveSupport `(:properties ["edit" "command"])
:dataSupport t
: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)
:inlayHint `(: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)])))
:window `(:showDocument (:support t)
:workDoneProgress t)
:general (list :positionEncodings ["utf-32" "utf-8" "utf-16"])
: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)
(languages
:initform nil
:documentation "Alist ((MODE . LANGUAGE-ID-STRING)...) of managed languages."