-
Notifications
You must be signed in to change notification settings - Fork 8
/
eglot-x.el
2454 lines (2243 loc) · 101 KB
/
eglot-x.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-x.el --- Protocol extensions for Eglot -*- lexical-binding: t; -*-
;; Copyright (C) 2019-2023 Free Software Foundation, Inc.
;; Version: 0.6
;; Author: Felicián Németh <[email protected]>
;; URL: https://github.com/nemethf/eglot-x
;; Keywords: convenience, languages
;; Package-Requires: ((emacs "27.1") (project "0.8.1") (eglot "1.16") (xref "1.4"))
;; 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:
;; Eglot aims to support the Language Server Protocol, but none of its
;; unofficial extensions. Eglot-x adds support for some of these
;; protocol extensions.
;;
;; If you find a bug in Eglot, please, try to reproduce it
;; without Eglot-x, because Eglot-x substantially modifies Eglot's
;; normal behavior as well.
;;
;; Add the following lines to your init file to enable eglot-x
;;
;; (with-eval-after-load 'eglot
;; (require 'eglot-x)
;; (eglot-x-setup))
;;
;; To adjust which extensions are enabled:
;;
;; M-x customize-group RET eglot-x RET
;;; Code:
(require 'eglot)
(require 'project)
(require 'text-property-search)
;;; Customization
(defgroup eglot-x nil
"Protocol extensions for Eglot"
:group 'eglot
:prefix "eglot-x-")
(defcustom eglot-x-enable-menu t
"If non-nil, extend Eglot's mode-line menu."
:type 'boolean)
(defcustom eglot-x-enable-files nil
"If non-nil, enable the support for the files protocol extension.
This extension allows the client and the server to have separate
file systems. For example, the server can run inside a Docker
container, or the source code can be on a remote system accessed
by Tramp.
The client can send files to the server only from the result of
`project-files'. The list of eligible files can further limited
by `eglot-x-files-visible-regexp' and
`eglot-x-files-hidden-regexp'. This feature works if
`project-root' and `project-external-roots' are set correctly.
Enabling extension disables Eglot's built-in support for Tramp
files."
:type 'boolean
:link `(url-link
:tag "the documentation of the extension proposal"
,(concat "https://github.com/sourcegraph/language-server-protocol/"
"blob/master/extension-files.md")))
(defcustom eglot-x-files-visible-regexp "."
"Regexp matching filenames that can be sent to the language server."
:type 'regexp)
(defcustom eglot-x-files-hidden-regexp "/\\."
"Regexp matching filenames that cannot be sent to the language server.
It has precedence over `eglot-x-files-visible-regexp'."
:type 'regexp)
;; There's no point in disabling this feature. The variable exists to
;; help discoverability and for documentation purposes.
(defcustom eglot-x-enable-refs t
"If non-nil, enable the support for additional reference methods.
The command `eglot-x-find-refs' is the entry point for the extra
methods. You can bind it to a key:
(define-key eglot-mode-map (kbd \"s-.\") #\\='eglot-x-find-refs)
Currently, the `ccls' and `rust-analyzer' are the only servers
whose extra reference methods eglot-x supports.
"
:type 'boolean
:link '(url-link
:tag "LSP extensions of the `ccls' server"
"https://github.com/MaskRay/ccls/wiki/LSP-Extensions"))
(defcustom eglot-x-enable-encoding-negotiation t
"If non-nil, automatically negotiate proper encoding of positions.
The extension allows the client and the server to negotiate a
proper encoding to be used in transmitting column positions. It
predates the standardized positionEncodings capability.
`eglot-x-encoding-alist' defines the details of the client's
behavior."
;; Since this feature is the LSP standard as positionEncodings and
;; Eglot supports it, eglot-x "soon" can drop the support for this
;; extension. See: https://github.com/clangd/clangd/issues/1746
:type 'boolean
:link '(url-link
:tag "The definition of the extension (clangd)"
"https://clangd.github.io/extensions.html#utf-8-offsets"))
(defcustom eglot-x-encoding-alist
'(("utf-32" . eglot-x--encoding-configure-utf-32)
("utf-16" . eglot-x--encoding-configure-utf-16))
"Alist of encoding and configuration function pairs.
The keys are the encodings eglot supports. Encodings should be
in the order of peference. It SHOULD include \"utf-16\". Note
that eglot achieves the best performance with \"utf-32\". If the
result of the client-server negotiation is a key of the alist,
then the corresponding function is called with the key as an
argument."
:type '(alist :key-type string :value-type function))
(defcustom eglot-x-enable-snippet-text-edit t
"If non-nil, the server may send SnippetTextEdits.
More precisely, \"WorkspaceEdits returned from codeAction requests
might contain SnippetTextEdits instead of usual TextEdits\".
Example: the \"Add derive\" code action transforms \"struct S;\"
into \"#[derive($0)] struct S;\""
:type 'boolean
:link '(url-link
:tag "A more complex example"
"https://github.com/rust-lang/rust-analyzer/blob/master/\
/crates/ide-assists/src/handlers/generate_trait_from_impl.rs#L20")
:link '(url-link
:tag "The definition of the extension (rust-analyzer)"
"https://github.com/rust-analyzer/rust-analyzer/blob/master/\
docs/dev/lsp-extensions.md#snippet-textedit"))
(defcustom eglot-x-enable-server-status t
"If non-nil, ask the server to send status messages.
The status is displayed in the mode-line and requires
server-support for capability experimental/serverStatus."
:type 'boolean
:link '(url-link
:tag "the definition of the extension (rust-analyzer)"
"https://github.com/rust-analyzer/rust-analyzer/blob/master/\
docs/dev/lsp-extensions.md#server-status"))
(defcustom eglot-x-graph-type 'auto
"Default graph type of `eglot-x-view-crate-graph'."
:type
'(radio
(const :tag "auto: based on display capabilities" auto)
(const svg)
(const :tag "boxart: using unicode characters" boxart)
(const ascii)
(const :tag "raw: for debugging purposes" rawtext))
:link '(url-link
:tag "the definition of the extension"
"https://github.com/rust-analyzer/rust-analyzer/blob/master/\
docs/dev/lsp-extensions.md#view-crate-graph")
:link '(url-link
:tag "documentation of rust-analyzer"
"https://rust-analyzer.github.io/manual.html#view-crate-graph"))
(defcustom eglot-x-enable-colored-diagnostics t
"If non-nil, enable colored diagnostic support for rust-analyzer."
:type 'boolean
:link '(url-link
:tag "the definition of the extension (rust-analyzer)"
"https://github.com/rust-lang/rust-analyzer/blob/master/\
docs/dev/lsp-extensions.md#colored-diagnostic-output"))
(defcustom eglot-x-enable-ff-related-file-integration t
"If non-nil, integrate eglot-x with `ff-find-related-file'.
Eglot-x provides this feature when (i) the Taplo LSP server
manages .toml files, (ii) the rust-analyzer LSP server manages
.rs files, (iii) clangd manages c-related files, or (iv)
OCaml-LSP manages ocaml files. Then it sets a buffer local value
for `ff-related-file-alist'."
:type 'boolean
:link '(function-link ff-find-related-file)
:link '(variable-link ff-related-file-alist))
(defcustom eglot-x-enable-local-docs-support t
"If non-nil, `eglot-x-open-external-documentation' can receive local links."
:type 'boolean
:link '(function-link eglot-x-open-external-documentation)
:link '(url-link
:tag "the definition of the extension (rust-analyzer)"
"https://github.com/rust-lang/rust-analyzer/blob/master/\
docs/dev/lsp-extensions.md#local-documentation"))
(defcustom eglot-x-enable-open-server-logs t
"If non-nil, servers can ask Eglot to show its diagnostics buffers.
This is an undocumented LSP extension of rust-analyzer. When the
server detects a problem, this extension makes the beginning of
the debugging process a tiny bit easier."
:type 'boolean)
(defcustom eglot-x-client-commands
(list "rust-analyzer.runSingle" "rust-analyzer.showReferences"
"rust-analyzer.gotoLocation" "rust-analyzer.rename"
"editor.action.rename")
"List of commands the LSP client supports and advertises to the server."
:type '(set
(const "rust-analyzer.runSingle")
;;(const "rust-analyzer.debugSingle")
(const "rust-analyzer.showReferences")
(const "rust-analyzer.gotoLocation")
;;(const "rust-analyzer.triggerParameterHints")
(const "rust-analyzer.rename")
;;; These have been obsoleted since 2024-07-22 by
;;; https://github.com/rust-lang/rust-analyzer/pull/17647
;; (const "editor.action.triggerParameterHints")
(const "editor.action.rename"))
:link '(url-link
:tag "the definition of the extension (rust-analyzer)"
"https://github.com/rust-lang/rust-analyzer/blob/master/\
docs/dev/lsp-extensions.md#client-commands"))
(defcustom eglot-x-enable-hover-actions t
"Allow the server to put clickable actions at end of hover info.
\\<eglot-mode-map>
\\[eldoc-doc-buffer] shows the eldoc buffer where the actions may appear,
but command `eglot-x-hover-actions' can also execute actions
corresponding to the current point."
:type 'boolean
:link '(url-link
:tag "the definition of the extension (rust-analyzer)"
"https://github.com/rust-lang/rust-analyzer/blob/master/\
docs/dev/lsp-extensions.md#hover-actions"))
;;; Enable the extensions
;;
(defvar eglot-x--enabled nil)
(defun eglot-x-setup ()
"Set up eglot-x to extend Eglot's feature-set.
Call it when there are no active LSP servers."
(interactive)
(setq eglot-x--enabled t)
;; defuns containing file-remote-p
(advice-add 'eglot--cmd :around #'eglot-x--disable-built-in-tramp)
(advice-add 'eglot--connect :around #'eglot-x--disable-built-in-tramp)
(advice-add 'eglot-path-to-uri :around #'eglot-x--disable-built-in-tramp)
(advice-add 'eglot-uri-to-path :around #'eglot-x--disable-built-in-tramp)
;; defuns containing file-local-name (but not file-remote-p)
(advice-add 'eglot--connect :around #'eglot-x--disable-built-in-tramp)
;; others
(advice-add 'eglot--connect :around #'eglot-x--encoding-enable-hack)
(advice-add 'jsonrpc--async-request-1 :filter-args
#'eglot-x--encoding-mod-async-request)
(advice-add #'eglot--apply-text-edits :around #'eglot-x--override-text-edits))
(defun eglot-x-disable ()
"Disable eglot-x.
Some features will not be completely disabled for on-going LSP
connections."
(interactive)
(setq eglot-x--enabled nil)
;; defuns containing file-remote-p
(advice-remove 'eglot--cmd #'eglot-x--disable-built-in-tramp)
(advice-remove 'eglot--connect #'eglot-x--disable-built-in-tramp)
(advice-remove 'eglot-path-to-uri #'eglot-x--disable-built-in-tramp)
(advice-remove 'eglot-uri-to-path #'eglot-x--disable-built-in-tramp)
;; defuns containing file-local-name (but not file-remote-p)
(advice-remove 'eglot--connect #'eglot-x--disable-built-in-tramp)
;; others
(advice-remove 'eglot--connect #'eglot-x--encoding-enable-hack)
(advice-remove 'jsonrpc--async-request-1
#'eglot-x--encoding-mod-async-request)
(advice-remove #'eglot--apply-text-edits #'eglot-x--override-text-edits))
(easy-menu-define eglot-x-menu nil "Eglot-x menu"
`("Eglot-x"
["Customize Eglot-x" (lambda () (interactive) (customize-group "eglot-x"))]
"--"
["Find additional references" eglot-x-find-refs]
["Find related file" ff-find-other-file
:visible (and eglot-x-enable-ff-related-file-integration
(map-contains-key eglot--saved-bindings
'ff-other-file-alist))]
["Join lines" eglot-x-join-lines
:visible (eglot-server-capable :experimental :joinLines)]
["Move item down" eglot-x-move-item-down
:visible (eglot-server-capable :experimental :moveItem)]
["Move item up" eglot-x-move-item-up
:visible (eglot-server-capable :experimental :moveItem)]
["On enter" eglot-x-on-enter
:visible (eglot-server-capable :experimental :onEnter)]
["Jump to matching brace" eglot-x-matching-brace
:visible (eglot-server-capable :experimental :matchingBrace)]
["Open external documentation" eglot-x-open-external-documentation
:visible (eglot-server-capable :experimental :externalDocs)]
["Structural Search Replace (SSR)" eglot-x-structural-search-replace
:visible (eglot-server-capable :experimental :ssr)]
["Ask Runnables" eglot-x-ask-runnables
:visible (eglot-server-capable :experimental :runnables)]
["Show Server Status" eglot-x-show-server-status
:visible eglot-x-enable-server-status
:active (eglot-x--get-from-server (eglot-current-server)
:server-status)]
("rust-analyzer commands"
:visible (equal "rust-analyzer"
(plist-get (eglot--server-info (eglot-current-server))
:name))
["Ask related tests" eglot-x-ask-related-tests]
["Find workspace symbol" eglot-x-find-workspace-symbol]
["Expand macro" eglot-x-expand-macro]
("Flycheck"
["Run flycheck" eglot-x-run-flycheck]
["Clear flycheck" eglot-x-clear-flycheck]
["Cancel flycheck" eglot-x-cancel-flycheck])
["View crate graph" eglot-x-view-crate-graph]
["Find crate in dependencies" eglot-x-find-crate]
["View Recursive Memory Layout" eglot-x-view-recursive-memory-layout]
"--"
["Reload workspace" eglot-x-reload-workspace]
["Rebuild proc-macros" eglot-x-rebuild-proc-macros]
["Status" eglot-x-analyzer-status]
["Show syntax tree" eglot-x-show-syntax-tree]
["View HIR" eglot-x-view-hir]
["View MIR" eglot-x-view-mir]
["Interpret Function" eglot-x-interpret-function]
["Debug file sync problems" eglot-x-debug-file-sync-problems]
["View item tree" eglot-x-view-item-tree]
["Show memory usage" eglot-x-memory-usage])
("taplo commands"
:visible (equal "Taplo"
(plist-get (eglot--server-info (eglot-current-server))
:name))
["Show info about associated schema" eglot-x-taplo-show-associated-schema]
["Find associated schema" eglot-x-taplo-find-associated-schema]
["List schemas" eglot-x-taplo-list-schemas])
;; OCaml-LSP commands
["Find typed holes" eglot-x-find-typed-holes
:visible (eglot-server-capable
:experimental :ocamllsp :handleTypedHoles)]))
(cl-defmethod eglot-client-capabilities :around
(_s)
"Extend client with non-standard capabilities."
(if (not eglot-x--enabled)
(cl-call-next-method)
(let ((capabilities (copy-tree (cl-call-next-method))))
(when eglot-x-enable-files
(setq capabilities (append capabilities
(list :xfilesProvider t
:xcontentProvider t))))
(when eglot-x-enable-encoding-negotiation
(add-hook 'eglot-managed-mode-hook
#'eglot-x--encoding-configure)
(setq capabilities
(append capabilities
(list :offsetEncoding
(apply #'vector
(mapcar #'car eglot-x-encoding-alist))))))
(when (and eglot-x-enable-snippet-text-edit
(eglot--snippet-expansion-fn))
(let* ((exp (plist-get capabilities :experimental))
(old (if (eq exp eglot--{}) '() exp))
(new (plist-put old :snippetTextEdit t)))
(setq capabilities (plist-put capabilities :experimental new))))
(when eglot-x-enable-server-status
(let* ((exp (plist-get capabilities :experimental))
(old (if (eq exp eglot--{}) '() exp))
(new (plist-put old :serverStatusNotification t)))
(setq capabilities (plist-put capabilities :experimental new))))
(when eglot-x-enable-colored-diagnostics
(let* ((exp (plist-get capabilities :experimental))
(old (if (eq exp eglot--{}) '() exp))
(new (plist-put old :colorDiagnosticOutput t)))
(setq capabilities (plist-put capabilities :experimental new))))
(when eglot-x-enable-open-server-logs
(let* ((exp (plist-get capabilities :experimental))
(old (if (eq exp eglot--{}) '() exp))
(new (plist-put old :openServerLogs t)))
(setq capabilities (plist-put capabilities :experimental new))))
(when eglot-x-client-commands
(let* ((exp (plist-get capabilities :experimental))
(old (if (eq exp eglot--{}) '() exp))
(new (plist-put
old
:commands `(:commands ,(apply #'vector
eglot-x-client-commands)))))
(setq capabilities (plist-put capabilities :experimental new))))
(when eglot-x-enable-hover-actions
(add-hook 'eglot-managed-mode-hook #'eglot-x-configure-eldoc)
(let* ((exp (plist-get capabilities :experimental))
(old (if (eq exp eglot--{}) '() exp))
(new (plist-put old :hoverActions t)))
(setq capabilities (plist-put capabilities :experimental new))))
(when (boundp 'eglot-menu)
(if eglot-x-enable-menu
(progn
(add-to-list 'eglot-menu
'(eglot-x-sep menu-item "--") t)
(add-to-list 'eglot-menu
`(eglot-x menu-item "eglot-x" ,eglot-x-menu) t))
(setq eglot-menu (assq-delete-all 'eglot-x-sep eglot-menu))
(setq eglot-menu (assq-delete-all 'eglot-x eglot-menu))))
(when eglot-x-enable-ff-related-file-integration
(add-hook 'eglot-managed-mode-hook
#'eglot-x--configure-ff-related-file-alist))
(when eglot-x-enable-local-docs-support
(let* ((exp (plist-get capabilities :experimental))
(old (if (eq exp eglot--{}) '() exp))
(new (plist-put old :localDocs t)))
(setq capabilities (plist-put capabilities :experimental new))))
capabilities)))
(eval-when-compile (require 'find-file))
(declare-function ff-find-the-other-file "find-file")
;; Should be in `eglot-managed-mode-hook'.
(defun eglot-x--configure-ff-related-file-alist ()
(if (and (eglot-managed-p)
eglot-x-enable-ff-related-file-integration
(require 'find-file nil t))
(let* ((server-info (eglot--server-info (eglot-current-server)))
(server-name (plist-get server-info :name))
(alist (cond
((equal "clangd" server-name)
'(("." eglot-x--c-ff-related-file)))
((equal "Taplo" server-name)
'(("." eglot-x--taplo-ff-related-file)))
((eglot-server-capable :experimental :openCargoToml)
'(("." eglot-x--rust-ff-related-file)))
((eglot-server-capable :experimental :ocamllsp
:handleSwitchImplIntf)
'(("." eglot-x--ocaml-ff-related-file))))))
(when alist
(eglot--setq-saving ff-other-file-alist alist)))))
;;; Files extension
;;
;; https://github.com/sourcegraph/language-server-protocol/blob/master/extension-files.md
(defun eglot-x--disable-built-in-tramp (orig-fun &rest args)
"Disable Eglot's remote server support when `eglot-x-enable-files' is set."
(if eglot-x-enable-files
(cl-flet ((file-remote-p nil)
(file-local-name (file) file))
(apply orig-fun args))
(apply orig-fun args)))
(defun eglot-x--path-to-TextDocumentIdentifier (path)
"Convert PATH to TextDocumentIdentifier."
`(:uri ,(eglot-path-to-uri path)))
(defvar eglot-x--project-files-cache '(0 nil nil)
"A cache for function `eglot-x--project-files'.
The format for the cache: (timestamp args files).")
;; It seems language servers repeatedly request textDocument/xcontent,
;; so we cache the available files.
(defun eglot-x--project-files (project &optional dirs)
"Return a list of files in directories DIRS in PROJECT.
DIRS is a list of absolute directories; it should be some
subset of the project roots and external roots."
(let* ((args (list project dirs))
(files (caddr eglot-x--project-files-cache))
(timestamp (current-time))
(time-diff (time-subtract timestamp
(car eglot-x--project-files-cache)))
(dirs (or dirs
(append (list (project-root project))
(project-external-roots project)))))
(when (or (not (equal args (cadr eglot-x--project-files-cache)))
(< 0 (car time-diff))
(< 5 (cadr time-diff)))
;; Cache is expired
(setq files (project-files project dirs)))
(setq eglot-x--project-files-cache (list timestamp args files))
files))
(defun eglot-x--files-visible-p (file &optional dir)
"Return non-nil if FILE can be sent to the language server.
If DIR is non-nil, the file should be in directory DIR. FILE is
assumed to be an element of `project-files'."
(and (string-match eglot-x-files-visible-regexp file)
(not (string-match eglot-x-files-hidden-regexp file))
(or (not dir)
(file-in-directory-p file dir))))
(cl-defmethod eglot-handle-request
(server (_method (eql workspace/xfiles)) &key base)
"Handle server request workspace/xfiles"
(let* ((project (eglot--project server))
(roots (append (list (project-root project))
(project-external-roots project)))
(dirs (if base
;; Find the root directory of base
`(,(seq-find (lambda (dir) (file-in-directory-p base dir))
roots))
roots))
(dirs (seq-remove #'null dirs))
(files (when dirs
(eglot-x--project-files project dirs)))
(pred (lambda (file) (eglot-x--files-visible-p file base))))
(apply 'vector
(mapcar 'eglot-x--path-to-TextDocumentIdentifier
(seq-filter pred files)))))
(cl-defmethod eglot-handle-request
(server (_method (eql textDocument/xcontent)) &key textDocument)
"Handle server request textDocument/xcontent"
(let* ((file (eglot-uri-to-path (plist-get textDocument :uri)))
(buffer (find-buffer-visiting file))
(project-files (eglot-x--project-files (eglot--project server))))
(if (or (not (eglot-x--files-visible-p file))
(not (seq-contains-p project-files file #'string-equal)))
(progn
(eglot--warn "Server-request denied for file: %s" file)
;; https://github.com/sourcegraph/language-server-protocol/pull/26
(jsonrpc-error :code -32001 :message "Access denied"))
(if buffer
(with-current-buffer buffer
;; The server might request textDocument/xcontent even
;; before `eglot--connect' succesfully finishes and puts
;; the server into `eglot--servers-by-project'. But this
;; buffer belongs to the project, so set the local cache,
;; and avoid a failure in
;; `eglot--TextDocumentItem'/`eglot--current-server-or-lose'.
(setq eglot--cached-server server)
(eglot--TextDocumentItem))
(condition-case err
(with-temp-buffer
(let ((buffer-file-name file))
(insert-file-contents-literally file)
(eglot--TextDocumentItem)))
(file-error
(let ((msg (error-message-string err)))
(eglot--warn "Server-request failed for %s: %s" file msg)
(jsonrpc-error :code -32002 :message msg))))))))
;;; Extra reference methods
;;
;; API functions, variables, and the implementation is not yet set in
;; stone.
(defvar eglot-x--extra-refs-alist
'(("ccls" .
;; https://github.com/MaskRay/ccls/wiki/LSP-Extensions
(("reload" (lambda ()
(jsonrpc-notify (eglot-current-server)
:$ccls/reload
(make-hash-table))))
("vars" :$ccls/vars)
("call" :$ccls/call)
("callee" :$ccls/call :callee t)
("navigate-up" :$ccls/navigate :direction "U")
("navigate-down" :$ccls/navigate :direction "D")
("navigate-right" :$ccls/navigate :direction "R")
("navigate-left" :$ccls/navigate :direction "L")
("inheritance" :$ccls/inheritance)
("inheritance-derived" :$ccls/navigate :derived t)
("member-var" :$ccls/member :kind 4)
("member-fun" :$ccls/member :kind 3)
("member-type" :$ccls/member :kind 2)
("declaration" eglot-find-declaration)
("implementation" eglot-find-implementation)
("type definition" eglot-find-typeDefinition)))
("rust-analyzer" .
(("parent-module" :experimental/parentModule)
("open-cargo-toml" :experimental/openCargoToml)
("matching brace" eglot-x-matching-brace)
("declaration" eglot-find-declaration)
("implementation" eglot-find-implementation)
("type definition" eglot-find-typeDefinition)))
("Taplo" .
(("Find-associated-schema" eglot-x-taplo-find-associated-schema)))
(t .
(("declaration" eglot-find-declaration)
("implementation" eglot-find-implementation)
("type definition" eglot-find-typeDefinition)))))
(defun eglot-x-find-refs ()
"Find additional references for the identifier at point.
The available reference types depend on the server.
See `eglot-x-enable-refs'."
(interactive)
(unless eglot-x-enable-refs
(eglot--error "Feature is disabled (`eglot-x-enable-refs')"))
(unless (eglot-current-server)
(eglot--error "No active LSP server"))
(let* ((server-name
(plist-get (eglot--server-info (eglot-current-server)) :name))
(extra-refs-alist
(alist-get server-name eglot-x--extra-refs-alist
(alist-get t eglot-x--extra-refs-alist) nil #'equal))
(menu `("Extra refs:" ,`("dummy" . ,extra-refs-alist)))
(selected (tmm-prompt menu)))
(if (functionp (car selected))
(apply #'funcall selected)
(eglot--lsp-xrefs-for-method (car selected)
:extra-params (cdr selected)
:capability :definitionProvider))))
;;; Encoding negotiation
;; https://clangd.llvm.org/extensions.html#utf-8-offsets
;; Eglot does not save the full InitializeResult response of the
;; server, so the following chain of advised functions copies the
;; negotiated encoding into the server's capabilities. It therefore
;; becomes accessible by `eglot-x--encoding-configure'.
(defvar eglot-x--encoding-hack nil)
(defun eglot-x--encoding-enable-hack (orig-fun &rest args)
(let ((eglot-x--encoding-hack t))
(apply orig-fun args)))
;(advice-add 'eglot--connect :around #'eglot-x--encoding-enable-hack)
(defun eglot-x--encoding-mod-async-request (args)
(if (not eglot-x--encoding-hack)
args
(let* ((plist (seq-drop args 3))
(head (seq-take args 3))
(success-fn (plist-get plist :success-fn))
(success-fn (lambda (&rest args)
(let ((args (eglot-x--encoding-mod-result args)))
(apply success-fn args))))
(plist (and plist
(plist-put plist :success-fn success-fn))))
`(,@head ,@plist))))
;(advice-add 'jsonrpc--async-request-1 :filter-args
; #'eglot-x--encoding-mod-async-request)
(defun eglot-x--encoding-mod-result (result)
"If RESULT is initializationOptions, copy offsetEncoding into capabilities."
(let* ((plist (car result))
(offset-encoding (plist-get plist :offsetEncoding))
(capabilities (plist-get plist :capabilities)))
(if (not (and offset-encoding capabilities))
result
(setq plist (copy-tree plist))
(list (plist-put plist :capabilities
(plist-put capabilities :offsetEncoding
offset-encoding))))))
;; Should be in `eglot-managed-mode-hook'.
(defun eglot-x--encoding-configure ()
"Configure eglot based on the negotiated encoding."
(when (and eglot-x-enable-encoding-negotiation
(eglot-managed-p)
(eglot-current-server))
(let* ((encoding (eglot-server-capable :offsetEncoding))
(fn (assoc-default encoding eglot-x-encoding-alist)))
(when fn
(funcall fn encoding)))))
(defun eglot-x--encoding-configure-utf-32 (_encoding)
(let ((pairs
'((eglot-current-linepos-function . eglot-utf-32-linepos)
(eglot-move-to-linepos-function . eglot-move-to-utf-32-linepos))))
(dolist (pair pairs)
(set (make-local-variable (car pair)) (cdr pair)))))
(defun eglot-x--encoding-configure-utf-16 (_encoding)
(let ((pairs
'((eglot-current-linepos-function . eglot-utf-16-linepos)
(eglot-move-to-linepos-function . eglot-move-to-utf-16-linepos))))
(dolist (pair pairs)
(set (make-local-variable (car pair)) (cdr pair)))))
;;; rust-analyzer extensions
;; https://github.com/rust-analyzer/rust-analyzer/blob/master/docs/dev/lsp-extensions.md
;; Implemented elsewhere
;; - Parent Module: implemented in `eglot-x-find-refs'.
;; - Open Cargo.toml: implemented in `eglot-x-find-refs'.
;; Features not implemented:
;; Client Commands (See client_commands() in rust-analyzer/src/config.rs)
;; - rust-analyzer.debugSingle
;; - rust-analyzer.triggerParameterHints
;; CodeAction Groups
;; Configuration in initializationOptions
;; - This is in the standard: https://github.com/joaotavora/eglot/discussions/845
;; Hover Range
(eval-and-compile
;; This is an unnamed type within WorkspaceSymbol/location
(push '(Runnable
((:label kind args) (location)))
eglot--lsp-interface-alist)
(push '(LocationWithOptionalRange
((:uri) (:range)))
eglot--lsp-interface-alist)
;; SnippetTextEdit extends TextEdit
(push '(SnippetTextEdit
((:range :newText)
(:insertTextFormat :annotationId)))
eglot--lsp-interface-alist)
(push '(WorkspaceSymbol
((:name :kind)
(:tags :location :containerName :deprecated)))
eglot--lsp-interface-alist)
;; rust-analyzer: experimentail/serverStatus ServerStatusParams
(push '(ServerStatus
((:health :quiescent)
(:message :workspaceInfo)))
eglot--lsp-interface-alist))
;;; Snippet TextEdit
(defun eglot-x--unify-snippets (aa bb)
"Unify snippet regions AA BB.
AA and BB are in the form of (beg end).
Moreover, keep just one placeholder (default value) because
yasnippnet does not allow more than one placeholder for one field
index."
(if (not aa)
bb
(let* ((s (sort (list aa bb) (lambda (a b) (< (car a) (car b)))))
(a-min (caar s))
(a-max (cadar s))
(b-min (caadr s))
(b-max (cadadr s))
(i 0)
done)
(save-restriction
(widen)
(replace-regexp-in-region "([`$])" "\\\1" a-max b-min)
(narrow-to-region a-min b-max)
(while (not done)
(goto-char (point-min))
(if (not (re-search-forward (format "${?%d[^0-9]" i) nil t))
(setq done t)
(while (re-search-forward (format "${%d:[^}]+}" i) nil t)
(replace-match (format "$%d" i) nil nil))
(setq i (1+ i)))))
(list a-min b-max))))
(defun eglot-x--work-around-snippet-bug (beg end)
"Work around a yasnippet bug.
\"Expanding ${0:placeholder} doesn't replace placeholder text\"
See https://github.com/joaotavora/yasnippet/issues/1141"
;; Increment every field index. It leaves "\$" alone, which is
;; good, but it also leaves "\\$" alone, which it should not.
(save-restriction
(narrow-to-region beg end)
(let (first-done guard brace i)
(while (re-search-forward "\\(.?\\)$\\({?\\)\\([0-9]+\\)" nil t)
(setq guard (match-string 1))
(setq brace (match-string 2))
(setq i (string-to-number (match-string 3)))
(if (string-equal "\\" guard)
(setq i nil)
(replace-match (format "%s$%s%d" guard brace (1+ i))))
(when (and (not first-done) (= i 0))
(if (string-equal "{" brace)
(search-forward "}"))
(setq first-done t)
(insert "$0"))))))
(cl-defun eglot-x--apply-text-edits (edits &optional version silent)
"Apply EDITS for current buffer if at VERSION, or if it's nil.
This is almost a verbatim copy of `eglot--apply-text-edits', but
it handles the SnippetTextEdit format."
;; NOTE: SnippetTextEdit is going to be obsoleted:
;; https://github.com/microsoft/language-server-protocol/pull/1892
;; https://github.com/rust-lang/rust-analyzer/issues/16604
(unless edits (cl-return-from eglot-x--apply-text-edits))
(unless (or (not version) (equal version eglot--versioned-identifier))
(jsonrpc-error "Edits on `%s' require version %d, you have %d"
(current-buffer) version eglot--versioned-identifier))
(atomic-change-group
(let* ((change-group (prepare-change-group))
(howmany (length edits))
(reporter (unless silent
(make-progress-reporter
(format "[eglot-x] applying %s edits to `%s'..."
howmany (current-buffer))
0 howmany)))
(done 0)
snippet snippet-range)
(mapc (pcase-lambda (`(,newText ,insertTextFormat (,beg . ,end)))
(let ((source (current-buffer)))
(with-temp-buffer
(insert newText)
(let ((temp (current-buffer)))
(with-current-buffer source
(save-excursion
(save-restriction
(narrow-to-region beg end)
(replace-buffer-contents temp)))
(when (eql insertTextFormat 2)
(setq snippet-range
(eglot-x--unify-snippets
snippet-range (list (point-min-marker)
(point-max-marker)))))
(when reporter
(eglot--reporter-update reporter (cl-incf done))))))))
(mapcar (eglot--lambda ((SnippetTextEdit) range newText insertTextFormat)
(list newText insertTextFormat (eglot-range-region range 'markers)))
(reverse edits)))
(when snippet-range
(goto-char (car snippet-range))
(apply #'eglot-x--work-around-snippet-bug snippet-range)
(setq snippet (apply #'buffer-substring-no-properties snippet-range))
(apply #'delete-region snippet-range)
(funcall (eglot--snippet-expansion-fn) snippet))
(undo-amalgamate-change-group change-group)
(when reporter
(progress-reporter-done reporter)))))
(defun eglot-x--override-text-edits (oldfun &rest r)
(if (and eglot-x-enable-snippet-text-edit
(eglot--snippet-expansion-fn))
(apply #'eglot-x--apply-text-edits r)
(apply oldfun r)))
;(advice-add #'eglot--apply-text-edits :around #'eglot-x--override-text-edits)
;;; Join Lines
(defun eglot-x-join-lines (&optional beg end)
"Request the server to handle \"Join Lines\" editor action."
(interactive (and (region-active-p) (list (region-beginning) (region-end))))
(eglot-server-capable-or-lose :experimental :joinLines)
(let ((res
(jsonrpc-request (eglot--current-server-or-lose)
:experimental/joinLines
(list :textDocument (eglot--TextDocumentIdentifier)
:ranges
(vector (list :start (eglot--pos-to-lsp-position beg)
:end (eglot--pos-to-lsp-position end)))))))
(mapc (lambda (textEdit)
(eglot--dbind ((TextEdit) range newText) textEdit
(pcase-let ((`(,beg . ,end)
(eglot-range-region range)))
(delete-region beg end)
(goto-char beg)
(funcall #'insert newText))))
res)))
;;; Move Item
(defun eglot-x-move-item-down (arg)
"Ask server to move down item under point or selection.
With prefix arg move it up."
(interactive "*P")
(eglot-server-capable-or-lose :experimental :moveItem)
(let* ((beg (if (region-active-p) (region-beginning) (point)))
(end (if (region-active-p) (region-end) (point)))
(res
(jsonrpc-request (eglot--current-server-or-lose)
:experimental/moveItem
`(:direction ,(if arg "Up" "Down")
:range ,(list :start (eglot--pos-to-lsp-position beg)
:end (eglot--pos-to-lsp-position end))
:textDocument ,(eglot--TextDocumentIdentifier)))))
(eglot-x--apply-text-edits res)))
(defun eglot-x-move-item-up (arg)
"Ask server to move up item under point or selection.
With prefix arg move it down."
(interactive "*P")
(eglot-x-move-item-down (not arg)))
;;; On Enter
(defvar eglot-x-on-enter-fallback #'newline
"Fallback function when onEnter does nothing.
It seems onEnter works only in comments, otherwise it returns no
TextEdits. This variable defines what function to call in that
case.")
(defun eglot-x-on-enter (&optional arg interactive)
"Request the server to handle the \"Enter\" keypress."
(interactive "*P\np")
(eglot-server-capable-or-lose :experimental :onEnter)
(let ((res
(jsonrpc-request (eglot--current-server-or-lose)
:experimental/onEnter
(eglot--TextDocumentPositionParams))))
(if res
(eglot-x--apply-text-edits res)
(funcall eglot-x-on-enter-fallback arg interactive))))
;;; Matching Brace
(defun eglot-x-matching-brace ()
"Jump to matching brace. Available in `eglot-x-find-refs' as well."
;; When is this better than `backward-sexp', `forward-sexp'?
(interactive)
(eglot-server-capable-or-lose :experimental :matchingBrace)
(let ((res (jsonrpc-request
(eglot--current-server-or-lose)
:experimental/matchingBrace
`(:textDocument ,(eglot--TextDocumentIdentifier)
:positions ,(vector (eglot--pos-to-lsp-position))))))
(mapc (lambda (position)
(push-mark)
(goto-char (eglot--lsp-position-to-point position)))
res)))
;;; Open External Documentation
(defun eglot-x-open-external-documentation ()
"Open a URL to the documentation for the symbol under point."
(interactive)
(eglot-server-capable-or-lose :experimental :externalDocs)
(let ((res (jsonrpc-request (eglot--current-server-or-lose)
:experimental/externalDocs
(eglot--TextDocumentPositionParams))))
(when res
(let ((local (plist-get res :local))
(web (or (plist-get res :web)
res)))
(if (and local (file-exists-p (eglot-uri-to-path local)))
(browse-url local)
(browse-url web))))))
;;; Analyzer Status
(defun eglot-x-analyzer-status ()
"Show server's internal status message, mostly for debugging purposes."
(interactive)
(let ((res
(jsonrpc-request (eglot--current-server-or-lose)
:rust-analyzer/analyzerStatus
`(:textDocument ,(eglot--TextDocumentIdentifier)))))
(with-help-window (help-buffer)
(with-current-buffer (help-buffer)
(insert (format "%s" res))))))
;;; Reload Workspace; Rebuild proc-macros
(defun eglot-x-reload-workspace ()
"Ask server to reload project information (ie, re-execute cargo metadata)."
(interactive)
(jsonrpc-request (eglot--current-server-or-lose)
:rust-analyzer/reloadWorkspace
nil))
(defun eglot-x-rebuild-proc-macros ()
"Ask the rust-analyzer server to rebuilds build scripts and proc-macros.
The server also runs the build scripts to reseed the build data."
(interactive)
(jsonrpc-request (eglot--current-server-or-lose)
:rust-analyzer/rebuildProcMacros
nil))
;;; Syntax Tree
(defvar eglot-x--source-buffer)
(defun eglot-x--pop-source-buffer (marker)
(save-excursion
(goto-char (marker-position marker))
(beginning-of-line)
(when (re-search-forward "@\\([0-9]+\\)\\.\\.\\([0-9]+\\)")
(let ((beg (string-to-number (match-string 1)))
(end (string-to-number (match-string 2))))
(pop-to-buffer eglot-x--source-buffer)
(goto-char (+ 1 end))
(set-mark-command nil)
(goto-char (+ 1 beg))))))
(define-button-type 'eglot-x--syntax-tree
:supertype 'help-xref
'action #'eglot-x--pop-source-buffer
'help-echo (purecopy "mouse-1, RET: jump to source"))
(defun eglot-x-show-syntax-tree (&optional beg end)
"Show textual representation of a parse tree for the file/region.
Primarily for debugging, but very useful for all people working
on rust-analyzer itself."
(interactive (and (region-active-p) (list (region-beginning) (region-end))))
(let ((res