-
Notifications
You must be signed in to change notification settings - Fork 13
/
lspce.el
2146 lines (1959 loc) · 88.3 KB
/
lspce.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
;;; lspce.el --- LSP Client for Emacs -*- lexical-binding: t; -*-
(unless (json-available-p)
(user-error "LSPCE needs JSON support in Emacs;
please rebuild it using `--with-json'"))
;;; Require
(require 'json)
(eval-when-compile
(require 'cl-lib))
(require 'project)
(require 'url-util)
(require 'compile) ; for some faces
(require 'warnings)
(ignore-errors
(require 'posframe-plus))
(require 'markdown-mode)
(require 'yasnippet)
(require 'flymake)
(require 'lspce-core)
(eval-and-compile
(require 'lspce-util))
(require 'lspce-langs)
;;; Code
(defface lspce-mode-line
'((t (:inherit font-lock-constant-face :weight bold)))
"Face for package-name in LSPCE's mode line.")
(defcustom lspce-send-changes-idle-time 0.5
"Don't tell server of changes before Emacs's been idle for this many seconds."
:group 'lspce
:type 'number)
(defcustom lspce-doc-tooltip-border-width 1
"The border width of lspce tooltip, default is 1 px."
:group 'lspce
:type 'integer)
(defcustom lspce-doc-tooltip-timeout 30
"The timeout of lspce tooltip show time, in seconds."
:group 'lspce
:type 'integer)
(defcustom lspce-completion-ignore-case t
"If non-nil, ignore case when completing."
:group 'lspce
:type 'boolean)
(defcustom lspce-enable-eldoc t
"If non-nil, enable eldoc."
:group 'lspce
:type 'boolean)
(defcustom lspce-eldoc-enable-hover t
"If non-nil, enable hover in eldoc."
:group 'lspce
:type 'boolean)
(defcustom lspce-eldoc-enable-signature t
"If non-nil, enable signature in eldoc."
:group 'lspce
:type 'boolean)
(defcustom lspce-enable-flymake t
"If non-nil, enable flymake."
:group 'lspce
:type 'boolean)
(defcustom lspce-enable-logging nil
"If non-nil, enable logging to file."
:group 'lspce
:type 'boolean)
(defcustom lspce-auto-enable-within-project t
"If non-nil, enable lspce when a file is opened
if lspce is running in current project."
:group 'lspce
:type 'boolean)
(defcustom lspce-completion-no-annotation nil
"If non-nil, do not display completion item's annotation."
:group 'lspce
:type 'boolean)
(defcustom lspce-show-log-level-in-modeline t
"If non-nil, show log level in modeline."
:group 'lspce
:type 'boolean)
(defcustom lspce-xref-append-implementations-to-definitions nil
"If non-nil, when finding definitions, also query implementations
and append them to definitions."
:group 'lspce
:type 'boolean)
(defcustom lspce-enable-imenu-index-function nil
"If non-nil, set `lspce-imenu-create' as `imenu-create-index-function'."
:group 'lspce
:type 'boolean)
(defcustom lspce-after-text-edit-hook '()
"Functions called after finishing text edits in a buffer.
When running hooks, current buffer is set to the buffer being edited."
:type 'hook)
(defcustom lspce-after-each-text-edit-hook '()
"Functions called after finishing each text edit in a buffer.
When running hooks, current buffer is set to the buffer being edited."
:type 'hook)
;;; Logging
(defvar lspce--log-level-text nil)
(defun lspce-get-log-level ()
"Get current log level."
(interactive)
(let ((ll (lspce-module-get-log-level)))
ll))
(defconst lspce--log-level-plist
'(0 "DISABLED" 1 "ERROR" 2 "INFO" 3 "TRACE" 4 "DEBUG"))
(defun lspce--refresh-log-level ()
(when lspce-show-log-level-in-modeline
(let* ((ll (lspce-module-get-log-level))
(ltext (plist-get lspce--log-level-plist ll)))
(setq lspce--log-level-text ltext)
nil)))
(defun lspce-disable-logging ()
"Disable logging"
(interactive)
(lspce-module-disable-logging)
(lspce--refresh-log-level))
(defun lspce-enable-logging ()
"Enable logging"
(interactive)
(lspce-module-enable-logging)
(lspce--refresh-log-level))
(defun lspce-set-log-level-error ()
"Set log level to error on rust code side."
(interactive)
(lspce-module-set-log-level 1)
(lspce--refresh-log-level))
(defun lspce-set-log-level-info ()
"Set log level to info on rust code side."
(interactive)
(lspce-module-set-log-level 2)
(lspce--refresh-log-level))
(defun lspce-set-log-level-trace ()
"Set log level to trace on rust code side."
(interactive)
(lspce-module-set-log-level 3)
(lspce--refresh-log-level))
(defun lspce-set-log-level-debug ()
"Set log level to debug on rust code side."
(interactive)
(lspce-module-set-log-level 4)
(lspce--refresh-log-level))
(defun lspce-set-log-file (filename)
(let ((dirname (f-dirname filename)))
(unless (file-exists-p dirname)
(f-mkdir-full-path dirname))
(lspce-module-set-log-file filename)))
(defun lspce--remove-overlays ()
(remove-overlays nil nil 'lspce--overlay t))
(defvar-local lspce--saved-bindings nil
"Bindings saved by `lspce--save-and-setq'.")
(defmacro lspce--save-and-rebind (symbol binding)
`(unless (not (boundp ',symbol))
(push (cons ',symbol (symbol-value ',symbol)) lspce--saved-bindings)
(setq-local ,symbol ,binding)))
(defun lspce--restore-bindings ()
(dolist (binding lspce--saved-bindings)
(set (make-local-variable (car binding)) (cdr binding))))
;;; Xref
(defun lspce-xref-backend () 'xref-lspce)
(cl-defstruct lspce--xref-item
(filename)
(start-pos)
(start-line)
(start-column)
(end-pos)
(end-line)
(end-column))
(defun lspce--location-before-p (left right)
"Sort first by file, then by line, then by column."
(let ((left-uri (lspce--xref-item-filename left))
(right-uri (lspce--xref-item-filename right))
(left-start-line (lspce--xref-item-start-line left))
(right-start-line (lspce--xref-item-start-line right))
(left-start-column (lspce--xref-item-start-column left))
(right-start-column (lspce--xref-item-start-column right)))
(if (not (string= left-uri right-uri))
(string< left-uri right-uri)
(if (= left-start-line right-start-line)
(< left-start-column right-start-column)
(< left-start-line right-start-line)))))
(defun lspce--lsp-position-to-point (pos &optional markers)
"Convert LSP position to Emacs point."
(let ((line (gethash "line" pos))
(character (gethash "character" pos)))
(save-excursion
(save-restriction
(widen)
(goto-char (point-min))
(forward-line line)
(unless (eobp) ;; if line was excessive leave point at eob
(let ((tab-width 1)
(col character))
(unless (wholenump col)
(lspce--warn
"LSP server sent invalid character position %s. Using 0 instead."
col)
(setq col 0))
(funcall lspce-move-to-column-function col)))
(if markers (copy-marker (point-marker)) (point))))))
(defun lspce--range-region (range &optional markers)
"Return region (BEG . END) that represents LSP RANGE.
If optional MARKERS, make markers."
(let* ((start (gethash "start" range))
(end (gethash "end" range))
(beg (lspce--lsp-position-to-point start markers))
(end (lspce--lsp-position-to-point end markers)))
(cons beg end)))
(defun lspce--locations-to-xref (locations)
(let (xrefs uri range start
end filename start-line start-column
end-line end-column items xref-items groups)
(cond
((arrayp locations)
(setq items locations)
)
((hash-table-p locations)
(setq items (list locations)))
((listp locations)
(setq items locations))
(t
(setq items nil)))
(condition-case err
(progn
(dolist (item items)
(setq uri (or (gethash "uri" item)
(gethash "targetUri" item)))
(setq range (or (gethash "range" item)
(gethash "targetSelectionRange" item)))
(setq start (gethash "start" range))
(setq end (gethash "end" range))
(setq start-line (gethash "line" start))
(setq start-column (gethash "character" start))
(setq end-line (gethash "line" end))
(setq end-column (gethash "character" end))
(if (string-prefix-p "jdt:\/\/" uri)
(setq filename (lspce--jdtls-open-jdt-link uri))
(setq filename (lspce--uri-to-path uri)))
(when filename
(cl-pushnew (make-lspce--xref-item :filename filename
:start-pos start
:start-line start-line
:start-column start-column
:end-pos end
:end-line end-line
:end-column end-column)
xref-items)))
(setq groups (seq-group-by
(lambda (x) (lspce--xref-item-filename x))
(seq-sort #'lspce--location-before-p xref-items)))
(dolist (group groups)
(let* ((filename (car group))
(items (cdr group))
(visiting (find-buffer-visiting filename))
(collect
(lambda (item)
(lspce--widening
(let* ((beg (lspce--lsp-position-to-point
(lspce--xref-item-start-pos item)))
(end (lspce--lsp-position-to-point
(lspce--xref-item-end-pos item)))
(bol (progn
(goto-char beg) (point-at-bol)))
(substring
(buffer-substring bol (point-at-eol)))
(hi-beg (- beg bol))
(hi-end (- (min (point-at-eol) end) bol)))
(add-face-text-property hi-beg hi-end
'xref-match t substring)
(cl-pushnew
(xref-make substring
(xref-make-file-location
filename
(+ (lspce--xref-item-start-line item) 1)
(lspce--xref-item-start-column item)))
xrefs))))))
(if visiting
(with-current-buffer visiting
(seq-map collect items))
(when (file-readable-p filename)
(with-temp-buffer
(insert-file-contents-literally filename)
(seq-map collect items)))))))
(error (lspce--warn "Failed to process xref entry for filename '%s': %s"
filename (error-message-string err)))
(file-error (lspce--warn "Failed to process xref entry, '%s': %s"
filename (error-message-string err))))
(nreverse xrefs)))
(cl-defmethod xref-backend-identifier-at-point ((_backend (eql xref-lspce)))
(propertize (or (thing-at-point 'symbol) "")
'identifier-at-point t))
(defun lspce--xref-dup-test (x1 x2)
(let* ((x1-location (xref-item-location x1))
(x1-file (xref-file-location-file x1-location))
(x1-line (xref-file-location-line x1-location))
(x1-column (xref-file-location-column x1-location))
(x2-location (xref-item-location x2))
(x2-file (xref-file-location-file x2-location))
(x2-line (xref-file-location-line x2-location))
(x2-column (xref-file-location-column x2-location)))
(and (string-equal x1-file x2-file)
(= x1-line x2-line)
(= x1-column x2-column))))
(cl-defmethod xref-backend-definitions ((_backend (eql xref-lspce)) identifier)
(let (defs
impls)
(save-excursion
(when (lspce--server-capable "definitionProvider")
(let* ((method "textDocument/definition")
(response (lspce--request method
(lspce--make-definitionParams))))
(when response
(setq defs (lspce--locations-to-xref response)))))
(when (and lspce-xref-append-implementations-to-definitions
(lspce--server-capable "implementationProvider"))
(let* ((method "textDocument/implementation")
(response (lspce--request method
(lspce--make-implementationParams))))
(when response
(setq impls (lspce--locations-to-xref response))))))
(cl-remove-duplicates (append defs impls) :test #'lspce--xref-dup-test)))
;; NOTE if you use `ivy-xref-show-xrefs' as the `xref-show-xrefs-function',
;; you will find `xref-backend-references' is called twice.
;; See https://github.com/alexmurray/ivy-xref/issues/2
(cl-defmethod xref-backend-references ((_backend (eql xref-lspce)) identifier)
(when (lspce--server-capable "referencesProvider")
(save-excursion
(let* ((method "textDocument/references")
(response (lspce--request method (lspce--make-referenceParams))))
(when response
(lspce--locations-to-xref response))))))
(cl-defmethod xref-backend-apropos ((_backend (eql xref-lspce)) pattern)
(when (lspce--server-capable "workspaceSymbolProvider")
(let* ((method "workspace/symbol")
(response (lspce--request
method
(lspce--make-workspaceSymbolParams pattern)))
location locations)
(when response
(dolist (symbol response)
(when-let ((location (gethash "location" symbol)))
(cl-pushnew location locations)))
(lspce--locations-to-xref locations)))))
(cl-defmethod xref-backend-identifier-completion-table
((_backend (eql xref-lspce)))
(list (propertize (or (thing-at-point 'symbol) "")
'identifier-at-point t)))
(when (not (fboundp 'xref-backend-implementations))
(cl-defgeneric xref-backend-implementations (backend identifier)
"Find implementations of IDENTIFIER.
The result must be a list of xref objects. If there are multiple possible
implementations, return all of them. If no implementations can be found,
return nil.
IDENTIFIER can be any string returned by
`xref-backend-identifier-at-point', or from the table returned by
`xref-backend-identifier-completion-table'.
To create an xref object, call `xref-make'.")
)
(cl-defmethod xref-backend-implementations
((_backend (eql xref-lspce)) identifier)
(when (lspce--server-capable "implementationProvider")
(save-excursion
(let* ((method "textDocument/implementation")
(response (lspce--request method
(lspce--make-implementationParams))))
(when response
(lspce--locations-to-xref response))))))
;;;###autoload
(defun xref-find-implementations (identifier)
"Find implementations to the identifier at point.
This command might prompt for the identifier as needed, perhaps
offering the symbol at point as the default.
With prefix argument, or if `xref-prompt-for-identifier' is t,
always prompt for the identifier. If `xref-prompt-for-identifier'
is nil, prompt only if there's no usable symbol at point."
(interactive (list (xref--read-identifier "Find implementations of: ")))
(xref--find-xrefs identifier 'implementations identifier nil))
;; type definition
(when (not (fboundp 'xref-backend-type-definition))
(cl-defgeneric xref-backend-type-definition (backend identifier)
"Find type definition of IDENTIFIER.
The result must be a list of xref objects.
If no type definition can be found, return nil.
IDENTIFIER can be any string returned by
`xref-backend-identifier-at-point', or from the table returned by
`xref-backend-identifier-completion-table'.
To create an xref object, call `xref-make'.")
)
(cl-defmethod xref-backend-type-definition
((_backend (eql xref-lspce)) identifier)
(when (lspce--server-capable "typeDefinitionProvider")
(save-excursion
(let* ((method "textDocument/typeDefinition")
(response (lspce--request
method
(lspce--make-typeDefinitionParams))))
(when response
(lspce--locations-to-xref response))))))
;;;###autoload
(defun xref-find-type-definition (identifier)
"Find type definition to the IDENTIFIER at point.
This command might prompt for the identifier as needed, perhaps
offering the symbol at point as the default.
With prefix argument, or if `xref-prompt-for-identifier' is t,
always prompt for the identifier. If `xref-prompt-for-identifier'
is nil, prompt only if there's no usable symbol at point."
(interactive (list (xref--read-identifier "Find Type Definition of: ")))
(xref--show-defs
(xref--create-fetcher identifier 'type-definition identifier)
nil))
;; declaration
(when (not (fboundp 'xref-backend-declaration))
(cl-defgeneric xref-backend-declaration (backend identifier)
"Find declaration of IDENTIFIER.
The result must be a list of xref objects. If there are multiple possible
declarations, return all of them. If no declaration can be found,
return nil.
IDENTIFIER can be any string returned by
`xref-backend-identifier-at-point', or from the table returned by
`xref-backend-identifier-completion-table'.
To create an xref object, call `xref-make'.")
)
(cl-defmethod xref-backend-declaration ((_backend (eql xref-lspce)) identifier)
(when (lspce--server-capable "declarationProvider")
(save-excursion
(let* ((method "textDocument/declaration")
(response (lspce--request method (lspce--make-declarationParams))))
(when response
(lspce--locations-to-xref response))))))
;;;###autoload
(defun xref-find-declaration (identifier)
"Find declaration to the IDENTIFIER at point.
This command might prompt for the identifier as needed, perhaps
offering the symbol at point as the default.
With prefix argument, or if `xref-prompt-for-identifier' is t,
always prompt for the identifier. If `xref-prompt-for-identifier'
is nil, prompt only if there's no usable symbol at point."
(interactive (list (xref--read-identifier "Find Definition of: ")))
(xref--show-defs
(xref--create-fetcher identifier 'declaration identifier)
nil))
;;; Capf
(defvar-local lspce--completion-complete? nil) ;; 1 incomplete 2 complete
(defvar-local lspce--last-inserted-char nil
"If non-nil, value of the last inserted character in buffer.")
(defvar lspce--completion-cache nil
"Cached candidates for completion at point function.
In the form of plist (prefix-start-pos items :lsp-items :markers :prefix ...).
When the completion is incomplete, `items' contains value of :incomplete.")
(defvar lspce--completion-last-result nil
"Last completion result.")
(defun lspce--completion-clear-cache (&optional keep-last-result)
"Clear completion caches, and last result if KEEP-LAST-RESULT not specified."
(let ((markers (and lspce--completion-cache
(lspce-completionCache-markers lspce--completion-cache))))
(when markers
(setq markers (list (cl-first markers)
(set-marker (cl-second markers) nil)))
(setf (lspce-completionCache-markers lspce--completion-cache) markers)))
(setq lspce--completion-cache nil)
(unless keep-last-result
(setq lspce--completion-last-result nil)))
(defun lspce--post-self-insert-hook ()
"Set `lspce--last-inserted-char'."
(setq lspce--last-inserted-char last-input-event))
(defun lspce--pre-command-hook ()
"Reset `lspce--last-inserted-char'."
(setq lspce--last-inserted-char nil))
(defun lspce--make-completionContext ()
(let ((trigger (and (characterp lspce--last-inserted-char)
(cl-find lspce--last-inserted-char
(lspce--server-capable-chain "completionProvider"
"triggerCharacters")
:key (lambda (str) (aref str 0))
:test #'char-equal))))
(if trigger
(lspce--completionContext LSPCE-TriggerCharacter trigger)
(if (and lspce--completion-complete? (= lspce--completion-complete? 1))
(lspce--completionContext LSPCE-TriggerForIncompleteCompletions nil)
(lspce--completionContext LSPCE-Invoked nil)))))
(defvar lspce--in-completion-p nil)
(cl-defun lspce--request-completion ()
(setq lspce--in-completion-p t)
(condition-case err
(let* ((method "textDocument/completion")
(params (lspce--make-completionParams))
(response (lspce--request method params))
items complete?)
(setq lspce--in-completion-p nil)
(unless response
(lspce--debug "lspce--request-completion failed to getting response")
(cl-return-from lspce--request-completion nil))
(lspce--debug "lspce--request-completion response: %S" response)
(lspce--debug "lspce--request-completion response type-of: %s"
(type-of response))
(cond
((listp response)
(setq complete? t
items response))
((hash-table-p response)
(setq complete? (not (gethash "isIncomplete" response))
items (gethash "items" response)))
(t
(lspce--warn "Unknown response type: %s" (type-of response))
(cl-return-from lspce--request-completion nil)))
(list complete? items))
((error quit)
(lspce--error "lspce--request-completion error: [%s]" err)
(setq lspce--in-completion-p nil)
nil)))
(defun lspce--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)
'lspce--expand-snippet))
(defun lspce--completion-resolve (item)
(when (and
(lspce--server-capable-chain "completionProvider" "resolveProvider")
(gethash "data" item))
(lspce--request "completionItem/resolve" item)))
(defun lspce--format-markup (markup)
"Format MARKUP according to LSP's spec."
(pcase-let ((`(,string ,mode)
(if (stringp markup) (list markup 'gfm-view-mode)
(list (gethash "value" markup)
(pcase (gethash "kind" markup)
("markdown" 'gfm-view-mode)
("plaintext" 'text-mode)
(_ major-mode))))))
(with-temp-buffer
(setq-local markdown-fontify-code-blocks-natively t)
(insert string)
(let ((inhibit-message t)
(message-log-max nil))
(ignore-errors (delay-mode-hooks (funcall mode))))
(font-lock-ensure)
(string-trim (buffer-string)))))
(defun lspce--completion-looking-back-trigger (trigger-characters)
"Return trigger character if text before point
matches any of the TRIGGER-CHARACTERS."
(unless (= (point) (point-at-bol))
(seq-some
(lambda (trigger-char)
(and (equal (buffer-substring-no-properties
(- (point) (length trigger-char)) (point))
trigger-char)
trigger-char))
trigger-characters)))
(defun lspce--completion-bounds-start (start trigger-chars)
(let ((bounds-start (point)))
(when start
(setq bounds-start (save-excursion
(ignore-errors
(goto-char (+ start 1))
(while (lspce--completion-looking-back-trigger
trigger-chars)
(cl-incf start)
(forward-char))
start))))
bounds-start))
(defun lspce-completion-at-point()
(when-let (completion-capability (lspce--server-capable "completionProvider"))
(let* ((trigger-chars (lspce--server-capable-chain "completionProvider"
"triggerCharacters"))
(bounds (bounds-of-thing-at-point 'symbol))
(bounds-start (lspce--completion-bounds-start
(cl-first bounds) trigger-chars))
(sort-completions
(lambda (completions)
(cl-sort completions
#'string-lessp
:key (lambda (c)
(or (gethash
"sortText"
(get-text-property 0 'lspce--lsp-item c))
"")))))
done?
(cached-proxies :none)
(proxies
(lambda ()
(let* ((same-session?
(and lspce--completion-cache
;; Special case for empty prefix and empty result
(or (lspce-completionCache-candidates lspce--completion-cache)
(not (string-empty-p
(lspce-completionCache-prefix lspce--completion-cache))))
(equal
(lspce-completionCache-prefix-start lspce--completion-cache) bounds-start)
(string-prefix-p
(lspce-completionCache-prefix lspce--completion-cache)
(buffer-substring-no-properties bounds-start (point)))))
(old-cached-proxies
(and same-session?
lspce--completion-cache
(lspce-completionCache-candidates lspce--completion-cache))))
(if same-session?
(lspce--debug "same-session")
(lspce--debug "not same-session"))
(cond
((or done? (listp cached-proxies))
(lspce--debug "use cached-proxies")
cached-proxies)
((and same-session?
old-cached-proxies
(listp old-cached-proxies))
(lspce--debug "use old cached-proxies")
(setq cached-proxies old-cached-proxies))
(t
(let* ((completions (lspce--request-completion))
(complete? (nth 0 completions))
(items (nth 1 completions))
(markers (list bounds-start (copy-marker (point) t)))
(prefix (buffer-substring-no-properties bounds-start (point))))
(if completions
(progn
(if complete?
(setq-local lspce--completion-complete? 2)
(setq-local lspce--completion-complete? 1))
(setq cached-proxies
(mapcar
(lambda (item)
(let* ((label (gethash "label" item))
(insertTextFormat (or (gethash "insertTextFormat" item) 1))
(insertText (gethash "insertText" item))
(proxy
(cond
((and (eql insertTextFormat 2)
(lspce--snippet-expansion-fn))
(string-trim-left label))
((and insertText
(not (string-empty-p insertText)))
insertText)
(t
(string-trim-left label)))))
(unless (zerop (length proxy))
(put-text-property 0 1 'lspce--lsp-item item proxy)
(put-text-property 0 1 'lspce--lsp-markers markers proxy)
(put-text-property 0 1 'lspce--lsp-start bounds-start proxy)
(put-text-property 0 1 'lspce--lsp-prefix prefix proxy))
proxy))
items))
(lspce--completion-clear-cache same-session?)
(setq done? complete?)
(setq lspce--completion-cache
(make-lspce-completionCache :prefix-start bounds-start
:candidates (cond
((and done?
(not (seq-empty-p cached-proxies)))
cached-proxies)
((not done?)
:incomplete))
:lsp-items nil
:markers markers
:prefix prefix))
(setq lspce--completion-last-result cached-proxies))
(when same-session?
lspce--completion-last-result))))))))
(resolved (make-hash-table))
(resolve-maybe (lambda (lsp-item)
(or (gethash lsp-item resolved)
(setf (gethash lsp-item resolved)
(or (lspce--completion-resolve lsp-item) lsp-item))))))
(list
bounds-start
(point)
(lambda (probe pred action)
(let (collection)
(cond
((eq action 'metadata) `(metadata (category . lspce-capf)
(display-sort-function . ,sort-completions)
(cycle-sort-function . identity))) ; metadata
((eq (car-safe action) 'boundaries) nil) ; boundaries
;; test-completion: not return exact match so that the selection will
;; always be shown
((eq action 'lambda) ; test-completion
nil)
((null action) ; try-completion
(setq collection (funcall proxies))
(try-completion probe collection))
((eq action t) ; all-completions
(setq collection (funcall proxies))
(all-completions
probe
collection
(lambda (proxy)
(let* ((item (get-text-property 0 'lspce--lsp-item proxy))
(filterText (gethash "filterText" item)))
(and (or (null pred) (funcall pred proxy))
(string-prefix-p
probe (or filterText proxy) lspce-completion-ignore-case)))))))))
:annotation-function
(lambda (proxy)
(unless lspce-completion-no-annotation
(let* ((item (get-text-property 0 'lspce--lsp-item proxy))
(detail (gethash "detail" item))
(kind (gethash "kind" item))
annotation)
(setq detail (and (stringp detail)
(not (string-empty-p detail))
detail))
(setq annotation (or detail
(cdr (assoc kind lspce--kind-names))))
(when annotation
(concat " "
(propertize annotation
'face 'font-lock-function-name-face))))))
:company-require-match 'never
:company-kind
;; Associate each lsp-item with a lsp-kind symbol.
(lambda (proxy)
(when-let* ((lsp-item (get-text-property 0 'lspce--lsp-item proxy))
(kind (alist-get (gethash "kind" lsp-item)
lspce--kind-names)))
(intern (downcase kind))))
:company-deprecated
(lambda (proxy)
(let ((lsp-item (get-text-property 0 'lspce--lsp-item proxy))
tags deprecated)
(setq tags (gethash "tags" lsp-item)
deprecated (gethash "deprecated" lsp-item))
(or (seq-contains-p tags 1)
(eq t deprecated))))
:company-doc-buffer
(lambda (proxy)
(let* ((documentation
(let* ((lsp-item (get-text-property 0 'lspce--lsp-item proxy))
(resolve (funcall resolve-maybe lsp-item)))
(when resolve
(gethash "documentation" resolve))))
(formatted (and documentation
(lspce--format-markup documentation))))
(when formatted
(with-current-buffer (get-buffer-create " *lspce doc*")
(erase-buffer)
(insert formatted)
(current-buffer)))))
:company-prefix-length
(save-excursion
(when (car bounds)
(goto-char (car bounds)))
(when (hash-table-p completion-capability)
(looking-back
(regexp-opt
(cl-coerce (gethash "triggerCharacters" completion-capability) 'list))
(line-beginning-position))))
:exit-function
(lambda (proxy status)
(when (memq status '(finished exact))
(let ((inhibit-redisplay t))
(with-current-buffer (if (minibufferp)
(window-buffer (minibuffer-selected-window))
(current-buffer))
(setq-local lspce--completion-complete? nil)
(let* ((proxy (if (plist-member (text-properties-at 0 proxy) 'lspce--lsp-item)
proxy
(cl-find proxy (funcall proxies) :test #'equal)))
(lsp-item (funcall resolve-maybe (get-text-property 0 'lspce--lsp-item proxy)))
(lsp-markers (get-text-property 0 'lspce--lsp-markers proxy))
(lsp-prefix (get-text-property 0 'lspce--lsp-prefix proxy))
(lsp-start (get-text-property 0 'lspce--lsp-start proxy))
(insertTextFormat (or (gethash "insertTextFormat" lsp-item) 1))
(insertText (gethash "insertText" lsp-item))
(label (gethash "label" lsp-item))
(textEdit (gethash "textEdit" lsp-item))
(additionalTextEdits (gethash "additionalTextEdits" lsp-item))
(snippet-fn (and (eql insertTextFormat 2)
(lspce--snippet-expansion-fn))))
(lspce--debug "lsp-item %S" (json-encode lsp-item))
(cond (textEdit
(let* ((range (gethash "range" textEdit))
(newText (gethash "newText" textEdit))
(old-text (apply #'buffer-substring-no-properties lsp-markers))
(region (lspce--range-region range)))
(if (and (length> old-text 0)
(string-prefix-p old-text newText))
(progn
(funcall (or snippet-fn #'insert) (substring newText (length old-text))))
(progn
(lspce--debug "lsp-markers: %s, markers: %s"
lsp-markers
(apply #'buffer-substring-no-properties lsp-markers))
(lspce--debug "lsp-prefix: %s" lsp-prefix)
(lspce--debug "region: %s, region: %s"
region
(buffer-substring-no-properties (car region) (cdr region)))
(apply #'delete-region lsp-markers)
(insert lsp-prefix)
(delete-region (car region) (cdr region))
(goto-char (car region))
(funcall (or snippet-fn #'insert) newText))))
(when (cl-plusp (length additionalTextEdits))
(lspce--apply-text-edits additionalTextEdits)))
(snippet-fn
;; A snippet should be inserted, but using plain
;; `insertText' or `label'. This requires us to delete the
;; whole completion, since `insertText' or `label' is the full
;; completion's text.
(let* ((newText (or insertText label))
(old-text (apply #'buffer-substring-no-properties lsp-markers)))
(if (and (string-prefix-p old-text newText))
(progn
(funcall snippet-fn (substring newText (length old-text))))
(apply #'delete-region lsp-markers)
(insert lsp-prefix)
(delete-region lsp-start (point))
(funcall snippet-fn (or insertText label)))))))
(lspce--completion-clear-cache)
(lspce--notify-textDocument/didChange)))))))))
;;; imenu
(defun lspce-imenu-create ()
(cl-labels
((unfurl (obj)
(if-let ((children (gethash "children" obj))
(name (gethash "name" obj)))
(cons obj
(mapcar (lambda (c)
(puthash
"containerName"
(let ((existing (gethash "containerName" c)))
(if existing (format "%s::%s" name existing)
name)) c) c)
(mapcan #'unfurl children)))
(list obj))))
(when (lspce--server-capable-chain "documentSymbolProvider")
(mapcar
(lambda (obj)
(cons
(cdr (assoc (car obj) lspce--symbol-kind-names))
(mapcar
(lambda (obj)
(let ((content
(cons (gethash "name" obj)
(lspce--lsp-position-to-point
(gethash "start"
(if-let ((range (gethash "selectionRange" obj)))
range
(gethash "range" (gethash "location" obj)))))))
(container (gethash "containerName" obj)))
(if container (list container content)
content)))
(cdr obj))))
(seq-group-by
(lambda (obj) (gethash "kind" obj))
(mapcan #'unfurl
(lspce--request "textDocument/documentSymbol" (list :textDocument (lspce--textDocumentIdenfitier (lspce--uri))))))))))
;;; hover
(defvar lspce--doc-buffer-name "*lspce-hover*")
(defvar lspce--doc-max-width 100)
(defvar lspce--doc-max-height 30)
(defun lspce--display-help (kind content)
(let* ((theme-mode (format "%s" (frame-parameter nil 'background-mode)))
(background-color (if (string-equal theme-mode "dark")
"#191a1b"
"#f0f0f0"))
(height 1)
(lines 1))
(with-current-buffer (get-buffer-create lspce--doc-buffer-name)
(read-only-mode -1)
(erase-buffer)
(setq-local markdown-fontify-code-blocks-natively t)
(insert content)
(if (fboundp 'gfm-view-mode)
(let ((view-inhibit-help-message t))
(gfm-view-mode))
(gfm-mode))
(font-lock-ensure)
(save-excursion
(goto-char (point-max))
(setq lines (line-number-at-pos))
(if (> lines height)
(setq height (min lines lspce--doc-max-height)))))
(if (and (fboundp #'posframe-workable-p)
(posframe-workable-p)
(fboundp #'posframe-plus-show))
(posframe-plus-show lspce--doc-buffer-name t t
:position (point)
:timeout lspce-doc-tooltip-timeout
:internal-border-color "orange"
:internal-border-width lspce-doc-tooltip-border-width
:background-color background-color
:accept-focus nil
:width lspce--doc-max-width
:height height
:left-fringe 10
:right-fringe 10)
(switch-to-buffer-other-window lspce--doc-buffer-name))))
(defun lspce-help-at-point ()
"Show document of the symbol at the point using LSP's hover."
(interactive)
(if lspce-mode
(let ((hover-info (lspce--hover-at-point)))
(when hover-info
(lspce--display-help (nth 0 hover-info) (nth 1 hover-info))))
(user-error "Lspce mode is not enabled yet.")))
(defun lspce--hover-at-point ()
"Show document of the symbol at the point using LSP's hover."
(when (and
(not lspce--in-completion-p)
(lspce--server-capable-chain "hoverProvider"))
(let* ((method "textDocument/hover")
(params (lspce--make-hoverParams))
(response (lspce--request method params))
contents kind content language hover-info)
(when response
(setq contents (gethash "contents" response))
(cond
((hash-table-p contents)
(setq kind (gethash "kind" contents))
(setq language (gethash "language" contents))
(setq content (gethash "value" contents))
(when (and (null kind)
language)
(setq kind "markdown"
content (concat "```" language "\n" content "\n```")))
(when (and kind content)