forked from joaotavora/eglot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
eglot.el
1846 lines (1679 loc) · 82.4 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 Free Software Foundation, Inc.
;; Version: 1.1
;; 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.6"))
;; 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 'cl-lib)
(require 'project)
(require 'url-parse)
(require 'url-util)
(require 'pcase)
(require 'compile) ; for some faces
(require 'warnings)
(require 'flymake)
(require 'xref)
(require 'subr-x)
(require 'jsonrpc)
(require 'filenotify)
(require 'ert)
;;; 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
js2-mode
rjsx-mode) . ("javascript-typescript-stdio"))
(sh-mode . ("bash-language-server" "start"))
((c++-mode
c-mode) . (eglot-cquery "cquery"))
(ruby-mode
. ("solargraph" "socket" "--port"
:autoport))
(php-mode . ("php" "vendor/felixfbecker/\
language-server/bin/php-language-server.php"))
(haskell-mode . ("hie-wrapper"))
(kotlin-mode . ("kotlin-language-server"))
(go-mode . ("go-langserver" "-mode=stdio" "-gocodecompletion")))
"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
na positive integer number 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...]), whereby 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 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 CLASS-NAME, or a plain list interpreted as
the previous descriptions of CONTACT, in which case it is
converted to produce a plist with a suitable :PROCESS initarg
to CLASS-NAME. The class `eglot-lsp-server' descends
`jsonrpc-process-connection', which you should see for the
semantics of the mandatory :PROCESS argument.
* A function of no arguments producing any of the above values
for CONTACT.")
(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-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")))
;;; API (WORK-IN-PROGRESS!)
;;;
(cl-defmacro eglot--with-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--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 id &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) nil)) ; blank default
(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))
: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)))
:hover `(:dynamicRegistration :json-false)
:signatureHelp `(:dynamicRegistration :json-false)
:references `(:dynamicRegistration :json-false)
:definition `(:dynamicRegistration :json-false)
:documentSymbol `(:dynamicRegistration :json-false)
:documentHighlight `(:dynamicRegistration :json-false)
:codeAction `(:dynamicRegistration :json-false)
:formatting `(:dynamicRegistration :json-false)
:rangeFormatting `(:dynamicRegistration :json-false)
:rename `(:dynamicRegistration :json-false)
:publishDiagnostics `(:relatedInformation :json-false))
:experimental (list))))
(defclass eglot-lsp-server (jsonrpc-process-connection)
((project-nickname
:documentation "Short nickname for the associated project."
:accessor eglot--project-nickname)
(major-mode
:documentation "Major mode symbol."
:accessor eglot--major-mode)
(capabilities
:documentation "JSON object containing server capabilities."
:accessor eglot--capabilities)
(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))
;; this one is supposed to always fail, because it asks the
;; server to exit itself. Hence ignore-errors.
(ignore-errors (jsonrpc-request server :exit nil :timeout 1)))
;; Turn off `eglot--managed-mode' where appropriate.
(dolist (buffer (eglot--managed-buffers server))
(eglot--with-live-buffer buffer (eglot--managed-mode-onoff server nil)))
;; Now ask jsonrpc.el to shut down the server (which under normal
;; conditions should return immediately).
(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))
(eglot--with-live-buffer buffer (eglot--managed-mode-onoff server nil)))
;; 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)
(or (eq m1 m2)
(and (listp m1) (memq m2 m1)))))))
(guess (if (functionp guess) (funcall guess) guess))
(class (or (and (consp guess) (symbolp (car guess))
(prog1 (car guess) (setq guess (cdr guess))))
'eglot-lsp-server))
(program (and (listp guess) (stringp (car 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 started (or contacted) via CONTACT. If
this operation is successful, current *and future* file buffers
of MANAGED-MAJOR-MODE inside PROJECT automatically 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 symbol `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
(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--with-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."
(interactive (list (eglot--current-server-or-lose)))
(display-buffer (jsonrpc-events-buffer server)))
(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 nil "Hook run after connecting in `eglot--connect'.")
(defvar eglot-server-initialized-hook
'(eglot-signal-didChangeConfiguration)
"Hook run after server is successfully initialized.
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 (car (project-roots 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 ()
(make-process
:name readable-name
:command contact
:connection-type 'pipe
:coding 'utf-8-emacs-unix
:stderr (get-buffer-create
(format "*%s stderr*" readable-name))))))))
(spread
(lambda (fn)
(lambda (&rest args)
(apply fn (append (butlast args) (car (last args)))))))
(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)
;; 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
(jsonrpc-lambda (&key capabilities)
(unless cancelled
(push server
(gethash project eglot--servers-by-project))
(setf (eglot--capabilities server) capabilities)
(dolist (buffer (buffer-list))
(with-current-buffer buffer
(eglot--maybe-activate-editing-mode server)))
(jsonrpc-notify server :initialized `(:__dummy__ t))
(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)))))))
(run-hook-with-args 'eglot-connect-hook server)
(run-hook-with-args 'eglot-server-initialized-hook server)
(eglot--message
"Connected! Server `%s' now managing `%s' buffers \
in project `%s'."
(jsonrpc-name server) managed-major-mode
(eglot--project-nickname server))
(when tag (throw tag t))))
:timeout eglot-connect-timeout
:error-fn (jsonrpc-lambda (&key code message _data)
(unless cancelled
(jsonrpc-shutdown server)
(let ((msg (format "%s: %s" code message)))
(if tag (throw tag `(error . ,msg))
(eglot--error msg)))))
:timeout-fn (lambda ()
(unless cancelled
(jsonrpc-shutdown server)
(let ((msg (format "Timed out")))
(if tag (throw tag `(error . ,msg))
(eglot--error msg))))))
(cond ((numberp eglot-sync-connect)
(accept-process-output nil eglot-sync-connect))
(eglot-sync-connect
(while t (accept-process-output nil 30)))))))
(pcase retval
(`(error . ,msg) (eglot--error msg))
(`nil (eglot--message "Waiting in background for server `%s'"
(jsonrpc-name server))
nil)
(_ server)))
(quit (jsonrpc-shutdown server) (setq cancelled 'quit)))
(setq tag nil))))
(defun eglot--inferior-bootstrap (name contact &optional connect-args)
"Use CONTACT to start a server, then connect to it.
Return a cons of two process objects (CONNECTION . INFERIOR).
Name both based on NAME.
CONNECT-ARGS are passed as additional arguments to
`open-network-stream'."
(let* ((port-probe (make-network-process :name "eglot-port-probe-dummy"
:server t
:host "localhost"
:service 0))
(port-number (unwind-protect
(process-contact port-probe :service)
(delete-process port-probe)))
inferior connection)
(unwind-protect
(progn
(setq inferior
(make-process
:name (format "autostart-inferior-%s" name)
:stderr (format "*%s stderr*" name)
:command (cl-subst
(format "%s" port-number) :autoport contact)))
(setq connection
(cl-loop
repeat 10 for i from 1
do (accept-process-output nil 0.5)
while (process-live-p inferior)
do (eglot--message
"Trying to connect to localhost and port %s (attempt %s)"
port-number i)
thereis (ignore-errors
(apply #'open-network-stream
(format "autoconnect-%s" name)
nil
"localhost" port-number connect-args))))
(cons connection inferior))
(cond ((and (process-live-p connection)
(process-live-p inferior))
(eglot--message "Done, connected to %s!" port-number))
(t
(when inferior (delete-process inferior))
(when connection (delete-process connection))
(eglot--error "Could not start and connect to server%s"
(if inferior
(format " started with %s"
(process-command inferior))
"!")))))))
;;; Helpers (move these to API?)
;;;
(defun eglot--error (format &rest args)
"Error out with FORMAT with ARGS."
(error "[eglot] %s" (apply #'format format args)))
(defun eglot--message (format &rest args)
"Message out with FORMAT with ARGS."
(message "[eglot] %s" (apply #'format format args)))
(defun eglot--warn (format &rest args)
"Warning message with FORMAT and ARGS."
(apply #'eglot--message (concat "(warning) " format) args)
(let ((warning-minimum-level :error))
(display-warning 'eglot (apply #'format format args) :warning)))
(defun eglot--pos-to-lsp-position (&optional pos)
"Convert point POS to LSP position."
(eglot--widening
(list :line (1- (line-number-at-pos pos t)) ; F!@&#$CKING OFF-BY-ONE
:character (- (goto-char (or pos (point)))
(line-beginning-position)))))
(defun eglot--lsp-position-to-point (pos-plist &optional marker)
"Convert LSP position POS-PLIST to Emacs point.
If optional MARKER, return a marker instead"
(save-excursion (goto-char (point-min))
(forward-line (min most-positive-fixnum
(plist-get pos-plist :line)))
(forward-char (min (plist-get pos-plist :character)
(- (line-end-position)
(line-beginning-position))))
(if marker (copy-marker (point-marker)) (point))))
(defun eglot--path-to-uri (path)
"URIfy PATH."
(url-hexify-string
(concat "file://" (if (eq system-type 'windows-nt) "/") (file-truename path))
url-path-allowed-chars))
(defun eglot--uri-to-path (uri)
"Convert URI to a file path."
(when (keywordp uri) (setq uri (substring (symbol-name uri) 1)))
(let ((retval (url-filename (url-generic-parse-url (url-unhex-string uri)))))
(if (eq system-type 'windows-nt) (substring retval 1) retval)))
(defun eglot--snippet-expansion-fn ()
"Compute a function to expand snippets.
Doubles as an indicator of snippet support."
(and (boundp 'yas-minor-mode)
(symbol-value 'yas-minor-mode)
'yas-expand-snippet))
(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")))
(defun eglot--format-markup (markup)
"Format MARKUP according to LSP's spec."
(pcase-let ((`(,string ,mode)
(if (stringp markup) (list (string-trim markup)
(intern "gfm-mode"))
(list (plist-get markup :value)
(intern (concat (plist-get markup :language) "-mode" ))))))
(with-temp-buffer
(ignore-errors (funcall mode))
(insert string) (font-lock-ensure) (buffer-string))))
(defcustom eglot-ignored-server-capabilites (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 '(repeat symbol))
(defun eglot--server-capable (&rest feats)
"Determine if current server is capable of FEATS."
(unless (cl-some (lambda (feat)
(memq feat eglot-ignored-server-capabilites))
feats)
(cl-loop for caps = (eglot--capabilities (eglot--current-server-or-lose))
then (cadr probe)
for (feat . more) on feats
for probe = (plist-member caps feat)
if (not probe) do (cl-return nil)
if (eq (cadr probe) :json-false) do (cl-return nil)
if (not (listp (cadr probe))) do (cl-return (if more nil (cadr probe)))
finally (cl-return (or (cadr probe) t)))))
(defun eglot--range-region (range &optional markers)
"Return region (BEG . END) that represents LSP RANGE.
If optional MARKERS, make markers."
(let* ((st (plist-get range :start))
(beg (eglot--lsp-position-to-point st markers))
(end (eglot--lsp-position-to-point (plist-get range :end) markers)))
(cons beg end)))
(defun eglot--read-server (prompt &optional dont-if-just-the-one)
"Read a running Eglot server from minibuffer using PROMPT.
If DONT-IF-JUST-THE-ONE and there's only one server, don't prompt
and just return it. PROMPT shouldn't end with a question mark."
(let ((servers (cl-loop for servers
being hash-values of eglot--servers-by-project
append servers))
(name (lambda (srv)
(format "%s/%s" (eglot--project-nickname srv)
(eglot--major-mode srv)))))
(cond ((null servers)
(eglot--error "No servers!"))
((or (cdr servers) (not dont-if-just-the-one))
(let* ((default (when-let ((current (eglot--current-server)))
(funcall name current)))
(read (completing-read
(if default
(format "%s (default %s)? " prompt default)
(concat prompt "? "))
(mapcar name servers)
nil t
nil nil
default)))
(cl-find read servers :key name :test #'equal)))
(t (car servers)))))
;;; Minor modes
;;;
(defvar eglot-mode-map (make-sparse-keymap))
(defvar-local eglot--current-flymake-report-fn nil
"Current flymake report function for this buffer")
(define-minor-mode eglot--managed-mode
"Mode for source buffers managed by some EGLOT project."
nil nil eglot-mode-map
(cond
(eglot--managed-mode
(add-hook 'after-change-functions 'eglot--after-change nil t)
(add-hook 'before-change-functions 'eglot--before-change nil t)
(add-hook 'flymake-diagnostic-functions 'eglot-flymake-backend nil t)
(add-hook 'kill-buffer-hook 'eglot--signal-textDocument/didClose nil t)
(add-hook 'kill-buffer-hook 'eglot--managed-mode-onoff nil t)
(add-hook 'before-revert-hook 'eglot--signal-textDocument/didClose nil t)
(add-hook 'before-save-hook 'eglot--signal-textDocument/willSave nil t)
(add-hook 'after-save-hook 'eglot--signal-textDocument/didSave nil t)
(add-hook 'xref-backend-functions 'eglot-xref-backend nil t)
(add-hook 'completion-at-point-functions #'eglot-completion-at-point nil t)
(add-hook 'change-major-mode-hook 'eglot--managed-mode-onoff nil t)
(add-function :before-until (local 'eldoc-documentation-function)
#'eglot-eldoc-function)
(add-function :around (local 'imenu-create-index-function) #'eglot-imenu)
(flymake-mode 1)
(eldoc-mode 1))
(t
(remove-hook 'flymake-diagnostic-functions 'eglot-flymake-backend t)
(remove-hook 'after-change-functions 'eglot--after-change t)
(remove-hook 'before-change-functions 'eglot--before-change t)
(remove-hook 'kill-buffer-hook 'eglot--signal-textDocument/didClose t)
(remove-hook 'before-revert-hook 'eglot--signal-textDocument/didClose t)
(remove-hook 'before-save-hook 'eglot--signal-textDocument/willSave t)
(remove-hook 'after-save-hook 'eglot--signal-textDocument/didSave t)
(remove-hook 'xref-backend-functions 'eglot-xref-backend t)
(remove-hook 'completion-at-point-functions #'eglot-completion-at-point t)
(remove-hook 'change-major-mode-hook #'eglot--managed-mode-onoff t)
(remove-function (local 'eldoc-documentation-function)
#'eglot-eldoc-function)
(remove-function (local 'imenu-create-index-function) #'eglot-imenu)
(setq eglot--current-flymake-report-fn nil))))
(defvar-local eglot--cached-current-server nil
"A cached reference to the current EGLOT server.
Reset in `eglot--managed-mode-onoff'.")
(defun eglot--managed-mode-onoff (&optional server turn-on)
"Proxy for function `eglot--managed-mode' with TURN-ON and SERVER."
(let ((buf (current-buffer)))
(cond ((and server turn-on)
(eglot--managed-mode 1)
(setq eglot--cached-current-server server)
(cl-pushnew buf (eglot--managed-buffers server)))
(t
(eglot--managed-mode -1)
(let ((server
(or server
eglot--cached-current-server)))
(setq eglot--cached-current-server nil)
(when server
(setf (eglot--managed-buffers server)
(delq buf (eglot--managed-buffers server)))))))))
(defun eglot--current-server ()
"Find the current logical EGLOT server."
(or
eglot--cached-current-server
(let* ((probe (or (project-current)
`(transient . ,default-directory))))
(cl-find major-mode (gethash probe eglot--servers-by-project)
:key #'eglot--major-mode))))
(defun eglot--current-server-or-lose ()
"Return current logical EGLOT server connection or error."
(or (eglot--current-server)
(jsonrpc-error "No current JSON-RPC connection")))
(defvar-local eglot--unreported-diagnostics nil
"Unreported Flymake diagnostics for this buffer.")
(defun eglot--maybe-activate-editing-mode (&optional server)
"Maybe activate mode function `eglot--managed-mode'.
If SERVER is supplied, do it only if BUFFER is managed by it. In
that case, also signal textDocument/didOpen."
(unless eglot--managed-mode
(unless server
(when eglot--cached-current-server
(display-warning
:eglot "`eglot--cached-current-server' is non-nil, but it shouldn't be!\n\
Please report this as a possible bug.")
(setq eglot--cached-current-server nil)))
;; Called even when revert-buffer-in-progress-p
(let* ((cur (and buffer-file-name (eglot--current-server)))
(server (or (and (null server) cur) (and server (eq server cur) cur))))
(when server
(setq eglot--unreported-diagnostics `(:just-opened . nil))
(eglot--managed-mode-onoff server t)
(eglot--signal-textDocument/didOpen)))))
(add-hook 'find-file-hook 'eglot--maybe-activate-editing-mode)
(add-hook 'after-change-major-mode-hook 'eglot--maybe-activate-editing-mode)
(defun eglot-clear-status (server)
"Clear the last JSONRPC error for SERVER."
(interactive (list (eglot--current-server-or-lose)))
(setf (jsonrpc-last-error server) nil))
;;; Mode-line, menu and other sugar
;;;
(defvar eglot--mode-line-format `(:eval (eglot--mode-line-format)))
(put 'eglot--mode-line-format 'risky-local-variable t)
(defun eglot--mouse-call (what)
"Make an interactive lambda for calling WHAT from mode-line."
(lambda (event)
(interactive "e")
(let ((start (event-start event))) (with-selected-window (posn-window start)
(save-excursion
(goto-char (or (posn-point start)
(point)))
(call-interactively what)
(force-mode-line-update t))))))
(defun eglot--mode-line-props (thing face defs &optional prepend)
"Helper for function `eglot--mode-line-format'.
Uses THING, FACE, DEFS and PREPEND."
(cl-loop with map = (make-sparse-keymap)
for (elem . rest) on defs
for (key def help) = elem
do (define-key map `[mode-line ,key] (eglot--mouse-call def))
concat (format "%s: %s" key help) into blurb
when rest concat "\n" into blurb
finally (return `(:propertize ,thing
face ,face
keymap ,map help-echo ,(concat prepend blurb)
mouse-face mode-line-highlight))))
(defun eglot--mode-line-format ()
"Compose the EGLOT's mode-line."
(pcase-let* ((server (eglot--current-server))
(nick (and server (eglot--project-nickname server)))
(pending (and server (hash-table-count
(jsonrpc--request-continuations server))))
(`(,_id ,doing ,done-p ,detail) (and server (eglot--spinner server)))
(last-error (and server (jsonrpc-last-error server))))
(append
`(,(eglot--mode-line-props "eglot" 'eglot-mode-line nil))
(when nick
`(":" ,(eglot--mode-line-props
nick 'eglot-mode-line
'((C-mouse-1 eglot-stderr-buffer "go to stderr buffer")
(mouse-1 eglot-events-buffer "go to events buffer")
(mouse-2 eglot-shutdown "quit server")
(mouse-3 eglot-reconnect "reconnect to server")))
,@(when last-error
`("/" ,(eglot--mode-line-props
"error" 'compilation-mode-line-fail
'((mouse-3 eglot-clear-status "clear this status"))
(format "An error occured: %s\n" (plist-get last-error
:message)))))
,@(when (and doing (not done-p))
`("/" ,(eglot--mode-line-props
(format "%s%s" doing
(if detail (format ":%s" detail) ""))
'compilation-mode-line-run '())))
,@(when (cl-plusp pending)
`("/" ,(eglot--mode-line-props
(format "%d oustanding requests" pending) 'warning
'((mouse-3 eglot-forget-pending-continuations
"fahgettaboudit"))))))))))
(add-to-list 'mode-line-misc-info
`(eglot--managed-mode (" [" eglot--mode-line-format "] ")))
(put 'eglot-note 'flymake-category 'flymake-note)
(put 'eglot-warning 'flymake-category 'flymake-warning)
(put 'eglot-error 'flymake-category 'flymake-error)
(defalias 'eglot--make-diag 'flymake-make-diagnostic)
(defalias 'eglot--diag-data 'flymake-diagnostic-data)
(cl-loop for i from 1
for type in '(eglot-note eglot-warning eglot-error )
do (put type 'flymake-overlay-control
`((mouse-face . highlight)
(priority . ,(+ 50 i))
(keymap . ,(let ((map (make-sparse-keymap)))
(define-key map [mouse-1]
(eglot--mouse-call 'eglot-code-actions))
map)))))
;;; Protocol implementation (Requests, notifications, etc)
;;;
(cl-defmethod eglot-handle-notification
(_server method &key &allow-other-keys)
"Handle unknown notification"
(eglot--warn "Server sent unknown notification method `%s'" method))
(cl-defmethod eglot-handle-request
(_server method &key &allow-other-keys)
"Handle unknown request"
(jsonrpc-error "Unknown request method `%s'" method))
(cl-defmethod eglot-execute-command
(server command arguments)
"Execute COMMAND on SERVER with `:workspace/executeCommand'.
COMMAND is a symbol naming the command."
(jsonrpc-request server :workspace/executeCommand
`(:command ,(format "%s" command) :arguments ,arguments)))