-
Notifications
You must be signed in to change notification settings - Fork 185
/
Copy pathsessions.py
2464 lines (2138 loc) · 104 KB
/
sessions.py
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
from __future__ import annotations
from .collections import DottedDict
from .constants import SEMANTIC_TOKENS_MAP
from .diagnostics_storage import DiagnosticsStorage
from .edit import apply_text_edits
from .edit import parse_workspace_edit
from .edit import WorkspaceChanges
from .file_watcher import DEFAULT_KIND
from .file_watcher import file_watcher_event_type_to_lsp_file_change_type
from .file_watcher import FileWatcher
from .file_watcher import FileWatcherEvent
from .file_watcher import get_file_watcher_implementation
from .file_watcher import lsp_watch_kind_to_file_watcher_event_types
from .logging import debug
from .logging import exception_log
from .open import center_selection
from .open import open_externally
from .open import open_file
from .progress import WindowProgressReporter
from .promise import PackagedTask
from .promise import Promise
from .protocol import ClientCapabilities
from .protocol import CodeAction, CodeActionKind
from .protocol import CodeLensExtended
from .protocol import Command
from .protocol import CompletionItemKind
from .protocol import CompletionItemTag
from .protocol import Diagnostic
from .protocol import DiagnosticServerCancellationData
from .protocol import DiagnosticSeverity
from .protocol import DiagnosticTag
from .protocol import DidChangeWatchedFilesRegistrationOptions
from .protocol import DidChangeWorkspaceFoldersParams
from .protocol import DocumentDiagnosticReportKind
from .protocol import DocumentLink
from .protocol import DocumentUri
from .protocol import Error
from .protocol import ErrorCodes
from .protocol import ExecuteCommandParams
from .protocol import FailureHandlingKind
from .protocol import FileEvent
from .protocol import FoldingRangeKind
from .protocol import GeneralClientCapabilities
from .protocol import InitializeError
from .protocol import InitializeParams
from .protocol import InitializeResult
from .protocol import InsertTextMode
from .protocol import Location
from .protocol import LocationLink
from .protocol import LogMessageParams
from .protocol import LSPAny
from .protocol import LSPErrorCodes
from .protocol import LSPObject
from .protocol import MarkupKind
from .protocol import Notification
from .protocol import PrepareSupportDefaultBehavior
from .protocol import PreviousResultId
from .protocol import ProgressParams
from .protocol import ProgressToken
from .protocol import PublishDiagnosticsParams
from .protocol import RegistrationParams
from .protocol import Range
from .protocol import Request
from .protocol import Response
from .protocol import ResponseError
from .protocol import SemanticTokenModifiers
from .protocol import SemanticTokenTypes
from .protocol import SymbolKind
from .protocol import SymbolTag
from .protocol import TextDocumentClientCapabilities
from .protocol import TextDocumentSyncKind
from .protocol import TextEdit
from .protocol import TokenFormat
from .protocol import UnregistrationParams
from .protocol import WindowClientCapabilities
from .protocol import WorkDoneProgressBegin
from .protocol import WorkDoneProgressCreateParams
from .protocol import WorkDoneProgressEnd
from .protocol import WorkDoneProgressReport
from .protocol import WorkspaceClientCapabilities
from .protocol import WorkspaceDiagnosticParams
from .protocol import WorkspaceDiagnosticReport
from .protocol import WorkspaceDocumentDiagnosticReport
from .protocol import WorkspaceFullDocumentDiagnosticReport
from .protocol import WorkspaceEdit
from .settings import client_configs
from .settings import globalprefs
from .settings import userprefs
from .transports import Transport
from .transports import TransportCallbacks
from .types import Capabilities
from .types import ClientConfig
from .types import ClientStates
from .types import debounced
from .types import diff
from .types import DocumentSelector
from .types import method_to_capability
from .types import SettingsRegistration
from .types import sublime_pattern_to_glob
from .types import WORKSPACE_DIAGNOSTICS_TIMEOUT
from .typing import StrEnum
from .url import filename_to_uri
from .url import parse_uri
from .url import unparse_uri
from .version import __version__
from .views import extract_variables
from .views import get_storage_path
from .views import get_uri_and_range_from_location
from .views import MarkdownLangMap
from .workspace import is_subpath_of
from .workspace import WorkspaceFolder
from abc import ABCMeta
from abc import abstractmethod
from enum import IntEnum, IntFlag
from typing import Any, Callable, Generator, List, Protocol, TypeVar
from typing import cast
from typing_extensions import TypeAlias, TypeGuard
from weakref import WeakSet
import functools
import mdpopups
import os
import sublime
import weakref
InitCallback: TypeAlias = Callable[['Session', bool], None]
T = TypeVar('T')
class ViewStateActions(IntFlag):
NONE = 0
SAVE = 1
CLOSE = 2
def is_workspace_full_document_diagnostic_report(
report: WorkspaceDocumentDiagnosticReport
) -> TypeGuard[WorkspaceFullDocumentDiagnosticReport]:
return report['kind'] == DocumentDiagnosticReportKind.Full
def is_diagnostic_server_cancellation_data(data: Any) -> TypeGuard[DiagnosticServerCancellationData]:
return isinstance(data, dict) and 'retriggerRequest' in data
def get_semantic_tokens_map(custom_tokens_map: dict[str, str] | None) -> tuple[tuple[str, str], ...]:
tokens_scope_map = SEMANTIC_TOKENS_MAP.copy()
if custom_tokens_map is not None:
tokens_scope_map.update(custom_tokens_map)
return tuple(sorted(tokens_scope_map.items())) # make map hashable
@functools.lru_cache(maxsize=128)
def decode_semantic_token(
types_legend: tuple[str, ...],
modifiers_legend: tuple[str, ...],
tokens_scope_map: tuple[tuple[str, str], ...],
token_type_encoded: int,
token_modifiers_encoded: int
) -> tuple[str, list[str], str | None]:
"""
This function converts the token type and token modifiers from encoded numbers into names, based on the legend from
the server. It also returns the corresponding scope name, which will be used for the highlighting color, either
derived from a predefined scope map if the token type is one of the types defined in the LSP specs, or from a scope
for custom token types if it was added in the client configuration (will be `None` if no scope has been defined for
the custom token type).
"""
token_type = types_legend[token_type_encoded]
token_modifiers = [modifiers_legend[idx]
for idx, val in enumerate(reversed(bin(token_modifiers_encoded)[2:])) if val == "1"]
scope = None
tokens_scope_map_dict = dict(tokens_scope_map) # convert hashable tokens/scope map back to dict for easy lookup
if token_type in tokens_scope_map_dict:
for token_modifier in token_modifiers:
# this approach is limited to consider at most one modifier for the scope lookup
key = f"{token_type}.{token_modifier}"
if key in tokens_scope_map_dict:
scope = tokens_scope_map_dict[key] + " meta.semantic-token.{}.{}.lsp".format(
token_type.lower(), token_modifier.lower())
break # first match wins (in case of multiple modifiers)
else:
scope = tokens_scope_map_dict[token_type]
if token_modifiers:
scope += f" meta.semantic-token.{token_type.lower()}.{token_modifiers[0].lower()}.lsp"
else:
scope += f" meta.semantic-token.{token_type.lower()}.lsp"
return token_type, token_modifiers, scope
class Manager(metaclass=ABCMeta):
"""
A Manager is a container of Sessions.
"""
# Observers
@property
@abstractmethod
def window(self) -> sublime.Window:
"""
Get the window associated with this manager.
"""
raise NotImplementedError()
@abstractmethod
def sessions(self, view: sublime.View, capability: str | None = None) -> Generator[Session, None, None]:
"""
Iterate over the sessions stored in this manager, applicable to the given view, with the given capability.
"""
raise NotImplementedError()
@abstractmethod
def get_project_path(self, file_path: str) -> str | None:
"""
Get the project path for the given file.
"""
raise NotImplementedError()
@abstractmethod
def should_ignore_diagnostics(self, uri: DocumentUri, configuration: ClientConfig) -> str | None:
"""
Should the diagnostics for this URI be shown in the view? Return a reason why not
"""
# Mutators
@abstractmethod
def start_async(self, configuration: ClientConfig, initiating_view: sublime.View) -> None:
"""
Start a new Session with the given configuration. The initiating view is the view that caused this method to
be called.
A normal flow of calls would be start -> on_post_initialize -> do language server things -> on_post_exit.
However, it is possible that the subprocess cannot start, in which case on_post_initialize will never be called.
"""
raise NotImplementedError()
@abstractmethod
def on_diagnostics_updated(self) -> None:
raise NotImplementedError()
# Event callbacks
@abstractmethod
def on_post_exit_async(self, session: Session, exit_code: int, exception: Exception | None) -> None:
"""
The given Session has stopped with the given exit code.
"""
raise NotImplementedError()
def _int_enum_to_list(e: type[IntEnum]) -> list[int]:
return [v.value for v in e]
def _str_enum_to_list(e: type[StrEnum]) -> list[str]:
return [v.value for v in e]
def get_initialize_params(variables: dict[str, str], workspace_folders: list[WorkspaceFolder],
config: ClientConfig) -> InitializeParams:
completion_kinds = cast(List[CompletionItemKind], _int_enum_to_list(CompletionItemKind))
symbol_kinds = cast(List[SymbolKind], _int_enum_to_list(SymbolKind))
diagnostic_tag_value_set = cast(List[DiagnosticTag], _int_enum_to_list(DiagnosticTag))
completion_tag_value_set = cast(List[CompletionItemTag], _int_enum_to_list(CompletionItemTag))
symbol_tag_value_set = cast(List[SymbolTag], _int_enum_to_list(SymbolTag))
semantic_token_types = cast(List[str], _str_enum_to_list(SemanticTokenTypes))
if config.semantic_tokens is not None:
for token_type in config.semantic_tokens.keys():
if token_type not in semantic_token_types:
semantic_token_types.append(token_type)
semantic_token_modifiers = cast(List[str], _str_enum_to_list(SemanticTokenModifiers))
supported_markup_kinds = cast(List[MarkupKind], [MarkupKind.Markdown.value, MarkupKind.PlainText.value])
folding_range_kind_value_set = cast(List[FoldingRangeKind], _str_enum_to_list(FoldingRangeKind))
first_folder = workspace_folders[0] if workspace_folders else None
general_capabilities: GeneralClientCapabilities = {
# https://microsoft.github.io/language-server-protocol/specification#regExp
"regularExpressions": {
# https://www.sublimetext.com/docs/completions.html#ver-dev
# https://www.boost.org/doc/libs/1_64_0/libs/regex/doc/html/boost_regex/syntax/perl_syntax.html
# ECMAScript syntax is a subset of Perl syntax
"engine": "ECMAScript"
},
# https://microsoft.github.io/language-server-protocol/specification#markupContent
"markdown": {
# https://python-markdown.github.io
"parser": "Python-Markdown",
"version": mdpopups.markdown.__version__ # type: ignore
}
}
text_document_capabilities: TextDocumentClientCapabilities = {
"synchronization": {
"dynamicRegistration": True, # exceptional
"didSave": True,
"willSave": True,
"willSaveWaitUntil": True
},
"hover": {
"dynamicRegistration": True,
"contentFormat": supported_markup_kinds
},
"completion": {
"dynamicRegistration": True,
"completionItem": {
"snippetSupport": True,
"deprecatedSupport": True,
"documentationFormat": supported_markup_kinds,
"tagSupport": {
"valueSet": completion_tag_value_set
},
"resolveSupport": {
"properties": ["detail", "documentation", "additionalTextEdits"]
},
"insertReplaceSupport": True,
"insertTextModeSupport": {
"valueSet": cast(List[InsertTextMode], [InsertTextMode.AdjustIndentation.value])
},
"labelDetailsSupport": True,
},
"completionItemKind": {
"valueSet": completion_kinds
},
"insertTextMode": cast(InsertTextMode, InsertTextMode.AdjustIndentation.value),
"completionList": {
"itemDefaults": ["editRange", "insertTextFormat", "data"]
}
},
"signatureHelp": {
"dynamicRegistration": True,
"contextSupport": True,
"signatureInformation": {
"activeParameterSupport": True,
"documentationFormat": supported_markup_kinds,
"parameterInformation": {
"labelOffsetSupport": True
}
}
},
"references": {
"dynamicRegistration": True
},
"documentHighlight": {
"dynamicRegistration": True
},
"documentSymbol": {
"dynamicRegistration": True,
"hierarchicalDocumentSymbolSupport": True,
"symbolKind": {
"valueSet": symbol_kinds
},
"tagSupport": {
"valueSet": symbol_tag_value_set
}
},
"documentLink": {
"dynamicRegistration": True,
"tooltipSupport": True
},
"formatting": {
"dynamicRegistration": True # exceptional
},
"rangeFormatting": {
"dynamicRegistration": True,
"rangesSupport": True
},
"declaration": {
"dynamicRegistration": True,
"linkSupport": True
},
"definition": {
"dynamicRegistration": True,
"linkSupport": True
},
"typeDefinition": {
"dynamicRegistration": True,
"linkSupport": True
},
"implementation": {
"dynamicRegistration": True,
"linkSupport": True
},
"codeAction": {
"dynamicRegistration": True,
"codeActionLiteralSupport": {
"codeActionKind": {
"valueSet": cast(List[CodeActionKind], [
CodeActionKind.QuickFix.value,
CodeActionKind.Refactor.value,
CodeActionKind.RefactorExtract.value,
CodeActionKind.RefactorInline.value,
CodeActionKind.RefactorRewrite.value,
CodeActionKind.SourceFixAll.value,
CodeActionKind.SourceOrganizeImports.value,
])
}
},
"dataSupport": True,
"isPreferredSupport": True,
"resolveSupport": {
"properties": [
"edit"
]
}
},
"rename": {
"dynamicRegistration": True,
"prepareSupport": True,
"prepareSupportDefaultBehavior": cast(
PrepareSupportDefaultBehavior, PrepareSupportDefaultBehavior.Identifier.value),
},
"colorProvider": {
"dynamicRegistration": True # exceptional
},
"publishDiagnostics": {
"relatedInformation": True,
"tagSupport": {
"valueSet": diagnostic_tag_value_set
},
"versionSupport": True,
"codeDescriptionSupport": True,
"dataSupport": True
},
"diagnostic": {
"dynamicRegistration": True,
"relatedDocumentSupport": True
},
"selectionRange": {
"dynamicRegistration": True
},
"foldingRange": {
"dynamicRegistration": True,
"foldingRangeKind": {
"valueSet": folding_range_kind_value_set
}
},
"codeLens": {
"dynamicRegistration": True
},
"inlayHint": {
"dynamicRegistration": True,
"resolveSupport": {
"properties": ["textEdits", "label.command"]
}
},
"semanticTokens": {
"dynamicRegistration": True,
"requests": {
"range": True,
"full": {
"delta": True
}
},
"tokenTypes": semantic_token_types,
"tokenModifiers": semantic_token_modifiers,
"formats": cast(List[TokenFormat], [
TokenFormat.Relative.value
]),
"overlappingTokenSupport": False,
"multilineTokenSupport": True,
"augmentsSyntaxTokens": True
},
"callHierarchy": {
"dynamicRegistration": True
},
"typeHierarchy": {
"dynamicRegistration": True
}
}
workspace_capabilites: WorkspaceClientCapabilities = {
"applyEdit": True,
"didChangeConfiguration": {
"dynamicRegistration": True
},
"executeCommand": {},
"workspaceEdit": {
"documentChanges": True,
"failureHandling": cast(FailureHandlingKind, FailureHandlingKind.Abort.value),
},
"workspaceFolders": True,
"symbol": {
"dynamicRegistration": True, # exceptional
"resolveSupport": {
"properties": ["location.range"]
},
"symbolKind": {
"valueSet": symbol_kinds
},
"tagSupport": {
"valueSet": symbol_tag_value_set
}
},
"configuration": True,
"codeLens": {
"refreshSupport": True
},
"inlayHint": {
"refreshSupport": True
},
"semanticTokens": {
"refreshSupport": True
},
"diagnostics": {
"refreshSupport": True
}
}
window_capabilities: WindowClientCapabilities = {
"showDocument": {
"support": True
},
"showMessage": {
"messageActionItem": {
"additionalPropertiesSupport": True
}
},
"workDoneProgress": True
}
capabilities: ClientCapabilities = {
"general": general_capabilities,
"textDocument": text_document_capabilities,
"workspace": workspace_capabilites,
"window": window_capabilities,
}
if config.experimental_capabilities is not None:
capabilities['experimental'] = cast(LSPObject, config.experimental_capabilities)
if get_file_watcher_implementation():
workspace_capabilites["didChangeWatchedFiles"] = {"dynamicRegistration": True}
return {
"processId": os.getpid(),
"clientInfo": {
"name": "Sublime Text LSP",
"version": ".".join(map(str, __version__))
},
"rootUri": first_folder.uri() if first_folder else None,
"rootPath": first_folder.path if first_folder else None,
"workspaceFolders": [folder.to_lsp() for folder in workspace_folders] if workspace_folders else None,
"capabilities": capabilities,
"initializationOptions": cast(LSPAny, config.init_options.get_resolved(variables))
}
class SessionViewProtocol(Protocol):
@property
def session(self) -> Session:
...
@property
def view(self) -> sublime.View:
...
@property
def listener(self) -> weakref.ref[AbstractViewListener]:
...
@property
def session_buffer(self) -> SessionBufferProtocol:
...
def get_uri(self) -> DocumentUri | None:
...
def get_language_id(self) -> str | None:
...
def get_view_for_group(self, group: int) -> sublime.View | None:
...
def on_capability_added_async(self, registration_id: str, capability_path: str, options: dict[str, Any]) -> None:
...
def on_capability_removed_async(self, registration_id: str, discarded_capabilities: dict[str, Any]) -> None:
...
def has_capability_async(self, capability_path: str) -> bool:
...
def shutdown_async(self) -> None:
...
def present_diagnostics_async(self, is_view_visible: bool) -> None:
...
def on_request_started_async(self, request_id: int, request: Request) -> None:
...
def on_request_finished_async(self, request_id: int) -> None:
...
def on_request_progress(self, request_id: int, params: dict[str, Any]) -> None:
...
def get_resolved_code_lenses_for_region(self, region: sublime.Region) -> Generator[CodeLensExtended, None, None]:
...
def start_code_lenses_async(self) -> None:
...
def clear_code_lenses_async(self) -> None:
...
def set_code_lenses_pending_refresh(self, needs_refresh: bool = True) -> None:
...
def reset_show_definitions(self) -> None:
...
def on_userprefs_changed_async(self) -> None:
...
class SessionBufferProtocol(Protocol):
@property
def session(self) -> Session:
...
@property
def session_views(self) -> WeakSet[SessionViewProtocol]:
...
@property
def version(self) -> int | None:
...
def get_uri(self) -> str | None:
...
def get_language_id(self) -> str | None:
...
def get_view_in_group(self, group: int) -> sublime.View:
...
def register_capability_async(
self,
registration_id: str,
capability_path: str,
registration_path: str,
options: dict[str, Any]
) -> None:
...
def unregister_capability_async(
self,
registration_id: str,
capability_path: str,
registration_path: str
) -> None:
...
def get_capability(self, capability_path: str) -> Any | None:
...
def has_capability(self, capability_path: str) -> bool:
...
def on_userprefs_changed_async(self) -> None:
...
def on_diagnostics_async(
self, raw_diagnostics: list[Diagnostic], version: int | None, visible_session_views: set[SessionViewProtocol]
) -> None:
...
def get_document_link_at_point(self, view: sublime.View, point: int) -> DocumentLink | None:
...
def update_document_link(self, new_link: DocumentLink) -> None:
...
def do_semantic_tokens_async(self, view: sublime.View) -> None:
...
def set_semantic_tokens_pending_refresh(self, needs_refresh: bool = ...) -> None:
...
def get_semantic_tokens(self) -> list[Any]:
...
def do_inlay_hints_async(self, view: sublime.View) -> None:
...
def set_inlay_hints_pending_refresh(self, needs_refresh: bool = ...) -> None:
...
def remove_inlay_hint_phantom(self, phantom_uuid: str) -> None:
...
def do_document_diagnostic_async(
self, view: sublime.View, version: int | None = ..., *, forced_update: bool = ...
) -> None:
...
def set_document_diagnostic_pending_refresh(self, needs_refresh: bool = ...) -> None:
...
class AbstractViewListener(metaclass=ABCMeta):
TOTAL_ERRORS_AND_WARNINGS_STATUS_KEY = "lsp_total_errors_and_warnings"
view = cast(sublime.View, None)
hover_provider_count = 0
@abstractmethod
def session_async(self, capability: str, point: int | None = None) -> Session | None:
raise NotImplementedError()
@abstractmethod
def sessions_async(self, capability: str | None = None) -> list[Session]:
raise NotImplementedError()
@abstractmethod
def session_buffers_async(self, capability: str | None = None) -> list[SessionBufferProtocol]:
raise NotImplementedError()
@abstractmethod
def session_views_async(self) -> list[SessionViewProtocol]:
raise NotImplementedError()
@abstractmethod
def purge_changes_async(self) -> None:
raise NotImplementedError()
@abstractmethod
def on_session_initialized_async(self, session: Session) -> None:
raise NotImplementedError()
@abstractmethod
def on_session_shutdown_async(self, session: Session) -> None:
raise NotImplementedError()
@abstractmethod
def diagnostics_intersecting_region_async(
self,
region: sublime.Region
) -> tuple[list[tuple[SessionBufferProtocol, list[Diagnostic]]], sublime.Region]:
raise NotImplementedError()
@abstractmethod
def diagnostics_touching_point_async(
self,
pt: int,
max_diagnostic_severity_level: int = DiagnosticSeverity.Hint
) -> tuple[list[tuple[SessionBufferProtocol, list[Diagnostic]]], sublime.Region]:
raise NotImplementedError()
def diagnostics_intersecting_async(
self,
region_or_point: sublime.Region | int
) -> tuple[list[tuple[SessionBufferProtocol, list[Diagnostic]]], sublime.Region]:
if isinstance(region_or_point, int):
return self.diagnostics_touching_point_async(region_or_point)
elif region_or_point.empty():
return self.diagnostics_touching_point_async(region_or_point.a)
else:
return self.diagnostics_intersecting_region_async(region_or_point)
@abstractmethod
def on_diagnostics_updated_async(self, is_view_visible: bool) -> None:
raise NotImplementedError()
@abstractmethod
def on_code_lens_capability_registered_async(self) -> None:
raise NotImplementedError()
@abstractmethod
def get_language_id(self) -> str:
raise NotImplementedError()
@abstractmethod
def get_uri(self) -> DocumentUri:
raise NotImplementedError()
@abstractmethod
def do_signature_help_async(self, manual: bool) -> None:
raise NotImplementedError()
@abstractmethod
def navigate_signature_help(self, forward: bool) -> None:
raise NotImplementedError()
@abstractmethod
def on_post_move_window_async(self) -> None:
raise NotImplementedError()
class AbstractPlugin(metaclass=ABCMeta):
"""
Inherit from this class to handle non-standard requests and notifications.
Given a request/notification, replace the non-alphabetic characters with an underscore, and prepend it with "m_".
This will be the name of your method.
For instance, to implement the non-standard eslint/openDoc request, define the Python method
def m_eslint_openDoc(self, params, request_id):
session = self.weaksession()
if session:
webbrowser.open_tab(params['url'])
session.send_response(Response(request_id, None))
To handle the non-standard eslint/status notification, define the Python method
def m_eslint_status(self, params):
pass
To understand how this works, see the __getattr__ method of the Session class.
"""
@classmethod
@abstractmethod
def name(cls) -> str:
"""
A human-friendly name. If your plugin is called "LSP-foobar", then this should return "foobar". If you also
have your settings file called "LSP-foobar.sublime-settings", then you don't even need to re-implement the
configuration method (see below).
"""
raise NotImplementedError()
@classmethod
def configuration(cls) -> tuple[sublime.Settings, str]:
"""
Return the Settings object that defines the "command", "languages", and optionally the "initializationOptions",
"default_settings", "env" and "tcp_port" as the first element in the tuple, and the path to the base settings
filename as the second element in the tuple.
The second element in the tuple is used to handle "settings" overrides from users properly. For example, if your
plugin is called LSP-foobar, you would return "Packages/LSP-foobar/LSP-foobar.sublime-settings".
The "command", "initializationOptions" and "env" are subject to template string substitution. The following
template strings are recognized:
$file
$file_base_name
$file_extension
$file_name
$file_path
$platform
$project
$project_base_name
$project_extension
$project_name
$project_path
These are just the values from window.extract_variables(). Additionally,
$storage_path The path to the package storage (see AbstractPlugin.storage_path)
$cache_path sublime.cache_path()
$temp_dir tempfile.gettempdir()
$home os.path.expanduser('~')
$port A random free TCP-port on localhost in case "tcp_port" is set to 0. This string template can only
be used in the "command"
The "command" and "env" are expanded upon starting the subprocess of the Session. The "initializationOptions"
are expanded upon doing the initialize request. "initializationOptions" does not expand $port.
When you're managing your own server binary, you would typically place it in sublime.cache_path(). So your
"command" should look like this: "command": ["$cache_path/LSP-foobar/server_binary", "--stdio"]
"""
name = cls.name()
basename = f"LSP-{name}.sublime-settings"
filepath = f"Packages/LSP-{name}/{basename}"
return sublime.load_settings(basename), filepath
@classmethod
def additional_variables(cls) -> dict[str, str] | None:
"""
In addition to the above variables, add more variables here to be expanded.
"""
return None
@classmethod
def storage_path(cls) -> str:
"""
The storage path. Use this as your base directory to install server files. Its path is '$DATA/Package Storage'.
You should have an additional subdirectory preferably the same name as your plugin. For instance:
```python
from LSP.plugin import AbstractPlugin
import os
class MyPlugin(AbstractPlugin):
@classmethod
def name(cls) -> str:
return "my-plugin"
@classmethod
def basedir(cls) -> str:
# Do everything relative to this directory
return os.path.join(cls.storage_path(), cls.name())
```
"""
return get_storage_path()
@classmethod
def needs_update_or_installation(cls) -> bool:
"""
If this plugin manages its own server binary, then this is the place to check whether the binary needs
an update, or whether it needs to be installed before starting the language server.
"""
return False
@classmethod
def install_or_update(cls) -> None:
"""
Do the actual update/installation of the server binary. This runs in a separate thread, so don't spawn threads
yourself here.
"""
pass
@classmethod
def can_start(cls, window: sublime.Window, initiating_view: sublime.View,
workspace_folders: list[WorkspaceFolder], configuration: ClientConfig) -> str | None:
"""
Determines ability to start. This is called after needs_update_or_installation and after install_or_update.
So you may assume that if you're managing your server binary, then it is already installed when this
classmethod is called.
:param window: The window
:param initiating_view: The initiating view
:param workspace_folders: The workspace folders
:param configuration: The configuration
:returns: A string describing the reason why we should not start a language server session, or None if we
should go ahead and start a session.
"""
return None
@classmethod
def on_pre_start(cls, window: sublime.Window, initiating_view: sublime.View,
workspace_folders: list[WorkspaceFolder], configuration: ClientConfig) -> str | None:
"""
Callback invoked just before the language server subprocess is started. This is the place to do last-minute
adjustments to your "command" or "init_options" in the passed-in "configuration" argument, or change the
order of the workspace folders. You can also choose to return a custom working directory, but consider that a
language server should not care about the working directory.
:param window: The window
:param initiating_view: The initiating view
:param workspace_folders: The workspace folders, you can modify these
:param configuration: The configuration, you can modify this one
:returns: A desired working directory, or None if you don't care
"""
return None
@classmethod
def on_post_start(cls, window: sublime.Window, initiating_view: sublime.View,
workspace_folders: list[WorkspaceFolder], configuration: ClientConfig) -> None:
"""
Callback invoked when the subprocess was just started.
:param window: The window
:param initiating_view: The initiating view
:param workspace_folders: The workspace folders
:param configuration: The configuration
"""
pass
@classmethod
def should_ignore(cls, view: sublime.View) -> bool:
"""
Exclude a view from being handled by the language server, even if it matches the URI scheme(s) and selector from
the configuration. This can be used to, for example, ignore certain file patterns which are listed in a
configuration file (e.g. .gitignore). Please note that this also means that no document syncronization
notifications (textDocument/didOpen, textDocument/didChange, textDocument/didClose, etc.) are sent to the server
for ignored views, when they are opened in the editor. Therefore this method should be used with caution for
language servers which index all files in the workspace.
"""
return False
@classmethod
def markdown_language_id_to_st_syntax_map(cls) -> MarkdownLangMap | None:
"""
Override this method to tweak the syntax highlighting of code blocks in popups from your language server.
The returned object should be a dictionary exactly in the form of mdpopup's language_map setting.
See: https://facelessuser.github.io/sublime-markdown-popups/settings/#mdpopupssublime_user_lang_map
:returns: The markdown language map, or None
"""
return None
def __init__(self, weaksession: weakref.ref[Session]) -> None:
"""
Constructs a new instance. Your instance is constructed after a response to the initialize request.
:param weaksession: A weak reference to the Session. You can grab a strong reference through
self.weaksession(), but don't hold on to that reference.
"""
self.weaksession = weaksession
def on_settings_changed(self, settings: DottedDict) -> None:
"""
Override this method to alter the settings that are returned to the server for the
workspace/didChangeConfiguration notification and the workspace/configuration requests.
:param settings: The settings that the server should receive.
"""