forked from emacs-lsp/lsp-mode
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlsp-mode.el
4958 lines (4370 loc) · 209 KB
/
lsp-mode.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
;;; lsp-mode.el --- LSP mode -*- lexical-binding: t; -*-
;; Copyright (C) 2018 Vibhav Pant, Ivan Yonchovski
;; Author: Vibhav Pant, Fangrui Song, Ivan Yonchovski
;; Keywords: languages
;; Package-Requires: ((emacs "25.1") (dash "2.14.1") (dash-functional "2.14.1") (f "0.20.0") (ht "2.0") (spinner "1.7.3") (markdown-mode "2.3"))
;; Version: 6.0
;; 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 <https://www.gnu.org/licenses/>.
;;; Commentary:
;;
;;; Code:
(unless (version< emacs-version "26")
(require 'project)
(require 'flymake))
(require 'cl-lib)
(require 'compile)
(require 'dash)
(require 'dash-functional)
(require 'em-glob)
(require 'f)
(require 'filenotify)
(require 'files)
(require 'ht)
(require 'imenu)
(require 'inline)
(require 'json)
(require 'network-stream)
(require 'pcase)
(require 'seq)
(require 'spinner)
(require 'subr-x)
(require 'url-parse)
(require 'url-util)
(require 'widget)
(require 'xref)
(require 'tree-widget)
(require 'markdown-mode)
(declare-function company-mode "company")
(declare-function flycheck-mode "flycheck")
(declare-function lsp-ui-flycheck-enable "lsp-ui")
(declare-function evil-set-command-property "evil")
(declare-function projectile-project-root "projectile")
(defconst lsp--message-type-face
`((1 . ,compilation-error-face)
(2 . ,compilation-warning-face)
(3 . ,compilation-message-face)
(4 . ,compilation-info-face)))
(defconst lsp--errors
'((-32700 "Parse Error")
(-32600 "Invalid Request")
(-32601 "Method not Found")
(-32602 "Invalid Parameters")
(-32603 "Internal Error")
(-32099 "Server Start Error")
(-32000 "Server End Error")
(-32002 "Server Not Initialized")
(-32001 "Unknown Error Code")
(-32800 "Request Cancelled"))
"Alist of error codes to user friendly strings.")
(defconst lsp--completion-item-kind
[nil
"Text"
"Method"
"Function"
"Constructor"
"Field"
"Variable"
"Class"
"Interface"
"Module"
"Property"
"Unit"
"Value"
"Enum"
"Keyword"
"Snippet"
"Color"
"File"
"Reference"
"Folder"
"EnumMember"
"Constant"
"Struct"
"Event"
"Operator"
"TypeParameter"])
(defcustom lsp-print-io nil
"If non-nil, print all messages to and from the language server to *lsp-log*."
:group 'lsp-mode
:type 'boolean)
(defcustom lsp-trace nil
"If non-nil, keep a trace of all messages to and from the language server."
:group 'lsp-mode
:type 'boolean)
(defcustom lsp-print-performance nil
"If non-nil, print performance info in the logs."
:group 'lsp-mode
:type 'boolean)
(defcustom lsp-use-native-json t
"If non-nil, use native json parsing if available."
:group 'lsp-mode
:type 'boolean)
(defcustom lsp-json-use-lists nil
"If non-nil, use lists instead of vectors when doing json deserialization."
:group 'lsp-mode
:type 'boolean)
(defcustom lsp-log-max message-log-max
"Maximum number of lines to keep in the log buffer.
If nil, disable message logging. If t, log messages but don’t truncate
the buffer when it becomes large."
:group 'lsp-mode
:type '(choice (const :tag "Disable" nil)
(integer :tag "lines")
(const :tag "Unlimited" t)))
(defcustom lsp-report-if-no-buffer t
"If non nil the errors will be reported even when the file is not open."
:type 'boolean
:group 'lsp-mode)
(defcustom lsp-keep-workspace-alive t
"If non nil keep workspace alive when the last workspace buffer is closed."
:group 'lsp-mode
:type 'boolean)
(defcustom lsp-enable-snippet t
"Enable/disable snippet completion support."
:group 'lsp-mode
:type 'boolean)
(defcustom lsp-enable-folding t
"Enable/disable code folding support."
:group 'lsp-mode
:type 'boolean)
(defcustom lsp-folding-range-limit nil
"The maximum number of folding ranges to receive from the language server."
:group 'lsp-mode
:type '(choice (const :tag "No limit." nil)
(integer :tag "Number of lines.")))
(defcustom lsp-folding-line-folding-only nil
"If non-nil, only fold complete lines."
:group 'lsp-mode
:type 'boolean)
(defcustom lsp-auto-require-clients t
"Auto require lsp-clients."
:group 'lsp-mode
:type 'boolean)
(defvar-local lsp--cur-workspace nil)
(defvar-local lsp--cur-version nil)
(defvar lsp--uri-file-prefix (pcase system-type
(`windows-nt "file:///")
(_ "file://"))
"Prefix for a file-uri.")
(defvar-local lsp-buffer-uri nil
"If set, return it instead of calculating it using `buffer-file-name'.")
(define-error 'lsp-error "Unknown lsp-mode error")
(define-error 'lsp-empty-response-error
"Empty response from the language server" 'lsp-error)
(define-error 'lsp-timed-out-error
"Timed out while waiting for a response from the language server" 'lsp-error)
(define-error 'lsp-capability-not-supported
"Capability not supported by the language server" 'lsp-error)
(define-error 'lsp-file-scheme-not-supported
"Unsupported file scheme" 'lsp-error)
(defcustom lsp-auto-guess-root nil
"Automatically guess the project root using projectile/project."
:group 'lsp-mode
:type 'boolean)
(defcustom lsp-restart 'interactive
"Defines how server exited event must be handled."
:group 'lsp-mode
:type '(choice (const interactive)
(const auto-restart)
(const ignore)))
(defcustom lsp-session-file (expand-file-name (locate-user-emacs-file ".lsp-session-v1"))
"Automatically guess the project root using projectile/project."
:group 'lsp-mode
:type 'file)
(defcustom lsp-auto-configure t
"Auto configure `lsp-mode'.
When set to t `lsp-mode' will auto-configure `lsp-ui' and `company-lsp'."
:group 'lsp-mode
:type 'boolean)
(defvar lsp-clients (make-hash-table :test 'eql)
"Hash table server-id -> client.
It contains all of the clients that are currently registered.")
(defvar lsp-last-id 0
"Last request id.")
(defcustom lsp-before-initialize-hook nil
"List of functions to be called before a Language Server has been initialized for a new workspace."
:type 'hook
:group 'lsp-mode)
(defcustom lsp-before-open-hook nil
"List of functions to be called before a new file with LSP support is opened."
:type 'hook
:group 'lsp-mode)
(defcustom lsp-after-open-hook nil
"List of functions to be called after a new file with LSP support is opened."
:type 'hook
:group 'lsp-mode)
(defcustom lsp-enable-file-watchers t
"If non-nil lsp-mode will watch the files in the workspace if
the server has requested that."
:type 'boolean
:group 'lsp-mode)
(defcustom lsp-file-watch-ignored '(".idea"
".ensime_cache"
".eunit"
"node_modules"
".git"
".hg"
".fslckout"
"_FOSSIL_"
".bzr"
"_darcs"
".tox"
".svn"
".stack-work"
".bloop"
".metals"
"target")
"List of directories which won't be monitored when creating file watches."
:group 'lsp-mode
:type '(repeat string))
(defcustom lsp-after-uninitialized-hook nil
"List of functions to be called after a Language Server has been uninitialized."
:type 'hook
:group 'lsp-mode)
(defvar lsp--sync-methods
'((0 . none)
(1 . full)
(2 . incremental)))
(defcustom lsp-debounce-full-sync-notifications t
"If non-nil debounce full sync events.
This flag affects only server which do not support incremental update."
:type 'boolean
:group 'lsp-mode)
(defcustom lsp-debounce-full-sync-notifications-interval 1.0
"Time to wait before sending full sync synchronization after buffer modication."
:type 'float
:group 'lsp-mode)
(defvar lsp--delayed-requests nil)
(defvar lsp--delay-timer nil)
(defvar-local lsp--server-sync-method nil
"Sync method recommended by the server.")
(defgroup lsp-mode nil
"Language Server Protocol client."
:group 'tools
:tag "Language Server")
(defgroup lsp-faces nil
"Faces."
:group 'lsp-mode
:tag "Faces")
(defcustom lsp-document-sync-method nil
"How to sync the document with the language server."
:type '(choice (const :tag "Documents should not be synced at all." 'none)
(const :tag "Documents are synced by always sending the full content of the document." 'full)
(const :tag "Documents are synced by always sending incremental changes to the document." 'incremental)
(const :tag "Use the method recommended by the language server." nil))
:group 'lsp-mode)
(defcustom lsp-auto-execute-action t
"Auto-execute single action."
:type 'boolean
:group 'lsp-mode)
(defcustom lsp-enable-links t
"If non-nil, all references to links in a file will be made clickable, if supported by the language server."
:type 'boolean
:group 'lsp-mode)
(defcustom lsp-links-check-internal 0.1
"The interval for updating document links."
:group 'lsp-mode
:type 'float)
(defcustom lsp-eldoc-enable-hover t
"If non-nil, eldoc will display hover info when it is present."
:type 'boolean
:group 'lsp-mode)
(defcustom lsp-eldoc-enable-signature-help t
"If non-nil, eldoc will display signature help when it is present."
:type 'boolean
:group 'lsp-mode)
(defcustom lsp-eldoc-prefer-signature-help t
"If non-nil, eldoc will display signature help when both hover and signature help are present."
:type 'boolean
:group 'lsp-mode)
(defcustom lsp-eldoc-render-all nil
"Define whether all of the returned by document/onHover will be displayed.
If `lsp-eldoc-render-all' is set to nil `eldoc' will show only
the symbol information."
:type 'boolean
:group 'lsp-mode)
(defcustom lsp-enable-completion-at-point t
"Enable `completion-at-point' integration."
:type 'boolean
:group 'lsp-mode)
(defcustom lsp-enable-symbol-highlighting t
"Highlight references of the symbol at point."
:type 'boolean
:group 'lsp-mode)
(defcustom lsp-enable-xref t
"Enable xref integration."
:type 'boolean
:group 'lsp-mode)
(defcustom lsp-enable-indentation t
"Indent regions using the file formatting functionality provided by the language server."
:type 'boolean
:group 'lsp-mode)
(defcustom lsp-enable-on-type-formatting t
"Enable `textDocument/onTypeFormatting' integration."
:type 'boolean
:group 'lsp-mode)
(defcustom lsp-before-save-edits t
"If non-nil, `lsp-mode' will apply edits suggested by the language server before saving a document."
:type 'boolean
:group 'lsp-mode)
(defcustom lsp-after-diagnostics-hook nil
"Hooks to run after diagnostics are received."
:type 'hook
:group 'lsp-mode)
(defconst lsp--sync-type
`((0 . "None")
(1 . "Full Document")
(2 . "Incremental Changes")))
(defcustom lsp-workspace-folders-changed-hook nil
"Hooks to run after the folders has changed.
The hook will receive two parameters list of added and removed folders."
:type 'hook
:group 'lsp-mode)
(defcustom lsp-on-hover-hook nil
"The hooks that run after on hover and signature information has been loaded.
The hook is called with two params: the signature information and hover data."
:type 'hook
:group 'lsp-mode)
(defcustom lsp-eldoc-hook '(lsp-hover)
"Hooks to run for eldoc."
:type 'hook
:group 'lsp-mode)
(defgroup lsp-imenu nil
"Imenu."
:group 'lsp-mode
:tag "Imenu")
(defcustom lsp-imenu-show-container-name t
"Display the symbol's container name in an imenu entry."
:type 'boolean
:group 'lsp-imenu)
(defcustom lsp-imenu-container-name-separator "/"
"Separator string to use to separate the container name from the symbol while displaying imenu entries."
:type 'string
:group 'lsp-imenu)
(defcustom lsp-imenu-sort-methods '(kind name)
"How to sort the imenu items.
The value is a list of `kind' `name' or `position'. Priorities
are determined by the index of the element."
:type '(repeat (choice (const name)
(const position)
(const kind))))
;; vibhavp: Should we use a lower value (5)?
(defcustom lsp-response-timeout 10
"Number of seconds to wait for a response from the language server before timing out."
:type 'number
:group 'lsp-mode)
(defconst lsp--imenu-compare-function-alist
(list (cons 'name #'lsp--imenu-compare-name)
(cons 'kind #'lsp--imenu-compare-kind)
(cons 'position #'lsp--imenu-compare-position))
"An alist of (METHOD . FUNCTION).
METHOD is one of the symbols accepted by
`lsp-imenu-sort-methods'.
FUNCTION takes two hash tables representing DocumentSymbol. It
returns a negative number, 0, or a positive number indicating
whether the first parameter is less than, equal to, or greater
than the second parameter.")
(defcustom lsp-prefer-flymake t
"Auto-configure to prefer `flymake' over `lsp-ui' if both are present.
If set to `:none' neither of two will be enabled."
:type '(choice (const :tag "Prefer flymake" t)
(const :tag "Prefer lsp-ui" nil)
(const :tag "Use neither flymake nor lsp-ui" :none))
:group 'lsp-mode)
(defvar-local lsp--flymake-report-fn nil)
(defvar lsp-language-id-configuration '((".*.vue" . "vue")
(java-mode . "java")
(python-mode . "python")
(lsp--render-markdown . "markdown")
(rust-mode . "rust")
(kotlin-mode . "kotlin")
(css-mode . "css")
(less-mode . "less")
(less-css-mode . "less")
(sass-mode . "sass")
(scss-mode . "scss")
(xml-mode . "xml")
(c-mode . "c")
(c++-mode . "cpp")
(objc-mode . "objective-c")
(web-mode . "html")
(html-mode . "html")
(sgml-mode . "html")
(mhtml-mode . "html")
(go-mode . "go")
(haskell-mode . "haskell")
(php-mode . "php")
(json-mode . "json")
(rjsx-mode . "javascript")
(js2-mode . "javascript")
(typescript-mode . "typescript")
(reason-mode . "reason")
(caml-mode . "ocaml")
(tuareg-mode . "ocaml")
(swift-mode . "swift")
(elixir-mode . "elixir")
(conf-javaprop-mode . "spring-boot-properties")
(yaml-mode . "spring-boot-properties-yaml")
(ruby-mode . "ruby")
(enh-ruby-mode . "ruby")
(f90-mode . "fortran"))
"Language id configuration.")
(defvar lsp-method-requirements
'(("textDocument/onTypeFormatting" :capability "documentOnTypeFormattingProvider")
("workspace/executeCommand"
:capability "executeCommandProvider"
:registered-capability "workspace/executeCommand")
("textDocument/hover" :capability "hoverProvider")
("textDocument/documentSymbol" :capability "documentSymbolProvider")
("textDocument/documentHighlight" :capability "documentHighlightProvider")
("textDocument/definition" :capability "definitionProvider")
("workspace/symbol" :capability "workspaceSymbolProvider")
("textDocument/prepareRename"
:check-command (lambda (workspace)
(with-lsp-workspace workspace
(let ((table (lsp--capability "renameProvider")))
(and (hash-table-p table)
(gethash "prepareProvider" table)))))))
"Contain method to requirements mapping.
It is used by send request functions to determine which server
must be used for handling a particular message.")
(defconst lsp--file-change-type
`((created . 1)
(changed . 2)
(deleted . 3)))
(defface lsp-face-highlight-textual
'((t :inherit highlight))
"Face used for textual occurances of symbols."
:group 'lsp-faces)
(defface lsp-face-highlight-read
'((t :inherit highlight :underline t))
"Face used for highlighting symbols being read."
:group 'lsp-faces)
(defface lsp-face-highlight-write
'((t :inherit highlight :italic t))
"Face used for highlighting symbols being written to."
:group 'lsp-faces)
(defcustom lsp-lens-check-interval 0.1
"The interval for checking for changes in the buffer state."
:group 'lsp-mode
:type 'boolean)
(defcustom lsp-lens-debounce-interval 0.7
"Debounce interval for loading lenses."
:group 'lsp-mode
:type 'number)
(defcustom lsp-symbol-highlighting-skip-current nil
"If non-nil skip current symbol when setting symbol highlights."
:group 'lsp-mode
:type 'boolean)
(defcustom lsp-document-highlight-delay 0.2
"Seconds of idle time to wait before showing symbol highlight."
:type 'number
:group 'lsp-mode)
(defvar lsp-custom-markup-modes
'((rust-mode "no_run" "rust,no_run" "rust,ignore" "rust,should_panic"))
"Mode to uses with markdown code blocks.
They are added to `markdown-code-lang-modes'")
(defface lsp-lens-mouse-face
'((t :height 0.8 :inherit link))
"The face used for code lens overlays."
:group 'lsp-mode)
(defface lsp-lens-face
'((t :height 0.8 :inherit shadow))
"The face used for code lens overlays."
:group 'lsp-mode)
(defvar-local lsp--lens-overlays nil
"Current lenses.")
(defvar-local lsp--lens-page nil
"Pair of points which holds the last window location the lenses were loaded.")
(defvar-local lsp--lens-last-count nil
"The number of lenses the last time they were rendered.")
(defvar lsp-lens-backends '(lsp-lens-backend)
"Backends providing lenses.")
(defvar-local lsp--lens-refresh-timer nil
"Refresh timer for the lenses.")
(defvar-local lsp--lens-idle-timer nil
"Lens idle timer.")
(defvar-local lsp--lens-data nil
"Pair of points which holds the last window location the lenses were loaded.")
(defvar-local lsp--lens-backend-cache nil)
(defvar-local lsp--buffer-workspaces ()
"List of the buffer workspaces.")
(defvar-local lsp--link-overlays nil
"A list of overlays that display document links.")
(defvar-local lsp--links-idle-timer nil)
(defvar lsp--session nil
"Contain the `lsp-session' for the current Emacs instance.")
(defvar lsp--tcp-port 10000)
;; Buffer local variable for storing number of lines.
(defvar lsp--log-lines)
(cl-defgeneric lsp-execute-command (server command arguments)
"Ask SERVER to execute COMMAND with ARGUMENTS.")
(defun lsp-elt (sequence n)
"Return Nth element of SEQUENCE or nil if N is out of range."
(if (listp sequence) (elt sequence n)
(and (> (length sequence) n) (elt sequence n))))
;; define seq-first and seq-rest for older emacs
(defun seq-first (sequence)
"Return the first element of SEQUENCE."
(lsp-elt sequence 0))
(defun seq-rest (sequence)
"Return a sequence of the elements of SEQUENCE except the first one."
(seq-drop sequence 1))
(defun lsp--info (format &rest args)
"Display lsp info message with FORMAT with ARGS."
(message "%s :: %s" (propertize "LSP" 'face 'success) (apply #'format format args)))
(defun lsp--warn (format &rest args)
"Display lsp warn message with FORMAT with ARGS."
(message "%s :: %s" (propertize "LSP" 'face 'warning) (apply #'format format args)))
(defun lsp--error (format &rest args)
"Display lsp error message with FORMAT with ARGS."
(message "%s :: %s" (propertize "LSP" 'face 'error) (apply #'format format args)))
(defun lsp--eldoc-message (&optional msg)
"Show MSG in eldoc."
(run-with-idle-timer 0 nil (lambda () (eldoc-message msg))))
(defun lsp-log (format &rest args)
"Log message to the ’*lsp-log*’ buffer.
FORMAT and ARGS i the same as for `message'."
(when lsp-log-max
(let ((log-buffer (get-buffer "*lsp-log*"))
(inhibit-read-only t))
(unless log-buffer
(setq log-buffer (get-buffer-create "*lsp-log*"))
(with-current-buffer log-buffer
(view-mode 1)
(set (make-local-variable 'lsp--log-lines) 0)))
(with-current-buffer log-buffer
(save-excursion
(let* ((message (apply 'format format args))
;; Count newlines in message.
(newlines (1+ (cl-loop with start = 0
for count from 0
while (string-match "\n" message start)
do (setq start (match-end 0))
finally return count))))
(goto-char (point-max))
;; in case the buffer is not empty insert before last \n to preserve
;; the point position(in case it is in the end)
(if (eq (point) (point-min))
(progn
(insert "\n")
(backward-char))
(backward-char)
(insert "\n"))
(insert message)
(setq lsp--log-lines (+ lsp--log-lines newlines))
(when (and (integerp lsp-log-max) (> lsp--log-lines lsp-log-max))
(let ((to-delete (- lsp--log-lines lsp-log-max)))
(goto-char (point-min))
(forward-line to-delete)
(delete-region (point-min) (point))
(setq lsp--log-lines lsp-log-max)))))))))
(defalias 'lsp-message 'lsp-log)
(defalias 'lsp-ht 'ht)
;; `file-local-name' was added in Emacs 26.1.
(defalias 'lsp-file-local-name
(if (fboundp 'file-local-name)
'file-local-name
(lambda (file)
"Return the local name component of FILE."
(or (file-remote-p file 'localname) file))))
(defun lsp--merge-results (results method)
"Merge RESULTS by filtering the empty hash-tables and merging the lists.
METHOD is the executed method so the results could be merged
depending on it."
(pcase (--map (if (vectorp it) (append it nil) it) (-filter 'identity results))
(`() ())
;; only one result - simply return it
(`(,fst) fst)
;; multiple results merge it based on stragegy
(results
(pcase method
("textDocument/hover" (let ((results (seq-filter
(-compose #'not #'hash-table-empty-p)
results)))
(if (not (cdr results))
(car results)
(let ((merged (make-hash-table :test 'equal)))
(seq-each
(lambda (it)
(let ((to-add (gethash "contents" it)))
(puthash "contents"
(append
(if (and (sequencep to-add)
(not (stringp to-add)))
to-add
(list to-add))
(gethash "contents" merged))
merged)))
results)
merged))))
("textDocument/completion"
(ht
;; any incomplete
("isIncomplete" (seq-some
(-andfn #'ht? (-partial 'gethash "isIncomplete"))
results))
("items" (apply 'append (--map (append (if (ht? it)
(gethash "items" it)
it)
nil)
results)))))
(_ (apply 'append (seq-map (lambda (it)
(if (seqp it)
it
(list it)))
results)))))))
(defun lsp--spinner-start ()
"Start spinner indication."
(condition-case _err (spinner-start 'progress-bar-filled) (error)))
(defun lsp--propertize (str type)
"Propertize STR as per TYPE."
(propertize str 'face (alist-get type lsp--message-type-face)))
(defun lsp-workspaces ()
"Return the lsp workspaces associated with the current project."
(if lsp--cur-workspace (list lsp--cur-workspace) lsp--buffer-workspaces))
(defun lsp--completing-read (prompt collection transform-fn &optional predicate
require-match initial-input
hist def inherit-input-method)
"Wrap `completing-read' to provide tranformation function.
TRANSFORM-FN will be used to transform each of the items before displaying.
PROMPT COLLECTION PREDICATE REQUIRE-MATCH INITIAL-INPUT HIST DEF
INHERIT-INPUT-METHOD will be proxied to `completing-read' without changes."
(let* ((result (--map (cons (funcall transform-fn it) it) collection))
(completion (completing-read prompt (-map 'cl-first result)
predicate require-match initial-input hist
def inherit-input-method)))
(cdr (assoc completion result))))
(cl-defstruct lsp--parser
(headers '()) ;; alist of headers
(body nil) ;; message body
(reading-body nil) ;; If non-nil, reading body
(body-length nil) ;; length of current message body
(body-received 0) ;; amount of current message body currently stored in 'body'
(leftovers nil) ;; Leftover data from previous chunk; to be processed
(workspace nil))
;; A ‘lsp--client’ object describes the client-side behavior of a language
;; server. It is used to start individual server processes, each of which is
;; represented by a ‘lsp--workspace’ object. Client objects are normally
;; created using ‘lsp-define-stdio-client’ or ‘lsp-define-tcp-client’. Each
;; workspace refers to exactly one client, but there can be multiple workspaces
;; for a single client.
(cl-defstruct lsp--client
;; ‘language-id’ is a function that receives a buffer as a single argument
;; and should return the language identifier for that buffer. See
;; https://microsoft.github.io/language-server-protocol/specification#textdocumentitem
;; for a list of language identifiers. Also consult the documentation for
;; the language server represented by this client to find out what language
;; identifiers it supports or expects.
(language-id nil :read-only t)
;; ‘add-on?’ when set to t the server will be started no matter whether there
;; is another server hadling the same mode.
(add-on? nil :read-only t)
;; ‘new-connection’ is a function that should start a language server process
;; and return a cons (COMMAND-PROCESS . COMMUNICATION-PROCESS).
;; COMMAND-PROCESS must be a process object representing the server process
;; just started. COMMUNICATION-PROCESS must be a process (including pipe and
;; network processes) that ‘lsp-mode’ uses to communicate with the language
;; server using the language server protocol. COMMAND-PROCESS and
;; COMMUNICATION-PROCESS may be the same process; in that case
;; ‘new-connection’ may also return that process as a single
;; object. ‘new-connection’ is called with two arguments, FILTER and
;; SENTINEL. FILTER should be used as process filter for
;; COMMUNICATION-PROCESS, and SENTINEL should be used as process sentinel for
;; COMMAND-PROCESS.
(new-connection nil :read-only t)
;; ‘ignore-regexps’ is a list of regexps. When a data packet from the
;; language server matches any of these regexps, it will be ignored. This is
;; intended for dealing with language servers that output non-protocol data.
(ignore-regexps nil :read-only t)
;; ‘ignore-messages’ is a list of regexps. When a message from the language
;; server matches any of these regexps, it will be ignored. This is useful
;; for filtering out unwanted messages; such as servers that send nonstandard
;; message types, or extraneous log messages.
(ignore-messages nil :read-only t)
;; ‘notification-handlers’ is a hash table mapping notification method names
;; (strings) to functions handling the respective notifications. Upon
;; receiving a notification, ‘lsp-mode’ will call the associated handler
;; function passing two arguments, the ‘lsp--workspace’ object and the
;; deserialized notification parameters.
(notification-handlers (make-hash-table :test 'equal) :read-only t)
;; ‘request-handlers’ is a hash table mapping request method names
;; (strings) to functions handling the respective notifications. Upon
;; receiving a request, ‘lsp-mode’ will call the associated handler function
;; passing two arguments, the ‘lsp--workspace’ object and the deserialized
;; request parameters.
(request-handlers (make-hash-table :test 'equal) :read-only t)
;; ‘response-handlers’ is a hash table mapping integral JSON-RPC request
;; identifiers for pending asynchronous requests to functions handling the
;; respective responses. Upon receiving a response from the language server,
;; ‘lsp-mode’ will call the associated response handler function with a
;; single argument, the deserialized response parameters.
(response-handlers (make-hash-table :test 'eql) :read-only t)
;; ‘prefix-function’ is called for getting the prefix for completion.
;; The function takes no parameter and returns a cons (start . end) representing
;; the start and end bounds of the prefix. If it's not set, the client uses a
;; default prefix function."
(prefix-function nil :read-only t)
;; Contains mapping of scheme to the function that is going to be used to load
;; the file.
(uri-handlers (make-hash-table :test #'equal) :read-only t)
;; ‘action-handlers’ is a hash table mapping action to a handler function. It
;; can be used in `lsp-execute-code-action' to determine whether the action
;; current client is interested in executing the action instead of sending it
;; to the server.
(action-handlers (make-hash-table :test 'equal) :read-only t)
;; major modes supported by the client.
(major-modes)
;; Function that will be called to decide if this language client
;; should manage a particular buffer. The function will be passed
;; the file name and major mode to inform the decision. Setting
;; `activation-fn' will override `major-modes' and `remote?', if
;; present.
(activation-fn)
;; Break the tie when major-mode is supported by multiple clients.
(priority 0)
;; Unique identifier for
(server-id)
;; defines whether the client supports multi root workspaces.
(multi-root)
;; Initialization options or a function that returns initialization options.
(initialization-options)
;; Function which returns the folders that are considered to be not projects but library files.
;; The function accepts one parameter currently active workspace.
;; See: https://github.com/emacs-lsp/lsp-mode/issues/225.
(library-folders-fn)
;; function which will be called when opening file in the workspace to perfom
;; client specific initialization. The function accepts one parameter
;; currently active workspace.
(before-file-open-fn)
;; Function which will be called right after a workspace has been intialized.
(initialized-fn)
;; ‘remote?’ indicate whether the client can be used for LSP server over TRAMP.
(remote? nil)
;; A trace of all messages to and from the language server
(message-trace nil))
;; from http://emacs.stackexchange.com/questions/8082/how-to-get-buffer-position-given-line-number-and-column-number
(defun lsp--line-character-to-point (line character)
"Return the point for character CHARACTER on line LINE."
(save-excursion
(save-restriction
(condition-case _err
(progn
(widen)
(goto-char (point-min))
(forward-line line)
(forward-char character)
(point))
(error (point))))))
(define-inline lsp--position-to-point (params)
"Convert Position object in PARAMS to a point."
(inline-letevals (params)
(inline-quote
(lsp--line-character-to-point (gethash "line" ,params)
(gethash "character" ,params)))))
(define-inline lsp--range-to-region (range)
(inline-letevals (range)
(inline-quote
(cons (lsp--position-to-point (gethash "start" ,range))
(lsp--position-to-point (gethash "end" ,range))))))
(pcase-defmacro lsp-range (region)
"Build a `pcase' pattern that matches a LSP Range object.
Elements should be of the form (START . END), where START and END are bound
to the beginning and ending points in the range correspondingly."
`(and (pred hash-table-p)
(app (lambda (range) (lsp--position-to-point (gethash "start" range)))
,(car region))
(app (lambda (range) (lsp--position-to-point (gethash "end" range)))
,(cdr region))))
(defun lsp-warn (message &rest args)
"Display a warning message made from (`format-message' MESSAGE ARGS...).
This is equivalent to `display-warning', using `lsp-mode' as the type and
`:warning' as the level."
(display-warning 'lsp-mode (apply #'format-message message args)))
(defun lsp--get-uri-handler (scheme)
"Get uri handler for SCHEME in the current workspace."
(--some (gethash scheme (lsp--client-uri-handlers (lsp--workspace-client it)))
(or (lsp-workspaces) (lsp--session-workspaces (lsp-session)))))
(defun lsp--fix-path-casing (path)
"On windows, downcases path because the windows file system is
case-insensitive.
On other systems, returns path without change."
(if (eq system-type 'windows-nt) (downcase path) path))
(defun lsp--uri-to-path (uri)
"Convert URI to a file path."
(let* ((url (url-generic-parse-url (url-unhex-string uri)))
(type (url-type url))
(file (decode-coding-string (url-filename url) locale-coding-system))
(file-name (if (and type (not (string= type "file")))
(if-let ((handler (lsp--get-uri-handler type)))
(funcall handler uri)
(signal 'lsp-file-scheme-not-supported (list uri)))
;; `url-generic-parse-url' is buggy on windows:
;; https://github.com/emacs-lsp/lsp-mode/pull/265
(or (and (eq system-type 'windows-nt)
(eq (elt file 0) ?\/)
(substring file 1))
file))))
(lsp--fix-path-casing
(concat (-some 'lsp--workspace-host-root (lsp-workspaces)) file-name))))
(defun lsp--buffer-uri ()
"Return URI of the current buffer."
(or lsp-buffer-uri
(lsp--path-to-uri
(or buffer-file-name (ignore-errors (buffer-file-name (buffer-base-buffer)))))))
(defun lsp-register-client-capabilities (&rest _args)
"Implemented only to make `company-lsp' happy.
DELETE when `lsp-mode.el' is deleted.")
(defun lsp--path-to-uri (path)
"Convert PATH to a uri."
(concat lsp--uri-file-prefix
(url-hexify-string (expand-file-name (or (file-remote-p path 'localname t) path))
url-path-allowed-chars)))
(define-inline lsp--string-match-any (regex-list str)
"Given a list of REGEX-LIST and STR return the first matching regex if any."
(inline-letevals (regex-list str)
(inline-quote
(--first (string-match it ,str) ,regex-list))))
(cl-defstruct lsp-watch
(descriptors (make-hash-table :test 'equal) :read-only t)
(root-directory))
(defun lsp-watch-root-folder (dir callback &optional watch)
"Create recursive file notificaton watch in DIR.
CALLBACK is the will be called when there are changes in any of