-
Notifications
You must be signed in to change notification settings - Fork 184
/
Copy pathsessions.py
2027 lines (1746 loc) · 83.7 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 .collections import DottedDict
from .diagnostics_storage import DiagnosticsStorage
from .edit import apply_edits
from .edit import parse_workspace_edit
from .edit import TextEditTuple
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 DiagnosticSeverity
from .protocol import DiagnosticTag
from .protocol import DidChangeWatchedFilesRegistrationOptions
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 GeneralClientCapabilities
from .protocol import InsertTextMode
from .protocol import Location
from .protocol import LocationLink
from .protocol import LSPObject
from .protocol import MarkupKind
from .protocol import Notification
from .protocol import PublishDiagnosticsParams
from .protocol import Range
from .protocol import Request
from .protocol import Response
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 TokenFormat
from .protocol import WindowClientCapabilities
from .protocol import WorkspaceClientCapabilities
from .protocol import WorkspaceEdit
from .settings import client_configs
from .settings import globalprefs
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 .typing import Callable, cast, Dict, Any, Optional, List, Tuple, Generator, Iterable, Type, Protocol, Mapping, TypeVar, Union # noqa: E501
from .url import filename_to_uri
from .url import parse_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 .views import SEMANTIC_TOKENS_MAP
from .workspace import is_subpath_of
from .workspace import WorkspaceFolder
from abc import ABCMeta
from abc import abstractmethod
from weakref import WeakSet
import functools
import mdpopups
import os
import sublime
import weakref
InitCallback = Callable[['Session', bool], None]
T = TypeVar('T')
def get_semantic_tokens_map(custom_tokens_map: Optional[Dict[str, str]]) -> 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], Optional[str]]:
"""
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 = "{}.{}".format(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 += " meta.semantic-token.{}.{}.lsp".format(token_type.lower(), token_modifiers[0].lower())
else:
scope += " meta.semantic-token.{}.lsp".format(token_type.lower())
return token_type, token_modifiers, scope
class Manager(metaclass=ABCMeta):
"""
A Manager is a container of Sessions.
"""
# Observers
@abstractmethod
def window(self) -> sublime.Window:
"""
Get the window associated with this manager.
"""
pass
@abstractmethod
def sessions(self, view: sublime.View, capability: Optional[str] = None) -> 'Generator[Session, None, None]':
"""
Iterate over the sessions stored in this manager, applicable to the given view, with the given capability.
"""
pass
@abstractmethod
def get_project_path(self, file_path: str) -> Optional[str]:
"""
Get the project path for the given file.
"""
pass
@abstractmethod
def should_present_diagnostics(self, uri: DocumentUri) -> Optional[str]:
"""
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.
"""
pass
@abstractmethod
def on_diagnostics_updated(self) -> None:
pass
@abstractmethod
def show_diagnostics_panel_async(self) -> None:
pass
@abstractmethod
def hide_diagnostics_panel_async(self) -> None:
pass
# Event callbacks
@abstractmethod
def on_post_exit_async(self, session: 'Session', exit_code: int, exception: Optional[Exception]) -> None:
"""
The given Session has stopped with the given exit code.
"""
pass
def _enum_like_class_to_list(c: Type[object]) -> List[Union[int, str]]:
return [v for k, v in c.__dict__.items() if not k.startswith('_')]
def get_initialize_params(variables: Dict[str, str], workspace_folders: List[WorkspaceFolder],
config: ClientConfig) -> dict:
completion_kinds = cast(List[CompletionItemKind], _enum_like_class_to_list(CompletionItemKind))
symbol_kinds = cast(List[SymbolKind], _enum_like_class_to_list(SymbolKind))
diagnostic_tag_value_set = cast(List[DiagnosticTag], _enum_like_class_to_list(DiagnosticTag))
completion_tag_value_set = cast(List[CompletionItemTag], _enum_like_class_to_list(CompletionItemTag))
symbol_tag_value_set = cast(List[SymbolTag], _enum_like_class_to_list(SymbolTag))
semantic_token_types = cast(List[str], _enum_like_class_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], _enum_like_class_to_list(SemanticTokenModifiers))
first_folder = workspace_folders[0] if workspace_folders else None
general_capabilities = {
# 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
}
} # type: GeneralClientCapabilities
text_document_capabilities = {
"synchronization": {
"dynamicRegistration": True, # exceptional
"didSave": True,
"willSave": True,
"willSaveWaitUntil": True
},
"hover": {
"dynamicRegistration": True,
"contentFormat": [MarkupKind.Markdown, MarkupKind.PlainText]
},
"completion": {
"dynamicRegistration": True,
"completionItem": {
"snippetSupport": True,
"deprecatedSupport": True,
"documentationFormat": [MarkupKind.Markdown, MarkupKind.PlainText],
"tagSupport": {
"valueSet": completion_tag_value_set
},
"resolveSupport": {
"properties": ["detail", "documentation", "additionalTextEdits"]
},
"insertReplaceSupport": True,
"insertTextModeSupport": {
"valueSet": [InsertTextMode.AdjustIndentation]
},
"labelDetailsSupport": True
},
"completionItemKind": {
"valueSet": completion_kinds
},
"insertTextMode": InsertTextMode.AdjustIndentation
},
"signatureHelp": {
"dynamicRegistration": True,
"contextSupport": True,
"signatureInformation": {
"activeParameterSupport": True,
"documentationFormat": [MarkupKind.Markdown, MarkupKind.PlainText],
"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
},
"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": [
CodeActionKind.QuickFix,
CodeActionKind.Refactor,
CodeActionKind.RefactorExtract,
CodeActionKind.RefactorInline,
CodeActionKind.RefactorRewrite,
CodeActionKind.SourceOrganizeImports,
]
}
},
"dataSupport": True,
"disabledSupport": True,
"isPreferredSupport": True,
"resolveSupport": {
"properties": [
"edit"
]
}
},
"rename": {
"dynamicRegistration": True,
"prepareSupport": True
},
"colorProvider": {
"dynamicRegistration": True # exceptional
},
"publishDiagnostics": {
"relatedInformation": True,
"tagSupport": {
"valueSet": diagnostic_tag_value_set
},
"versionSupport": True,
"codeDescriptionSupport": True,
"dataSupport": True
},
"selectionRange": {
"dynamicRegistration": True
},
"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": [
TokenFormat.Relative
],
"overlappingTokenSupport": False,
"multilineTokenSupport": True,
"augmentsSyntaxTokens": True
}
} # type: TextDocumentClientCapabilities
workspace_capabilites = {
"applyEdit": True,
"didChangeConfiguration": {
"dynamicRegistration": True
},
"executeCommand": {},
"workspaceEdit": {
"documentChanges": True,
"failureHandling": FailureHandlingKind.Abort,
},
"workspaceFolders": True,
"symbol": {
"dynamicRegistration": True, # exceptional
"symbolKind": {
"valueSet": symbol_kinds
},
"tagSupport": {
"valueSet": symbol_tag_value_set
}
},
"configuration": True,
"codeLens": {
"refreshSupport": True
},
"inlayHint": {
"refreshSupport": True
},
"semanticTokens": {
"refreshSupport": True
}
} # type: WorkspaceClientCapabilities
window_capabilities = {
"showDocument": {
"support": True
},
"showMessage": {
"messageActionItem": {
"additionalPropertiesSupport": True
}
},
"workDoneProgress": True
} # type: WindowClientCapabilities
capabilities = {
"general": general_capabilities,
"textDocument": text_document_capabilities,
"workspace": workspace_capabilites,
"window": window_capabilities,
} # type: ClientCapabilities
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": 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) -> Optional[str]:
...
def get_language_id(self) -> Optional[str]:
...
def get_view_for_group(self, group: int) -> Optional[sublime.View]:
...
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) -> 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 set_code_lenses_pending_refresh(self, needs_refresh: bool = True) -> None:
...
class SessionBufferProtocol(Protocol):
@property
def session(self) -> 'Session':
...
@property
def session_views(self) -> 'WeakSet[SessionViewProtocol]':
...
def get_uri(self) -> Optional[str]:
...
def get_language_id(self) -> Optional[str]:
...
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 on_diagnostics_async(self, raw_diagnostics: List[Diagnostic], version: Optional[int]) -> None:
...
def get_document_link_at_point(self, view: sublime.View, point: int) -> Optional[DocumentLink]:
...
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 = True) -> 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 = True) -> None:
...
def remove_inlay_hint_phantom(self, phantom_uuid: str) -> None:
...
class AbstractViewListener(metaclass=ABCMeta):
TOTAL_ERRORS_AND_WARNINGS_STATUS_KEY = "lsp_total_errors_and_warnings"
view = cast(sublime.View, None)
@abstractmethod
def session_async(self, capability_path: str, point: Optional[int] = None) -> Optional['Session']:
raise NotImplementedError()
@abstractmethod
def sessions_async(self, capability_path: Optional[str] = None) -> Generator['Session', None, None]:
raise NotImplementedError()
@abstractmethod
def session_views_async(self) -> Iterable['SessionViewProtocol']:
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: Union[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) -> 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) -> str:
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 = "LSP-{}.sublime-settings".format(name)
filepath = "Packages/LSP-{}/{}".format(name, basename)
return sublime.load_settings(basename), filepath
@classmethod
def additional_variables(cls) -> Optional[Dict[str, str]]:
"""
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 preferrably 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) -> Optional[str]:
"""
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) -> Optional[str]:
"""
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 markdown_language_id_to_st_syntax_map(cls) -> Optional[MarkdownLangMap]:
"""
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.
"""
pass
def on_workspace_configuration(self, params: Dict, configuration: Any) -> None:
"""
Override to augment configuration returned for the workspace/configuration request.
:param params: A ConfigurationItem for which configuration is requested.
:param configuration: The resolved configuration for given params.
"""
pass
def on_pre_server_command(self, command: Mapping[str, Any], done_callback: Callable[[], None]) -> bool:
"""
Intercept a command that is about to be sent to the language server.
:param command: The payload containing a "command" and optionally "arguments".
:param done_callback: The callback that you promise to invoke when you return true.
:returns: True if *YOU* will handle this command plugin-side, false otherwise. You must invoke the
passed `done_callback` when you're done.
"""
return False
def on_pre_send_request_async(self, request_id: int, request: Request) -> None:
"""
Notifies about a request that is about to be sent to the language server.
This API is triggered on async thread.
:param request_id: The request ID.
:param request: The request object. The request params can be modified by the plugin.
"""
pass
def on_pre_send_notification_async(self, notification: Notification) -> None:
"""
Notifies about a notification that is about to be sent to the language server.
This API is triggered on async thread.
:param notification: The notification object. The notification params can be modified by the plugin.
"""
pass
def on_server_response_async(self, method: str, response: Response) -> None:
"""
Notifies about a response message that has been received from the language server.
Only successful responses are passed to this method.
:param method: The method of the request.
:param response: The response object to the request. The response.result field can be modified by the
plugin, before it gets further handled by the LSP package.
"""
pass
def on_open_uri_async(self, uri: DocumentUri, callback: Callable[[str, str, str], None]) -> bool:
"""
Called when a language server reports to open an URI. If you know how to handle this URI, then return True and
invoke the passed-in callback some time.
The arguments of the provided callback work as follows:
- The first argument is the title of the view that will be populated with the content of a new scratch view
- The second argument is the content of the view
- The third argument is the syntax to apply for the new view
"""
return False
def on_session_buffer_changed_async(self, session_buffer: SessionBufferProtocol) -> None:
"""
Called when the context of the session buffer has changed or a new buffer was opened.
"""
pass
def on_session_end_async(self) -> None:
"""
Notifies about the session ending (also if the session has crashed). Provides an opportunity to clean up
any stored state or delete references to the session or plugin instance that would otherwise prevent the
instance from being garbage-collected. If the plugin hasn't crashed, a shutdown message will be send immediately
after this method returns.
This API is triggered on async thread.
"""
pass
_plugins = {} # type: Dict[str, Tuple[Type[AbstractPlugin], SettingsRegistration]]
def _register_plugin_impl(plugin: Type[AbstractPlugin], notify_listener: bool) -> None:
global _plugins
name = plugin.name()
if name in _plugins:
return
try:
settings, base_file = plugin.configuration()
if client_configs.add_external_config(name, settings, base_file, notify_listener):
on_change = functools.partial(client_configs.update_external_config, name, settings, base_file)
_plugins[name] = (plugin, SettingsRegistration(settings, on_change))
except Exception as ex:
exception_log('Failed to register plugin "{}"'.format(name), ex)
def register_plugin(plugin: Type[AbstractPlugin], notify_listener: bool = True) -> None:
"""
Register an LSP plugin in LSP.
You should put a call to this function in your `plugin_loaded` callback. This way, when your package is disabled
by a user and then re-enabled again by a user, the changes in state are picked up by LSP, and your language server
will start for the relevant views.
While your helper package may still work without calling `register_plugin` in `plugin_loaded`, the user will have a
better experience when you do call this function.
Your implementation should look something like this:
```python
from LSP.plugin import register_plugin
from LSP.plugin import unregister_plugin
from LSP.plugin import AbstractPlugin
class MyPlugin(AbstractPlugin):
...
def plugin_loaded():
register_plugin(MyPlugin)
def plugin_unloaded():
unregister_plugin(MyPlugin)
```