-
Notifications
You must be signed in to change notification settings - Fork 45
/
server.py
733 lines (642 loc) · 24.2 KB
/
server.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
"""Jedi Language Server.
Creates the language server constant and wraps "features" with it.
Official language server spec:
https://microsoft.github.io/language-server-protocol/specification
"""
import itertools
from typing import Any, List, Optional, Union
import cattrs
from jedi import Project, __version__
from jedi.api.refactoring import RefactoringError
from lsprotocol.types import (
COMPLETION_ITEM_RESOLVE,
INITIALIZE,
TEXT_DOCUMENT_CODE_ACTION,
TEXT_DOCUMENT_COMPLETION,
TEXT_DOCUMENT_DEFINITION,
TEXT_DOCUMENT_DID_CHANGE,
TEXT_DOCUMENT_DID_CLOSE,
TEXT_DOCUMENT_DID_OPEN,
TEXT_DOCUMENT_DID_SAVE,
TEXT_DOCUMENT_DOCUMENT_HIGHLIGHT,
TEXT_DOCUMENT_DOCUMENT_SYMBOL,
TEXT_DOCUMENT_HOVER,
TEXT_DOCUMENT_REFERENCES,
TEXT_DOCUMENT_RENAME,
TEXT_DOCUMENT_SIGNATURE_HELP,
TEXT_DOCUMENT_TYPE_DEFINITION,
WORKSPACE_DID_CHANGE_CONFIGURATION,
WORKSPACE_SYMBOL,
CodeAction,
CodeActionKind,
CodeActionOptions,
CodeActionParams,
CompletionItem,
CompletionList,
CompletionOptions,
CompletionParams,
DidChangeConfigurationParams,
DidChangeTextDocumentParams,
DidCloseTextDocumentParams,
DidOpenTextDocumentParams,
DidSaveTextDocumentParams,
DocumentHighlight,
DocumentSymbol,
DocumentSymbolParams,
Hover,
InitializeParams,
InitializeResult,
Location,
MarkupContent,
MarkupKind,
MessageType,
ParameterInformation,
RenameParams,
SignatureHelp,
SignatureHelpOptions,
SignatureInformation,
SymbolInformation,
TextDocumentPositionParams,
WorkspaceEdit,
WorkspaceSymbolParams,
)
from pygls.capabilities import get_capability
from pygls.protocol import LanguageServerProtocol, lsp_method
from pygls.server import LanguageServer
from . import jedi_utils, pygls_utils, text_edit_utils
from .initialization_options import (
InitializationOptions,
initialization_options_converter,
)
class JediLanguageServerProtocol(LanguageServerProtocol):
"""Override some built-in functions."""
_server: "JediLanguageServer"
@lsp_method(INITIALIZE)
def lsp_initialize(self, params: InitializeParams) -> InitializeResult:
"""Override built-in initialization.
Here, we can conditionally register functions to features based
on client capabilities and initializationOptions.
"""
server = self._server
try:
server.initialization_options = (
initialization_options_converter.structure(
{}
if params.initialization_options is None
else params.initialization_options,
InitializationOptions,
)
)
except cattrs.BaseValidationError as error:
msg = (
"Invalid InitializationOptions, using defaults:"
f" {cattrs.transform_error(error)}"
)
server.show_message(msg, msg_type=MessageType.Error)
server.show_message_log(msg, msg_type=MessageType.Error)
server.initialization_options = InitializationOptions()
initialization_options = server.initialization_options
jedi_utils.set_jedi_settings(initialization_options)
# Configure didOpen, didChange, and didSave
# currently need to be configured manually
diagnostics = initialization_options.diagnostics
did_open = (
did_open_diagnostics
if diagnostics.enable and diagnostics.did_open
else did_open_default
)
did_change = (
did_change_diagnostics
if diagnostics.enable and diagnostics.did_change
else did_change_default
)
did_save = (
did_save_diagnostics
if diagnostics.enable and diagnostics.did_save
else did_save_default
)
did_close = (
did_close_diagnostics if diagnostics.enable else did_close_default
)
server.feature(TEXT_DOCUMENT_DID_OPEN)(did_open)
server.feature(TEXT_DOCUMENT_DID_CHANGE)(did_change)
server.feature(TEXT_DOCUMENT_DID_SAVE)(did_save)
server.feature(TEXT_DOCUMENT_DID_CLOSE)(did_close)
if server.initialization_options.hover.enable:
server.feature(TEXT_DOCUMENT_HOVER)(hover)
initialize_result: InitializeResult = super().lsp_initialize(params)
workspace_options = initialization_options.workspace
server.project = (
Project(
path=server.workspace.root_path,
environment_path=workspace_options.environment_path,
added_sys_path=workspace_options.extra_paths,
smart_sys_path=True,
load_unsafe_extensions=False,
)
if server.workspace.root_path
else None
)
return initialize_result
class JediLanguageServer(LanguageServer):
"""Jedi language server.
:attr initialization_options: initialized in lsp_initialize from the
protocol_cls.
:attr project: a Jedi project. This value is created in
`JediLanguageServerProtocol.lsp_initialize`.
"""
initialization_options: InitializationOptions
project: Optional[Project]
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
SERVER = JediLanguageServer(
name="jedi-language-server",
version=__version__,
protocol_cls=JediLanguageServerProtocol,
)
# Server capabilities
@SERVER.feature(COMPLETION_ITEM_RESOLVE)
def completion_item_resolve(
server: JediLanguageServer, params: CompletionItem
) -> CompletionItem:
"""Resolves documentation and detail of given completion item."""
markup_kind = _choose_markup(server)
return jedi_utils.lsp_completion_item_resolve(
params, markup_kind=markup_kind
)
@SERVER.feature(
TEXT_DOCUMENT_COMPLETION,
CompletionOptions(
trigger_characters=[".", "'", '"'], resolve_provider=True
),
)
def completion(
server: JediLanguageServer, params: CompletionParams
) -> Optional[CompletionList]:
"""Returns completion items."""
snippet_disable = server.initialization_options.completion.disable_snippets
resolve_eagerly = server.initialization_options.completion.resolve_eagerly
ignore_patterns = server.initialization_options.completion.ignore_patterns
document = server.workspace.get_text_document(params.text_document.uri)
jedi_script = jedi_utils.script(server.project, document)
jedi_lines = jedi_utils.line_column(params.position)
completions_jedi_raw = jedi_script.complete(*jedi_lines)
if not ignore_patterns:
# A performance optimization. ignore_patterns should usually be empty;
# this special case avoid repeated filter checks for the usual case.
completions_jedi = (comp for comp in completions_jedi_raw)
else:
completions_jedi = (
comp
for comp in completions_jedi_raw
if not any(i.match(comp.name) for i in ignore_patterns)
)
snippet_support = get_capability(
server.client_capabilities,
"text_document.completion.completion_item.snippet_support",
False,
)
markup_kind = _choose_markup(server)
is_import_context = jedi_utils.is_import(
script_=jedi_script,
line=jedi_lines[0],
column=jedi_lines[1],
)
enable_snippets = (
snippet_support and not snippet_disable and not is_import_context
)
char_before_cursor = pygls_utils.char_before_cursor(
document=server.workspace.get_text_document(params.text_document.uri),
position=params.position,
)
jedi_utils.clear_completions_cache()
# number of characters in the string representation of the total number of
# completions returned by jedi.
total_completion_chars = len(str(len(completions_jedi_raw)))
completion_items = [
jedi_utils.lsp_completion_item(
completion=completion,
char_before_cursor=char_before_cursor,
enable_snippets=enable_snippets,
resolve_eagerly=resolve_eagerly,
markup_kind=markup_kind,
sort_append_text=str(count).zfill(total_completion_chars),
)
for count, completion in enumerate(completions_jedi)
]
return (
CompletionList(is_incomplete=False, items=completion_items)
if completion_items
else None
)
@SERVER.feature(
TEXT_DOCUMENT_SIGNATURE_HELP,
SignatureHelpOptions(trigger_characters=["(", ","]),
)
def signature_help(
server: JediLanguageServer, params: TextDocumentPositionParams
) -> Optional[SignatureHelp]:
"""Returns signature help.
Note: for docstring, we currently choose plaintext because coc doesn't
handle markdown well in the signature. Will update if this changes in the
future.
"""
document = server.workspace.get_text_document(params.text_document.uri)
jedi_script = jedi_utils.script(server.project, document)
jedi_lines = jedi_utils.line_column(params.position)
signatures_jedi = jedi_script.get_signatures(*jedi_lines)
markup_kind = _choose_markup(server)
signatures = [
SignatureInformation(
label=jedi_utils.signature_string(signature),
documentation=MarkupContent(
kind=markup_kind,
value=jedi_utils.convert_docstring(
signature.docstring(raw=True),
markup_kind,
),
),
parameters=[
ParameterInformation(label=info.to_string())
for info in signature.params
],
)
for signature in signatures_jedi
]
return (
SignatureHelp(
signatures=signatures,
active_signature=0,
active_parameter=(
signatures_jedi[0].index if signatures_jedi else 0
),
)
if signatures
else None
)
@SERVER.feature(TEXT_DOCUMENT_DEFINITION)
def definition(
server: JediLanguageServer, params: TextDocumentPositionParams
) -> Optional[List[Location]]:
"""Support Goto Definition."""
document = server.workspace.get_text_document(params.text_document.uri)
jedi_script = jedi_utils.script(server.project, document)
jedi_lines = jedi_utils.line_column(params.position)
names = jedi_script.goto(
*jedi_lines,
follow_imports=True,
follow_builtin_imports=True,
)
definitions = [
definition
for definition in (jedi_utils.lsp_location(name) for name in names)
if definition is not None
]
return definitions if definitions else None
@SERVER.feature(TEXT_DOCUMENT_TYPE_DEFINITION)
def type_definition(
server: JediLanguageServer, params: TextDocumentPositionParams
) -> Optional[List[Location]]:
"""Support Goto Type Definition."""
document = server.workspace.get_text_document(params.text_document.uri)
jedi_script = jedi_utils.script(server.project, document)
jedi_lines = jedi_utils.line_column(params.position)
names = jedi_script.infer(*jedi_lines)
definitions = [
definition
for definition in (jedi_utils.lsp_location(name) for name in names)
if definition is not None
]
return definitions if definitions else None
@SERVER.feature(TEXT_DOCUMENT_DOCUMENT_HIGHLIGHT)
def highlight(
server: JediLanguageServer, params: TextDocumentPositionParams
) -> Optional[List[DocumentHighlight]]:
"""Support document highlight request.
This function is called frequently, so we minimize the number of expensive
calls. These calls are:
1. Getting assignment of current symbol (script.goto)
2. Getting all names in the current script (script.get_names)
Finally, we only return names if there are more than 1. Otherwise, we don't
want to highlight anything.
"""
document = server.workspace.get_text_document(params.text_document.uri)
jedi_script = jedi_utils.script(server.project, document)
jedi_lines = jedi_utils.line_column(params.position)
names = jedi_script.get_references(*jedi_lines, scope="file")
lsp_ranges = [jedi_utils.lsp_range(name) for name in names]
highlight_names = [
DocumentHighlight(range=lsp_range)
for lsp_range in lsp_ranges
if lsp_range
]
return highlight_names if highlight_names else None
# Registered with HOVER dynamically
def hover(
server: JediLanguageServer, params: TextDocumentPositionParams
) -> Optional[Hover]:
"""Support Hover."""
document = server.workspace.get_text_document(params.text_document.uri)
jedi_script = jedi_utils.script(server.project, document)
jedi_lines = jedi_utils.line_column(params.position)
markup_kind = _choose_markup(server)
hover_text = jedi_utils.hover_text(
jedi_script.help(*jedi_lines),
markup_kind,
server.initialization_options,
)
if not hover_text:
return None
contents = MarkupContent(kind=markup_kind, value=hover_text)
_range = pygls_utils.current_word_range(document, params.position)
return Hover(contents=contents, range=_range)
@SERVER.feature(TEXT_DOCUMENT_REFERENCES)
def references(
server: JediLanguageServer, params: TextDocumentPositionParams
) -> Optional[List[Location]]:
"""Obtain all references to text."""
document = server.workspace.get_text_document(params.text_document.uri)
jedi_script = jedi_utils.script(server.project, document)
jedi_lines = jedi_utils.line_column(params.position)
names = jedi_script.get_references(*jedi_lines)
locations = [
location
for location in (jedi_utils.lsp_location(name) for name in names)
if location is not None
]
return locations if locations else None
@SERVER.feature(TEXT_DOCUMENT_DOCUMENT_SYMBOL)
def document_symbol(
server: JediLanguageServer, params: DocumentSymbolParams
) -> Optional[Union[List[DocumentSymbol], List[SymbolInformation]]]:
"""Document Python document symbols, hierarchically if possible.
In Jedi, valid values for `name.type` are:
- `module`
- `class`
- `instance`
- `function`
- `param`
- `path`
- `keyword`
- `statement`
We do some cleaning here. For hierarchical symbols, names from scopes that
aren't directly accessible with dot notation are removed from display. For
non-hierarchical symbols, we simply remove `param` symbols. Others are
included for completeness.
"""
document = server.workspace.get_text_document(params.text_document.uri)
jedi_script = jedi_utils.script(server.project, document)
names = jedi_script.get_names(all_scopes=True, definitions=True)
if get_capability(
server.client_capabilities,
"text_document.document_symbol.hierarchical_document_symbol_support",
False,
):
document_symbols = jedi_utils.lsp_document_symbols(names)
return document_symbols if document_symbols else None
symbol_information = [
symbol_info
for symbol_info in (
jedi_utils.lsp_symbol_information(name)
for name in names
if name.type != "param"
)
if symbol_info is not None
]
return symbol_information if symbol_information else None
def _ignore_folder(path_check: str, jedi_ignore_folders: List[str]) -> bool:
"""Determines whether there's an ignore folder in the path.
Intended to be used with the `workspace_symbol` function
"""
for ignore_folder in jedi_ignore_folders:
if f"/{ignore_folder}/" in path_check:
return True
return False
@SERVER.feature(WORKSPACE_SYMBOL)
def workspace_symbol(
server: JediLanguageServer, params: WorkspaceSymbolParams
) -> Optional[List[SymbolInformation]]:
"""Document Python workspace symbols.
Returns up to maxSymbols, or all symbols if maxSymbols is <= 0, ignoring
the following symbols:
1. Those that don't have a module_path associated with them (built-ins)
2. Those that are not rooted in the current workspace.
3. Those whose folders contain a directory that is ignored (.venv, etc)
"""
if not server.project:
return None
names = server.project.complete_search(params.query)
workspace_root = server.workspace.root_path
ignore_folders = (
server.initialization_options.workspace.symbols.ignore_folders
)
unignored_names = (
name
for name in names
if name.module_path is not None
and str(name.module_path).startswith(workspace_root)
and not _ignore_folder(str(name.module_path), ignore_folders)
)
_symbols = (
symbol
for symbol in (
jedi_utils.lsp_symbol_information(name) for name in unignored_names
)
if symbol is not None
)
max_symbols = server.initialization_options.workspace.symbols.max_symbols
symbols = (
list(itertools.islice(_symbols, max_symbols))
if max_symbols > 0
else list(_symbols)
)
return symbols if symbols else None
@SERVER.feature(TEXT_DOCUMENT_RENAME)
def rename(
server: JediLanguageServer, params: RenameParams
) -> Optional[WorkspaceEdit]:
"""Rename a symbol across a workspace."""
document = server.workspace.get_text_document(params.text_document.uri)
jedi_script = jedi_utils.script(server.project, document)
jedi_lines = jedi_utils.line_column(params.position)
try:
refactoring = jedi_script.rename(*jedi_lines, new_name=params.new_name)
except RefactoringError:
return None
changes = text_edit_utils.lsp_document_changes(
server.workspace, refactoring
)
return WorkspaceEdit(document_changes=changes) if changes else None
@SERVER.feature(
TEXT_DOCUMENT_CODE_ACTION,
CodeActionOptions(
code_action_kinds=[
CodeActionKind.RefactorInline,
CodeActionKind.RefactorExtract,
],
),
)
def code_action(
server: JediLanguageServer, params: CodeActionParams
) -> Optional[List[CodeAction]]:
"""Get code actions.
Currently supports:
1. Inline variable
2. Extract variable
3. Extract function
"""
document = server.workspace.get_text_document(params.text_document.uri)
jedi_script = jedi_utils.script(server.project, document)
code_actions = []
jedi_lines = jedi_utils.line_column(params.range.start)
jedi_lines_extract = jedi_utils.line_column_range(params.range)
try:
if params.range.start.line != params.range.end.line:
# refactor this at some point; control flow with exception == bad
raise RefactoringError("inline only viable for single-line range")
inline_refactoring = jedi_script.inline(*jedi_lines)
except (RefactoringError, AttributeError, IndexError):
inline_changes = []
else:
inline_changes = text_edit_utils.lsp_document_changes(
server.workspace, inline_refactoring
)
if inline_changes:
code_actions.append(
CodeAction(
title="Inline variable",
kind=CodeActionKind.RefactorInline,
edit=WorkspaceEdit(
document_changes=inline_changes,
),
)
)
extract_var = (
server.initialization_options.code_action.name_extract_variable
)
try:
extract_variable_refactoring = jedi_script.extract_variable(
new_name=extract_var, **jedi_lines_extract
)
except (RefactoringError, AttributeError, IndexError):
extract_variable_changes = []
else:
extract_variable_changes = text_edit_utils.lsp_document_changes(
server.workspace, extract_variable_refactoring
)
if extract_variable_changes:
code_actions.append(
CodeAction(
title=f"Extract expression into variable '{extract_var}'",
kind=CodeActionKind.RefactorExtract,
edit=WorkspaceEdit(
document_changes=extract_variable_changes,
),
)
)
extract_func = (
server.initialization_options.code_action.name_extract_function
)
try:
extract_function_refactoring = jedi_script.extract_function(
new_name=extract_func, **jedi_lines_extract
)
except (RefactoringError, AttributeError, IndexError):
extract_function_changes = []
else:
extract_function_changes = text_edit_utils.lsp_document_changes(
server.workspace, extract_function_refactoring
)
if extract_function_changes:
code_actions.append(
CodeAction(
title=f"Extract expression into function '{extract_func}'",
kind=CodeActionKind.RefactorExtract,
edit=WorkspaceEdit(
document_changes=extract_function_changes,
),
)
)
return code_actions if code_actions else None
@SERVER.feature(WORKSPACE_DID_CHANGE_CONFIGURATION)
def did_change_configuration(
server: JediLanguageServer,
params: DidChangeConfigurationParams,
) -> None:
"""Implement event for workspace/didChangeConfiguration.
Currently does nothing, but necessary for pygls. See::
<https://github.com/pappasam/jedi-language-server/issues/58>
"""
# Static capability or initializeOptions functions that rely on a specific
# client capability or user configuration. These are associated with
# JediLanguageServer within JediLanguageServerProtocol.lsp_initialize
@jedi_utils.debounce(1, keyed_by="uri")
def _publish_diagnostics(server: JediLanguageServer, uri: str) -> None:
"""Helper function to publish diagnostics for a file."""
# The debounce decorator delays the execution by 1 second
# canceling notifications that happen in that interval.
# Since this function is executed after a delay, we need to check
# whether the document still exists
if uri not in server.workspace.documents:
return
doc = server.workspace.get_text_document(uri)
diagnostic = jedi_utils.lsp_python_diagnostic(uri, doc.source)
diagnostics = [diagnostic] if diagnostic else []
server.publish_diagnostics(uri, diagnostics)
# TEXT_DOCUMENT_DID_SAVE
def did_save_diagnostics(
server: JediLanguageServer, params: DidSaveTextDocumentParams
) -> None:
"""Actions run on textDocument/didSave: diagnostics."""
_publish_diagnostics(server, params.text_document.uri)
def did_save_default(
server: JediLanguageServer,
params: DidSaveTextDocumentParams,
) -> None:
"""Actions run on textDocument/didSave: default."""
# TEXT_DOCUMENT_DID_CHANGE
def did_change_diagnostics(
server: JediLanguageServer, params: DidChangeTextDocumentParams
) -> None:
"""Actions run on textDocument/didChange: diagnostics."""
_publish_diagnostics(server, params.text_document.uri)
def did_change_default(
server: JediLanguageServer,
params: DidChangeTextDocumentParams,
) -> None:
"""Actions run on textDocument/didChange: default."""
# TEXT_DOCUMENT_DID_OPEN
def did_open_diagnostics(
server: JediLanguageServer, params: DidOpenTextDocumentParams
) -> None:
"""Actions run on textDocument/didOpen: diagnostics."""
_publish_diagnostics(server, params.text_document.uri)
def did_open_default(
server: JediLanguageServer,
params: DidOpenTextDocumentParams,
) -> None:
"""Actions run on textDocument/didOpen: default."""
# TEXT_DOCUMENT_DID_CLOSE
def did_close_diagnostics(
server: JediLanguageServer, params: DidCloseTextDocumentParams
) -> None:
"""Actions run on textDocument/didClose: diagnostics."""
server.publish_diagnostics(params.text_document.uri, [])
def did_close_default(
server: JediLanguageServer,
params: DidCloseTextDocumentParams,
) -> None:
"""Actions run on textDocument/didClose: default."""
def _choose_markup(server: JediLanguageServer) -> MarkupKind:
"""Returns the preferred or first of supported markup kinds."""
markup_preferred = server.initialization_options.markup_kind_preferred
markup_supported = get_capability(
server.client_capabilities,
"text_document.completion.completion_item.documentation_format",
[MarkupKind.PlainText],
)
return MarkupKind(
markup_preferred
if markup_preferred in markup_supported
else markup_supported[0]
)