forked from thonny/thonny
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlsp_proxy.py
More file actions
1382 lines (1172 loc) · 57.7 KB
/
Copy pathlsp_proxy.py
File metadata and controls
1382 lines (1172 loc) · 57.7 KB
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
# Adapted from https://github.com/predragnikolic/OLSP/
import dataclasses
import inspect
import json
import os.path
import subprocess
import sys
import threading
import time
import typing
from abc import ABC, abstractmethod
from dataclasses import is_dataclass
from enum import Enum
from logging import getLogger
from queue import Queue
if sys.version_info >= (3, 10):
from types import NoneType, UnionType
else:
# For Python < 3.10, use the built-in type(None) instead of NoneType
NoneType = type(None)
from typing import Union as UnionType
from typing import (
Any,
Callable,
Dict,
List,
Optional,
Type,
Union,
get_args,
get_origin,
get_type_hints,
)
from pystart import get_pystart_user_dir, get_workbench, lsp_types
from pystart.lsp_types import (
DidChangeConfigurationParams,
ErrorCodes,
InitializedParams,
InitializeResult,
LspResponse,
PublishDiagnosticsParams,
ResponseError,
)
JSON_RPC_LEN_HEADER_PREFIX = b"Content-Length: "
JSON_RPC_TYPE_HEADER_PREFIX = b"Content-Type: "
logger = getLogger(__name__)
class ResponseException(RuntimeError):
def __init__(self, message: str, code: int = ErrorCodes.UnknownErrorCode, data: Any = None):
super().__init__(message)
self.message = message
self.code = code
self.data = data
def get_error(self) -> ResponseError:
return ResponseError(message=self.message, code=self.code, data=self.data)
class JsonRpcError(RuntimeError):
pass
class LanguageServerProxy(ABC):
def __init__(self, initialize_params: lsp_types.InitializeParams):
if os.path.exists(self._get_communication_log_path()):
os.remove(self._get_communication_log_path())
self._proc: Optional[subprocess.Popen] = None
self._invalidated: bool = False
self._shutdown_accepted: bool = False
self._last_request_id: int = 0
self._pending_handlers: Dict[int, Callable] = {}
self._request_handlers: Dict[str, Optional[Callable]] = {}
self._notification_handlers: Dict[str, List[Callable]] = {}
self._diagnostics: Dict[str, PublishDiagnosticsParams] = {}
self._unprocessed_messages_from_server: Queue[Dict] = Queue()
self.server_capabilities: Optional[lsp_types.ServerCapabilities] = None
self.server_info: Optional[lsp_types.ServerCapabilities] = None
logger.info("Starting language server")
self._proc = self._create_server_process()
self._keep_processing_messages_from_server()
threading.Thread(target=self._listen_stdout, daemon=True).start()
threading.Thread(target=self._listen_stderr, daemon=True).start()
logger.info("Initializing language server")
if isinstance(initialize_params, dict):
initialize_params["initializationOptions"] = self.get_settings()
else:
assert isinstance(initialize_params, lsp_types.InitializeParams)
initialize_params.initializationOptions = self.get_settings()
self._request_initialize(initialize_params, self._handle_initialize_response)
# keep the cache of latest diagnostics TODO: do I need it?
self.bind_publish_diagnostics(self._collect_diagnostics)
# TODO: not really required, but let it be, maybe it becomes handy later
self.bind_configuration(self._handle_configuration)
@abstractmethod
def _create_server_process(self) -> subprocess.Popen[bytes]: ...
def _handle_initialize_response(self, response: LspResponse[InitializeResult]):
result = response.get_result_or_raise()
self.server_capabilities = result.capabilities
self.server_info = result.serverInfo
logger.info("Server initialized. Server info: %s", self.server_info)
logger.info("Server capabilities: %s", self.server_capabilities)
self.notify_initialized(InitializedParams())
get_workbench().event_generate("LanguageServerInitialized", self)
# Specifying settings as initializationOptions is not enough
self.notify_workspace_did_change_configuration(
DidChangeConfigurationParams(settings=self.get_settings())
)
def is_initialized(self) -> bool:
return self._server_process_alive() and self.server_capabilities is not None
def _check_initialized(self) -> None:
if not self.is_initialized():
if not self._server_process_alive():
raise RuntimeError("Server has been closed")
if self.server_capabilities is None:
raise RuntimeError("Server hasn't been initialized yet")
def _invalidate(self):
if not self._invalidated:
self._invalidated = True
get_workbench().event_generate("LanguageServerInvalidated", self)
def get_settings(self) -> Dict:
return {}
def shut_down(self):
self._invalidate()
if not self._server_process_alive():
logger.warning("Language server already closed")
return
"""
basedpyright does not exit after successful shutdown
timeout_for_shutdown = 2
self.request_shutdown(self._on_shut_down_response)
start_time = time.time()
while time.time() - start_time < timeout_for_shutdown:
time.sleep(0.1)
if not self._server_process_alive():
logger.info("Shutdown completed normally")
return
if self._shutdown_accepted:
# basedpyright server does not close after shutdown
time.sleep(0.1)
if self._server_process_alive():
logger.warning("Shutdown accepted but not completed. Will terminate")
break
else:
logger.warning(f"Shutdown not accepted in {timeout_for_shutdown} seconds. Will terminate.")
"""
try:
self._proc.terminate()
except Exception:
logger.exception("Problem when terminating language server process")
return
termination_timeout = 1
start_time = time.time()
while time.time() - start_time < termination_timeout:
time.sleep(0.1)
if not self._server_process_alive():
logger.info("Termination completed normally")
return
logger.warning(f"Termination not completed in {termination_timeout} seconds. Using kill.")
try:
self._proc.kill()
except Exception:
logger.exception("Problem when killing language server process")
def _on_shut_down_response(self, response: LspResponse[None]):
if response.get_error() is None:
self._shutdown_accepted = True
logger.info("Language server has been shut down")
else:
logger.error("Language server shutdown error: %r", response.get_error())
def _collect_diagnostics(self, result: PublishDiagnosticsParams):
self._diagnostics[result.uri] = result
def _handle_configuration(self, params: lsp_types.ConfigurationParams) -> Any:
logger.info("Configuration request: %r", params)
result = []
settings = self.get_settings()
for item in params.items:
result.append(self._extract_settings(settings, item.section))
return result
def _extract_settings(self, block: Dict, section: str) -> Dict:
if "." in section:
head, tail = section.split(".", maxsplit=1)
if head in block:
return self._extract_settings(block[head], tail)
else:
return {}
else:
if section in block:
return block[section]
else:
return {}
def _request_initialize(
self,
params: lsp_types.InitializeParams,
handler: Callable[[LspResponse[lsp_types.InitializeResult]], None],
) -> None:
"""The initialize request is sent from the client to the server.
It is sent once as the request after starting up the server.
The requests parameter is of type {@link InitializeParams}
the response if of type {@link InitializeResult} of a Thenable that
resolves to such."""
return self._send_request("initialize", params, handler)
def request_implementation(
self,
params: lsp_types.ImplementationParams,
handler: Callable[
[LspResponse[Union[lsp_types.Definition, List[lsp_types.LocationLink], None]]], None
],
) -> None:
"""A request to resolve the implementation locations of a symbol at a given text
document position. The request's parameter is of type [TextDocumentPositionParams]
(#TextDocumentPositionParams) the response is of type {@link Definition} or a
Thenable that resolves to such."""
return self._send_request("textDocument/implementation", params, handler)
def request_type_definition(
self,
params: lsp_types.TypeDefinitionParams,
handler: Callable[
[LspResponse[Union[lsp_types.Definition, List[lsp_types.LocationLink], None]]], None
],
) -> None:
"""A request to resolve the type definition locations of a symbol at a given text
document position. The request's parameter is of type [TextDocumentPositionParams]
(#TextDocumentPositionParams) the response is of type {@link Definition} or a
Thenable that resolves to such."""
return self._send_request("textDocument/typeDefinition", params, handler)
def request_document_color(
self,
params: lsp_types.DocumentColorParams,
handler: Callable[[LspResponse[List[lsp_types.ColorInformation]]], None],
) -> None:
"""A request to list all color symbols found in a given text document. The request's
parameter is of type {@link DocumentColorParams} the
response is of type {@link ColorInformation ColorInformation[]} or a Thenable
that resolves to such."""
return self._send_request("textDocument/documentColor", params, handler)
def request_color_presentation(
self,
params: lsp_types.ColorPresentationParams,
handler: Callable[[LspResponse[List[lsp_types.ColorPresentation]]], None],
) -> None:
"""A request to list all presentation for a color. The request's
parameter is of type {@link ColorPresentationParams} the
response is of type {@link ColorInformation ColorInformation[]} or a Thenable
that resolves to such."""
return self._send_request("textDocument/colorPresentation", params, handler)
def request_folding_range(
self,
params: lsp_types.FoldingRangeParams,
handler: Callable[[LspResponse[Union[List[lsp_types.FoldingRange], None]]], None],
) -> None:
"""A request to provide folding ranges in a document. The request's
parameter is of type {@link FoldingRangeParams}, the
response is of type {@link FoldingRangeList} or a Thenable
that resolves to such."""
return self._send_request("textDocument/foldingRange", params, handler)
def request_declaration(
self,
params: lsp_types.DeclarationParams,
handler: Callable[
[LspResponse[Union[lsp_types.Declaration, List[lsp_types.LocationLink], None]]], None
],
) -> None:
"""A request to resolve the type definition locations of a symbol at a given text
document position. The request's parameter is of type [TextDocumentPositionParams]
(#TextDocumentPositionParams) the response is of type {@link Declaration}
or a typed array of {@link DeclarationLink} or a Thenable that resolves
to such."""
return self._send_request("textDocument/declaration", params, handler)
def request_selection_range(
self,
params: lsp_types.SelectionRangeParams,
handler: Callable[[LspResponse[Union[List[lsp_types.SelectionRange], None]]], None],
) -> None:
"""A request to provide selection ranges in a document. The request's
parameter is of type {@link SelectionRangeParams}, the
response is of type {@link SelectionRange SelectionRange[]} or a Thenable
that resolves to such."""
return self._send_request("textDocument/selectionRange", params, handler)
def request_prepare_call_hierarchy(
self,
params: lsp_types.CallHierarchyPrepareParams,
handler: Callable[[LspResponse[Union[List[lsp_types.CallHierarchyItem], None]]], None],
) -> None:
"""A request to result a `CallHierarchyItem` in a document at a given position.
Can be used as an input to an incoming or outgoing call hierarchy.
@since 3.16.0"""
return self._send_request("textDocument/prepareCallHierarchy", params, handler)
def request_incoming_calls(
self,
params: lsp_types.CallHierarchyIncomingCallsParams,
handler: Callable[
[LspResponse[Union[List[lsp_types.CallHierarchyIncomingCall], None]]], None
],
) -> None:
"""A request to resolve the incoming calls for a given `CallHierarchyItem`.
@since 3.16.0"""
return self._send_request("callHierarchy/incomingCalls", params, handler)
def request_outgoing_calls(
self,
params: lsp_types.CallHierarchyOutgoingCallsParams,
handler: Callable[
[LspResponse[Union[List[lsp_types.CallHierarchyOutgoingCall], None]]], None
],
) -> None:
"""A request to resolve the outgoing calls for a given `CallHierarchyItem`.
@since 3.16.0"""
return self._send_request("callHierarchy/outgoingCalls", params, handler)
def request_semantic_tokens_full(
self,
params: lsp_types.SemanticTokensParams,
handler: Callable[[LspResponse[Union[lsp_types.SemanticTokens, None]]], None],
) -> None:
"""@since 3.16.0"""
return self._send_request("textDocument/semanticTokens/full", params, handler)
def request_semantic_tokens_delta(
self,
params: lsp_types.SemanticTokensDeltaParams,
handler: Callable[
[LspResponse[Union[lsp_types.SemanticTokens, lsp_types.SemanticTokensDelta, None]]],
None,
],
) -> None:
"""@since 3.16.0"""
return self._send_request("textDocument/semanticTokens/full/delta", params, handler)
def request_semantic_tokens_range(
self,
params: lsp_types.SemanticTokensRangeParams,
handler: Callable[[LspResponse[Union[lsp_types.SemanticTokens, None]]], None],
) -> None:
"""@since 3.16.0"""
return self._send_request("textDocument/semanticTokens/range", params, handler)
def request_linked_editing_range(
self,
params: lsp_types.LinkedEditingRangeParams,
handler: Callable[[LspResponse[Union[lsp_types.LinkedEditingRanges, None]]], None],
) -> None:
"""A request to provide ranges that can be edited together.
@since 3.16.0"""
return self._send_request("textDocument/linkedEditingRange", params, handler)
def request_will_create_files(
self,
params: lsp_types.CreateFilesParams,
handler: Callable[[LspResponse[Union[lsp_types.WorkspaceEdit, None]]], None],
) -> None:
"""The will create files request is sent from the client to the server before files are actually
created as long as the creation is triggered from within the client.
@since 3.16.0"""
return self._send_request("workspace/willCreateFiles", params, handler)
def request_will_rename_files(
self,
params: lsp_types.RenameFilesParams,
handler: Callable[[LspResponse[Union[lsp_types.WorkspaceEdit, None]]], None],
) -> None:
"""The will rename files request is sent from the client to the server before files are actually
renamed as long as the rename is triggered from within the client.
@since 3.16.0"""
return self._send_request("workspace/willRenameFiles", params, handler)
def request_will_delete_files(
self,
params: lsp_types.DeleteFilesParams,
handler: Callable[[LspResponse[Union[lsp_types.WorkspaceEdit, None]]], None],
) -> None:
"""The did delete files notification is sent from the client to the server when
files were deleted from within the client.
@since 3.16.0"""
return self._send_request("workspace/willDeleteFiles", params, handler)
def request_moniker(
self,
params: lsp_types.MonikerParams,
handler: Callable[[LspResponse[Union[List[lsp_types.Moniker], None]]], None],
) -> None:
"""A request to get the moniker of a symbol at a given text document position.
The request parameter is of type {@link TextDocumentPositionParams}.
The response is of type {@link Moniker Moniker[]} or `null`."""
return self._send_request("textDocument/moniker", params, handler)
def request_prepare_type_hierarchy(
self,
params: lsp_types.TypeHierarchyPrepareParams,
handler: Callable[[LspResponse[Union[List[lsp_types.TypeHierarchyItem], None]]], None],
) -> None:
"""A request to result a `TypeHierarchyItem` in a document at a given position.
Can be used as an input to a subtypes or supertypes type hierarchy.
@since 3.17.0"""
return self._send_request("textDocument/prepareTypeHierarchy", params, handler)
def request_type_hierarchy_supertypes(
self,
params: lsp_types.TypeHierarchySupertypesParams,
handler: Callable[[LspResponse[Union[List[lsp_types.TypeHierarchyItem], None]]], None],
) -> None:
"""A request to resolve the supertypes for a given `TypeHierarchyItem`.
@since 3.17.0"""
return self._send_request("typeHierarchy/supertypes", params, handler)
def request_type_hierarchy_subtypes(
self,
params: lsp_types.TypeHierarchySubtypesParams,
handler: Callable[[LspResponse[Union[List[lsp_types.TypeHierarchyItem], None]]], None],
) -> None:
"""A request to resolve the subtypes for a given `TypeHierarchyItem`.
@since 3.17.0"""
return self._send_request("typeHierarchy/subtypes", params, handler)
def request_inline_value(
self,
params: lsp_types.InlineValueParams,
handler: Callable[[LspResponse[Union[List[lsp_types.InlineValue], None]]], None],
) -> None:
"""A request to provide inline values in a document. The request's parameter is of
type {@link InlineValueParams}, the response is of type
{@link InlineValue InlineValue[]} or a Thenable that resolves to such.
@since 3.17.0"""
return self._send_request("textDocument/inlineValue", params, handler)
def request_inlay_hint(
self,
params: lsp_types.InlayHintParams,
handler: Callable[[LspResponse[Union[List[lsp_types.InlayHint], None]]], None],
) -> None:
"""A request to provide inlay hints in a document. The request's parameter is of
type {@link InlayHintsParams}, the response is of type
{@link InlayHint InlayHint[]} or a Thenable that resolves to such.
@since 3.17.0"""
return self._send_request("textDocument/inlayHint", params, handler)
def request_resolve_inlay_hint(
self,
params: lsp_types.InlayHint,
handler: Callable[[LspResponse[lsp_types.InlayHint]], None],
) -> None:
"""A request to resolve additional properties for an inlay hint.
The request's parameter is of type {@link InlayHint}, the response is
of type {@link InlayHint} or a Thenable that resolves to such.
@since 3.17.0"""
return self._send_request("inlayHint/resolve", params, handler)
def request_text_document_diagnostic(
self,
params: lsp_types.DocumentDiagnosticParams,
handler: Callable[[LspResponse[lsp_types.DocumentDiagnosticReport]], None],
) -> None:
"""The document diagnostic request definition.
@since 3.17.0"""
return self._send_request("textDocument/diagnostic", params, handler)
def request_workspace_diagnostic(
self,
params: lsp_types.WorkspaceDiagnosticParams,
handler: Callable[[LspResponse[lsp_types.WorkspaceDiagnosticReport]], None],
) -> None:
"""The workspace diagnostic request definition.
@since 3.17.0"""
return self._send_request("workspace/diagnostic", params, handler)
def request_shutdown(self, handler: Callable[[LspResponse[None]], None]) -> None:
"""A shutdown request is sent from the client to the server.
It is sent once when the client decides to shutdown the
server. The only notification that is sent after a shutdown request
is the exit event."""
return self._send_request("shutdown", None, handler)
def request_will_save_wait_until(
self,
params: lsp_types.WillSaveTextDocumentParams,
handler: Callable[[LspResponse[Union[List[lsp_types.TextEdit], None]]], None],
) -> None:
"""A document will save request is sent from the client to the server before
the document is actually saved. The request can return an array of TextEdits
which will be applied to the text document before it is saved. Please note that
clients might drop results if computing the text edits took too long or if a
server constantly fails on this request. This is done to keep the save fast and
reliable."""
return self._send_request("textDocument/willSaveWaitUntil", params, handler)
def request_completion(
self,
params: lsp_types.CompletionParams,
handler: Callable[
[LspResponse[Union[List[lsp_types.CompletionItem], lsp_types.CompletionList, None]]],
None,
],
) -> None:
"""Request to request completion at a given text document position. The request's
parameter is of type {@link TextDocumentPosition} the response
is of type {@link CompletionItem CompletionItem[]} or {@link CompletionList}
or a Thenable that resolves to such.
The request can delay the computation of the {@link CompletionItem.detail `detail`}
and {@link CompletionItem.documentation `documentation`} properties to the `completionItem/resolve`
request. However, properties that are needed for the initial sorting and filtering, like `sortText`,
`filterText`, `insertText`, and `textEdit`, must not be changed during resolve."""
return self._send_request("textDocument/completion", params, handler)
def request_resolve_completion_item(
self,
params: lsp_types.CompletionItem,
handler: Callable[[LspResponse[lsp_types.CompletionItem]], None],
) -> None:
"""Request to resolve additional information for a given completion item.The request's
parameter is of type {@link CompletionItem} the response
is of type {@link CompletionItem} or a Thenable that resolves to such."""
return self._send_request("completionItem/resolve", params, handler)
def request_hover(
self,
params: lsp_types.HoverParams,
handler: Callable[[LspResponse[Union[lsp_types.Hover, None]]], None],
) -> None:
"""Request to request hover information at a given text document position. The request's
parameter is of type {@link TextDocumentPosition} the response is of
type {@link Hover} or a Thenable that resolves to such."""
return self._send_request("textDocument/hover", params, handler)
def request_signature_help(
self,
params: lsp_types.SignatureHelpParams,
handler: Callable[[LspResponse[Union[lsp_types.SignatureHelp, None]]], None],
) -> None:
return self._send_request("textDocument/signatureHelp", params, handler)
def request_definition(
self,
params: lsp_types.DefinitionParams,
handler: Callable[
[LspResponse[Union[lsp_types.Definition, List[lsp_types.LocationLink], None]]], None
],
) -> None:
"""A request to resolve the definition location of a symbol at a given text
document position. The request's parameter is of type [TextDocumentPosition]
(#TextDocumentPosition) the response is of either type {@link Definition}
or a typed array of {@link DefinitionLink} or a Thenable that resolves
to such."""
return self._send_request("textDocument/definition", params, handler)
def request_references(
self,
params: lsp_types.ReferenceParams,
handler: Callable[[LspResponse[Union[List[lsp_types.Location], None]]], None],
) -> None:
"""A request to resolve project-wide references for the symbol denoted
by the given text document position. The request's parameter is of
type {@link ReferenceParams} the response is of type
{@link Location Location[]} or a Thenable that resolves to such."""
return self._send_request("textDocument/references", params, handler)
def request_document_highlight(
self,
params: lsp_types.DocumentHighlightParams,
handler: Callable[[LspResponse[Union[List[lsp_types.DocumentHighlight], None]]], None],
) -> None:
"""Request to resolve a {@link DocumentHighlight} for a given
text document position. The request's parameter is of type [TextDocumentPosition]
(#TextDocumentPosition) the request response is of type [DocumentHighlight[]]
(#DocumentHighlight) or a Thenable that resolves to such."""
return self._send_request("textDocument/documentHighlight", params, handler)
def request_document_symbol(
self,
params: lsp_types.DocumentSymbolParams,
handler: Callable[
[
LspResponse[
Union[List[lsp_types.SymbolInformation], List[lsp_types.DocumentSymbol], None]
]
],
None,
],
) -> None:
"""A request to list all symbols found in a given text document. The request's
parameter is of type {@link TextDocumentIdentifier} the
response is of type {@link SymbolInformation SymbolInformation[]} or a Thenable
that resolves to such."""
return self._send_request("textDocument/documentSymbol", params, handler)
def request_code_action(
self,
params: lsp_types.CodeActionParams,
handler: Callable[
[LspResponse[Union[List[Union[lsp_types.Command, lsp_types.CodeAction]], None]]], None
],
) -> None:
"""A request to provide commands for the given text document and range."""
return self._send_request("textDocument/codeAction", params, handler)
def request_resolve_code_action(
self,
params: lsp_types.CodeAction,
handler: Callable[[LspResponse[lsp_types.CodeAction]], None],
) -> None:
"""Request to resolve additional information for a given code action.The request's
parameter is of type {@link CodeAction} the response
is of type {@link CodeAction} or a Thenable that resolves to such."""
return self._send_request("codeAction/resolve", params, handler)
def request_workspace_symbol(
self,
params: lsp_types.WorkspaceSymbolParams,
handler: Callable[
[
LspResponse[
Union[List[lsp_types.SymbolInformation], List[lsp_types.WorkspaceSymbol], None]
]
],
None,
],
) -> None:
"""A request to list project-wide symbols matching the query string given
by the {@link WorkspaceSymbolParams}. The response is
of type {@link SymbolInformation SymbolInformation[]} or a Thenable that
resolves to such.
@since 3.17.0 - support for WorkspaceSymbol in the returned data. Clients
need to advertise support for WorkspaceSymbols via the client capability
`workspace.symbol.resolveSupport`.
"""
return self._send_request("workspace/symbol", params, handler)
def request_resolve_workspace_symbol(
self,
params: lsp_types.WorkspaceSymbol,
handler: Callable[[LspResponse[lsp_types.WorkspaceSymbol]], None],
) -> None:
"""A request to resolve the range inside the workspace
symbol's location.
@since 3.17.0"""
return self._send_request("workspaceSymbol/resolve", params, handler)
def request_code_lens(
self,
params: lsp_types.CodeLensParams,
handler: Callable[[LspResponse[Union[List[lsp_types.CodeLens], None]]], None],
) -> None:
"""A request to provide code lens for the given text document."""
return self._send_request("textDocument/codeLens", params, handler)
def request_resolve_code_lens(
self,
params: lsp_types.CodeLens,
handler: Callable[[LspResponse[lsp_types.CodeLens]], None],
) -> None:
"""A request to resolve a command for a given code lens."""
return self._send_request("codeLens/resolve", params, handler)
def request_document_link(
self,
params: lsp_types.DocumentLinkParams,
handler: Callable[[LspResponse[Union[List[lsp_types.DocumentLink], None]]], None],
) -> None:
"""A request to provide document links"""
return self._send_request("textDocument/documentLink", params, handler)
def request_resolve_document_link(
self,
params: lsp_types.DocumentLink,
handler: Callable[[LspResponse[lsp_types.DocumentLink]], None],
) -> None:
"""Request to resolve additional information for a given document link. The request's
parameter is of type {@link DocumentLink} the response
is of type {@link DocumentLink} or a Thenable that resolves to such."""
return self._send_request("documentLink/resolve", params, handler)
def request_formatting(
self,
params: lsp_types.DocumentFormattingParams,
handler: Callable[[LspResponse[Union[List[lsp_types.TextEdit], None]]], None],
) -> None:
"""A request to to format a whole document."""
return self._send_request("textDocument/formatting", params, handler)
def request_range_formatting(
self,
params: lsp_types.DocumentRangeFormattingParams,
handler: Callable[[LspResponse[Union[List[lsp_types.TextEdit], None]]], None],
) -> None:
"""A request to to format a range in a document."""
return self._send_request("textDocument/rangeFormatting", params, handler)
def request_on_type_formatting(
self,
params: lsp_types.DocumentOnTypeFormattingParams,
handler: Callable[[LspResponse[Union[List[lsp_types.TextEdit], None]]], None],
) -> None:
"""A request to format a document on type."""
return self._send_request("textDocument/onTypeFormatting", params, handler)
def request_rename(
self,
params: lsp_types.RenameParams,
handler: Callable[[LspResponse[Union[lsp_types.WorkspaceEdit, None]]], None],
) -> None:
"""A request to rename a symbol."""
return self._send_request("textDocument/rename", params, handler)
def request_prepare_rename(
self,
params: lsp_types.PrepareRenameParams,
handler: Callable[[LspResponse[Union[lsp_types.PrepareRenameResult, None]]], None],
) -> None:
"""A request to test and perform the setup necessary for a rename.
@since 3.16 - support for default behavior"""
return self._send_request("textDocument/prepareRename", params, handler)
def request_execute_command(
self,
params: lsp_types.ExecuteCommandParams,
handler: Callable[[LspResponse[Union[lsp_types.LSPAny, None]]], None],
) -> None:
"""A request send from the client to the server to execute a command. The request might return
a workspace edit which the client will apply to the workspace."""
return self._send_request("workspace/executeCommand", params, handler)
def notify_did_change_workspace_folders(
self, params: lsp_types.DidChangeWorkspaceFoldersParams
) -> None:
"""The `workspace/didChangeWorkspaceFolders` notification is sent from the client to the server when the workspace
folder configuration changes."""
return self._send_notification("workspace/didChangeWorkspaceFolders", params)
def notify_cancel_work_done_progress(
self, params: lsp_types.WorkDoneProgressCancelParams
) -> None:
"""The `window/workDoneProgress/cancel` notification is sent from the client to the server to cancel a progress
initiated on the server side."""
return self._send_notification("window/workDoneProgress/cancel", params)
def notify_did_create_files(self, params: lsp_types.CreateFilesParams) -> None:
"""The did create files notification is sent from the client to the server when
files were created from within the client.
@since 3.16.0"""
return self._send_notification("workspace/didCreateFiles", params)
def notify_did_rename_files(self, params: lsp_types.RenameFilesParams) -> None:
"""The did rename files notification is sent from the client to the server when
files were renamed from within the client.
@since 3.16.0"""
return self._send_notification("workspace/didRenameFiles", params)
def notify_did_delete_files(self, params: lsp_types.DeleteFilesParams) -> None:
"""The will delete files request is sent from the client to the server before files are actually
deleted as long as the deletion is triggered from within the client.
@since 3.16.0"""
return self._send_notification("workspace/didDeleteFiles", params)
def notify_did_open_notebook_document(
self, params: lsp_types.DidOpenNotebookDocumentParams
) -> None:
"""A notification sent when a notebook opens.
@since 3.17.0"""
return self._send_notification("notebookDocument/didOpen", params)
def notify_did_change_notebook_document(
self, params: lsp_types.DidChangeNotebookDocumentParams
) -> None:
return self._send_notification("notebookDocument/didChange", params)
def notify_did_save_notebook_document(
self, params: lsp_types.DidSaveNotebookDocumentParams
) -> None:
"""A notification sent when a notebook document is saved.
@since 3.17.0"""
return self._send_notification("notebookDocument/didSave", params)
def notify_did_close_notebook_document(
self, params: lsp_types.DidCloseNotebookDocumentParams
) -> None:
"""A notification sent when a notebook closes.
@since 3.17.0"""
return self._send_notification("notebookDocument/didClose", params)
def notify_initialized(self, params: lsp_types.InitializedParams) -> None:
"""The initialized notification is sent from the client to the
server after the client is fully initialized and the server
is allowed to send requests from the server to the client."""
return self._send_notification("initialized", params)
def notify_exit(self) -> None:
"""The exit event is sent from the client to the server to
ask the server to exit its process."""
return self._send_notification("exit", None)
def notify_workspace_did_change_configuration(
self, params: lsp_types.DidChangeConfigurationParams
) -> None:
"""The configuration change notification is sent from the client to the server
when the client's configuration has changed. The notification contains
the changed configuration as defined by the language client."""
return self._send_notification("workspace/didChangeConfiguration", params)
def notify_did_open_text_document(self, params: lsp_types.DidOpenTextDocumentParams) -> None:
"""The document open notification is sent from the client to the server to signal
newly opened text documents. The document's truth is now managed by the client
and the server must not try to read the document's truth using the document's
uri. Open in this sense means it is managed by the client. It doesn't necessarily
mean that its content is presented in an editor. An open notification must not
be sent more than once without a corresponding close notification send before.
This means open and close notification must be balanced and the max open count
is one."""
return self._send_notification("textDocument/didOpen", params)
def notify_did_change_text_document(
self, params: lsp_types.DidChangeTextDocumentParams
) -> None:
"""The document change notification is sent from the client to the server to signal
changes to a text document."""
return self._send_notification("textDocument/didChange", params)
def notify_did_close_text_document(self, params: lsp_types.DidCloseTextDocumentParams) -> None:
"""The document close notification is sent from the client to the server when
the document got closed in the client. The document's truth now exists where
the document's uri points to (e.g. if the document's uri is a file uri the
truth now exists on disk). As with the open notification the close notification
is about managing the document's content. Receiving a close notification
doesn't mean that the document was open in an editor before. A close
notification requires a previous open notification to be sent."""
return self._send_notification("textDocument/didClose", params)
def notify_did_save_text_document(self, params: lsp_types.DidSaveTextDocumentParams) -> None:
"""The document save notification is sent from the client to the server when
the document got saved in the client."""
return self._send_notification("textDocument/didSave", params)
def notify_will_save_text_document(self, params: lsp_types.WillSaveTextDocumentParams) -> None:
"""A document will save notification is sent from the client to the server before
the document is actually saved."""
return self._send_notification("textDocument/willSave", params)
def notify_did_change_watched_files(
self, params: lsp_types.DidChangeWatchedFilesParams
) -> None:
"""The watched files notification is sent from the client to the server when
the client detects changes to file watched by the language client."""
return self._send_notification("workspace/didChangeWatchedFiles", params)
def notify_set_trace(self, params: lsp_types.SetTraceParams) -> None:
return self._send_notification("$/setTrace", params)
def notify_cancel_request(self, params: lsp_types.CancelParams) -> None:
return self._send_notification("$/cancelRequest", params)
def notify_progress(self, params: lsp_types.ProgressParams) -> None:
return self._send_notification("$/progress", params)
def bind_workspace_folders(
self, handler: Callable[[None], Union[None, List[lsp_types.WorkspaceFolder]]]
):
"""The `workspace/workspaceFolders` is sent from the server to the client to fetch the open workspace folders."""
self._bind_request_handler("workspace/workspaceFolders", handler)
def bind_configuration(
self, handler: Callable[[lsp_types.ConfigurationParams], List[lsp_types.LSPAny]]
):
"""The 'workspace/configuration' request is sent from the server to the client to fetch a certain
configuration setting.
This pull model replaces the old push model where the client signaled configuration change via an
event. If the server still needs to react to configuration changes (since the server caches the
result of `workspace/configuration` requests) the server should register for an empty configuration
change event and empty the cache if such an event is received."""
self._bind_request_handler("workspace/configuration", handler)
def bind_work_done_progress_create(
self, handler: Callable[[lsp_types.WorkDoneProgressCreateParams], None]
):
"""The `window/workDoneProgress/create` request is sent from the server to the client to initiate progress
reporting from the server."""
self._bind_request_handler("window/workDoneProgress/create", handler)
def bind_semantic_tokens_refresh(self, handler: Callable[[None], None]):
self._bind_request_handler("workspace/semanticTokens/refresh", handler)
def bind_show_document(
self, handler: Callable[[lsp_types.ShowDocumentParams], lsp_types.ShowDocumentResult]
):
"""A request to show a document. This request might open an
external program depending on the value of the URI to open.
For example a request to open `https://code.visualstudio.com/`
will very likely open the URI in a WEB browser.
@since 3.16.0"""
self._bind_request_handler("window/showDocument", handler)
def bind_show_message_request(
self,
handler: Callable[
[lsp_types.ShowMessageRequestParams], Union[lsp_types.MessageActionItem, None]
],
):
"""The show message request is sent from the server to the client to show a message
and a set of options actions to the user."""
self._bind_request_handler("window/showMessageRequest", handler)
def bind_inline_value_refresh(self, handler: Callable[[None], None]):
self._bind_request_handler("workspace/inlineValue/refresh", handler)
def bind_inline_hint_refresh(self, handler: Callable[[None], None]):
self._bind_request_handler("workspace/inlineHint/refresh", handler)
def bind_diagnostic_refresh(self, handler: Callable[[None], None]):
"""The diagnostic refresh request definition.
@since 3.17.0"""
self._bind_request_handler("workspace/diagnostic/refresh", handler)
def bind_code_lens_refresh(self, handler: Callable[[None], None]):
"""A request to refresh all code actions
@since 3.16.0"""
self._bind_request_handler("workspace/codeLens/refresh", handler)
def bind_register_capability(self, handler: Callable[[lsp_types.RegistrationParams], None]):
"""The `client/registerCapability` request is sent from the server to the client to register a new capability
handler on the client side."""
self._bind_request_handler("client/registerCapability", handler)
def bind_unregister_capability(self, handler: Callable[[lsp_types.UnregistrationParams], None]):
"""The `client/unregisterCapability` request is sent from the server to the client to unregister a previously
registered capability handler on the client side."""
self._bind_request_handler("client/unregisterCapability", handler)
def bind_apply_edit(
self,
handler: Callable[[lsp_types.ApplyWorkspaceEditParams], lsp_types.ApplyWorkspaceEditResult],
):