-
Notifications
You must be signed in to change notification settings - Fork 184
/
views.py
860 lines (692 loc) · 31.7 KB
/
views.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
from .constants import CODE_ACTION_KINDS
from .constants import SUBLIME_KIND_SCOPES
from .constants import SublimeKind
from .css import css as lsp_css
from .protocol import CodeAction
from .protocol import CodeActionKind
from .protocol import CodeActionContext
from .protocol import CodeActionParams
from .protocol import CodeActionTriggerKind
from .protocol import Color
from .protocol import ColorInformation
from .protocol import Command
from .protocol import Diagnostic
from .protocol import DiagnosticRelatedInformation
from .protocol import DiagnosticSeverity
from .protocol import DidChangeTextDocumentParams
from .protocol import DidCloseTextDocumentParams
from .protocol import DidOpenTextDocumentParams
from .protocol import DidSaveTextDocumentParams
from .protocol import DocumentColorParams
from .protocol import DocumentUri
from .protocol import Location
from .protocol import LocationLink
from .protocol import MarkedString
from .protocol import MarkupContent
from .protocol import Notification
from .protocol import Point
from .protocol import Position
from .protocol import Range
from .protocol import Request
from .protocol import SelectionRangeParams
from .protocol import TextDocumentContentChangeEvent
from .protocol import TextDocumentIdentifier
from .protocol import TextDocumentItem
from .protocol import TextDocumentPositionParams
from .protocol import TextDocumentSaveReason
from .protocol import VersionedTextDocumentIdentifier
from .protocol import WillSaveTextDocumentParams
from .settings import userprefs
from .types import ClientConfig
from .typing import Callable, Optional, Dict, Any, Iterable, List, Union, Tuple, cast
from .url import parse_uri
from .workspace import is_subpath_of
import html
import itertools
import linecache
import mdpopups
import os
import re
import sublime
import sublime_plugin
import tempfile
MarkdownLangMap = Dict[str, Tuple[Tuple[str, ...], Tuple[str, ...]]]
_baseflags = sublime.DRAW_NO_FILL | sublime.DRAW_NO_OUTLINE | sublime.DRAW_EMPTY_AS_OVERWRITE | sublime.NO_UNDO
_multilineflags = sublime.DRAW_NO_FILL | sublime.NO_UNDO
DIAGNOSTIC_SEVERITY = [
# Kind CSS class Scope for color Icon resource add_regions flags for single-line diagnostic multi-line diagnostic # noqa: E501
("error", "errors", "region.redish markup.error.lsp", "Packages/LSP/icons/error.png", _baseflags | sublime.DRAW_SQUIGGLY_UNDERLINE, _multilineflags), # noqa: E501
("warning", "warnings", "region.yellowish markup.warning.lsp", "Packages/LSP/icons/warning.png", _baseflags | sublime.DRAW_SQUIGGLY_UNDERLINE, _multilineflags), # noqa: E501
("info", "info", "region.bluish markup.info.lsp", "Packages/LSP/icons/info.png", _baseflags | sublime.DRAW_STIPPLED_UNDERLINE, _multilineflags), # noqa: E501
("hint", "hints", "region.bluish markup.info.hint.lsp", "", _baseflags | sublime.DRAW_STIPPLED_UNDERLINE, _multilineflags), # noqa: E501
] # type: List[Tuple[str, str, str, str, int, int]]
class DiagnosticSeverityData:
__slots__ = ('regions', 'regions_with_tag', 'annotations', 'scope', 'icon')
def __init__(self, severity: int) -> None:
self.regions = [] # type: List[sublime.Region]
self.regions_with_tag = {} # type: Dict[int, List[sublime.Region]]
self.annotations = [] # type: List[str]
_, _, self.scope, self.icon, _, _ = DIAGNOSTIC_SEVERITY[severity - 1]
if userprefs().diagnostics_gutter_marker != "sign":
self.icon = "" if severity == DiagnosticSeverity.Hint else userprefs().diagnostics_gutter_marker
class InvalidUriSchemeException(Exception):
def __init__(self, uri: str) -> None:
self.uri = uri
def __str__(self) -> str:
return "invalid URI scheme: {}".format(self.uri)
def get_line(window: sublime.Window, file_name: str, row: int, strip: bool = True) -> str:
'''
Get the line from the buffer if the view is open, else get line from linecache.
row - is 0 based. If you want to get the first line, you should pass 0.
'''
view = window.find_open_file(file_name)
if view:
# get from buffer
point = view.text_point(row, 0)
line = view.substr(view.line(point))
else:
# get from linecache
# linecache row is not 0 based, so we increment it by 1 to get the correct line.
line = linecache.getline(file_name, row + 1)
return line.strip() if strip else line
def get_storage_path() -> str:
"""
The "Package Storage" is a way to store server data without influencing the behavior of Sublime Text's "catalog".
Its path is '$DATA/Package Storage', where $DATA means:
- on macOS: ~/Library/Application Support/Sublime Text
- on Windows: %LocalAppData%/Sublime Text
- on Linux: ~/.cache/sublime-text
"""
return os.path.abspath(os.path.join(sublime.cache_path(), "..", "Package Storage"))
def extract_variables(window: sublime.Window) -> Dict[str, str]:
variables = window.extract_variables()
variables["storage_path"] = get_storage_path()
variables["cache_path"] = sublime.cache_path()
variables["temp_dir"] = tempfile.gettempdir()
variables["home"] = os.path.expanduser('~')
return variables
def point_to_offset(point: Point, view: sublime.View) -> int:
# @see https://microsoft.github.io/language-server-protocol/specifications/specification-3-15/#position
# If the character value is greater than the line length it defaults back to the line length.
return view.text_point_utf16(point.row, point.col, clamp_column=True)
def offset_to_point(view: sublime.View, offset: int) -> Point:
return Point(*view.rowcol_utf16(offset))
def position(view: sublime.View, offset: int) -> Position:
return offset_to_point(view, offset).to_lsp()
def position_to_offset(position: Position, view: sublime.View) -> int:
return point_to_offset(Point.from_lsp(position), view)
def get_symbol_kind_from_scope(scope_name: str) -> SublimeKind:
best_kind = sublime.KIND_AMBIGUOUS
best_kind_score = 0
for kind, selector in SUBLIME_KIND_SCOPES.items():
score = sublime.score_selector(scope_name, selector)
if score > best_kind_score:
best_kind = kind
best_kind_score = score
return best_kind
def range_to_region(range: Range, view: sublime.View) -> sublime.Region:
return sublime.Region(position_to_offset(range['start'], view), position_to_offset(range['end'], view))
def region_to_range(view: sublime.View, region: sublime.Region) -> Range:
return {
'start': offset_to_point(view, region.begin()).to_lsp(),
'end': offset_to_point(view, region.end()).to_lsp(),
}
def to_encoded_filename(path: str, position: Position) -> str:
# WARNING: Cannot possibly do UTF-16 conversion :) Oh well.
return '{}:{}:{}'.format(path, position['line'] + 1, position['character'] + 1)
def get_uri_and_range_from_location(location: Union[Location, LocationLink]) -> Tuple[DocumentUri, Range]:
if "targetUri" in location:
location = cast(LocationLink, location)
uri = location["targetUri"]
r = location["targetSelectionRange"]
else:
location = cast(Location, location)
uri = location["uri"]
r = location["range"]
return uri, r
def get_uri_and_position_from_location(location: Union[Location, LocationLink]) -> Tuple[DocumentUri, Position]:
if "targetUri" in location:
location = cast(LocationLink, location)
uri = location["targetUri"]
position = location["targetSelectionRange"]["start"]
else:
location = cast(Location, location)
uri = location["uri"]
position = location["range"]["start"]
return uri, position
def location_to_encoded_filename(location: Union[Location, LocationLink]) -> str:
"""
DEPRECATED
"""
uri, position = get_uri_and_position_from_location(location)
scheme, parsed = parse_uri(uri)
if scheme == "file":
return to_encoded_filename(parsed, position)
raise InvalidUriSchemeException(uri)
class MissingUriError(Exception):
def __init__(self, view_id: int) -> None:
super().__init__("View {} has no URI".format(view_id))
self.view_id = view_id
def uri_from_view(view: sublime.View) -> DocumentUri:
uri = view.settings().get("lsp_uri")
if isinstance(uri, DocumentUri):
return uri
raise MissingUriError(view.id())
def text_document_identifier(view_or_uri: Union[DocumentUri, sublime.View]) -> TextDocumentIdentifier:
if isinstance(view_or_uri, DocumentUri):
uri = view_or_uri
else:
uri = uri_from_view(view_or_uri)
return {"uri": uri}
def first_selection_region(view: sublime.View) -> Optional[sublime.Region]:
try:
return view.sel()[0]
except IndexError:
return None
def has_single_nonempty_selection(view: sublime.View) -> bool:
selections = view.sel()
return len(selections) == 1 and not selections[0].empty()
def entire_content_region(view: sublime.View) -> sublime.Region:
return sublime.Region(0, view.size())
def entire_content(view: sublime.View) -> str:
return view.substr(entire_content_region(view))
def entire_content_range(view: sublime.View) -> Range:
return region_to_range(view, entire_content_region(view))
def text_document_item(view: sublime.View, language_id: str) -> TextDocumentItem:
return {
"uri": uri_from_view(view),
"languageId": language_id,
"version": view.change_count(),
"text": entire_content(view)
}
def versioned_text_document_identifier(view: sublime.View, version: int) -> VersionedTextDocumentIdentifier:
return {"uri": uri_from_view(view), "version": version}
def text_document_position_params(view: sublime.View, location: int) -> TextDocumentPositionParams:
return {"textDocument": text_document_identifier(view), "position": position(view, location)}
def did_open_text_document_params(view: sublime.View, language_id: str) -> DidOpenTextDocumentParams:
return {"textDocument": text_document_item(view, language_id)}
def render_text_change(change: sublime.TextChange) -> TextDocumentContentChangeEvent:
# Note: cannot use protocol.Range because these are "historic" points.
return {
"range": {
"start": {"line": change.a.row, "character": change.a.col_utf16},
"end": {"line": change.b.row, "character": change.b.col_utf16}},
"rangeLength": change.len_utf16,
"text": change.str
}
def did_change_text_document_params(
view: sublime.View, version: int, changes: Optional[Iterable[sublime.TextChange]] = None
) -> DidChangeTextDocumentParams:
content_changes = [] # type: List[TextDocumentContentChangeEvent]
result = {
"textDocument": versioned_text_document_identifier(view, version),
"contentChanges": content_changes
} # type: DidChangeTextDocumentParams
if changes is None:
# TextDocumentSyncKind.Full
content_changes.append({"text": entire_content(view)})
else:
# TextDocumentSyncKind.Incremental
for change in changes:
content_changes.append(render_text_change(change))
return result
def will_save_text_document_params(
view_or_uri: Union[DocumentUri, sublime.View], reason: TextDocumentSaveReason
) -> WillSaveTextDocumentParams:
return {"textDocument": text_document_identifier(view_or_uri), "reason": reason}
def did_save_text_document_params(
view: sublime.View, include_text: bool, uri: Optional[DocumentUri] = None
) -> DidSaveTextDocumentParams:
result = {
"textDocument": text_document_identifier(uri if uri is not None else view)
} # type: DidSaveTextDocumentParams
if include_text:
result["text"] = entire_content(view)
return result
def did_close_text_document_params(uri: DocumentUri) -> DidCloseTextDocumentParams:
return {"textDocument": text_document_identifier(uri)}
def did_open(view: sublime.View, language_id: str) -> Notification:
return Notification.didOpen(did_open_text_document_params(view, language_id))
def did_change(view: sublime.View, version: int,
changes: Optional[Iterable[sublime.TextChange]] = None) -> Notification:
return Notification.didChange(did_change_text_document_params(view, version, changes))
def will_save(uri: DocumentUri, reason: TextDocumentSaveReason) -> Notification:
return Notification.willSave(will_save_text_document_params(uri, reason))
def will_save_wait_until(view: sublime.View, reason: TextDocumentSaveReason) -> Request:
return Request.willSaveWaitUntil(will_save_text_document_params(view, reason), view)
def did_save(view: sublime.View, include_text: bool, uri: Optional[DocumentUri] = None) -> Notification:
return Notification.didSave(did_save_text_document_params(view, include_text, uri))
def did_close(uri: DocumentUri) -> Notification:
return Notification.didClose(did_close_text_document_params(uri))
def formatting_options(settings: sublime.Settings) -> Dict[str, Any]:
# Build 4085 allows "trim_trailing_white_space_on_save" to be a string so we have to account for that in a
# backwards-compatible way.
trim_trailing_white_space = settings.get("trim_trailing_white_space_on_save") not in (False, None, "none")
return {
# Size of a tab in spaces.
"tabSize": settings.get("tab_size", 4),
# Prefer spaces over tabs.
"insertSpaces": settings.get("translate_tabs_to_spaces", False),
# Trim trailing whitespace on a line. (since 3.15)
"trimTrailingWhitespace": trim_trailing_white_space,
# Insert a newline character at the end of the file if one does not exist. (since 3.15)
"insertFinalNewline": settings.get("ensure_newline_at_eof_on_save", False),
# Trim all newlines after the final newline at the end of the file. (sine 3.15)
"trimFinalNewlines": settings.get("ensure_newline_at_eof_on_save", False)
}
def text_document_formatting(view: sublime.View) -> Request:
return Request("textDocument/formatting", {
"textDocument": text_document_identifier(view),
"options": formatting_options(view.settings())
}, view, progress=True)
def text_document_range_formatting(view: sublime.View, region: sublime.Region) -> Request:
return Request("textDocument/rangeFormatting", {
"textDocument": text_document_identifier(view),
"options": formatting_options(view.settings()),
"range": region_to_range(view, region)
}, view, progress=True)
def text_document_ranges_formatting(view: sublime.View) -> Request:
return Request("textDocument/rangesFormatting", {
"textDocument": text_document_identifier(view),
"options": formatting_options(view.settings()),
"ranges": [region_to_range(view, region) for region in view.sel() if not region.empty()]
}, view, progress=True)
def selection_range_params(view: sublime.View) -> SelectionRangeParams:
return {
"textDocument": text_document_identifier(view),
"positions": [position(view, r.b) for r in view.sel()]
}
def text_document_code_action_params(
view: sublime.View,
region: sublime.Region,
diagnostics: List[Diagnostic],
only_kinds: Optional[List[CodeActionKind]] = None,
manual: bool = False
) -> CodeActionParams:
context = {
"diagnostics": diagnostics,
"triggerKind": CodeActionTriggerKind.Invoked if manual else CodeActionTriggerKind.Automatic,
} # type: CodeActionContext
if only_kinds:
context["only"] = only_kinds
return {
"textDocument": text_document_identifier(view),
"range": region_to_range(view, region),
"context": context
}
# Workaround for limited margin-collapsing capabilities of the minihtml.
LSP_POPUP_SPACER_HTML = '<div class="lsp_popup--spacer"></div>'
def show_lsp_popup(
view: sublime.View,
contents: str,
*,
location: int = -1,
md: bool = False,
flags: int = 0,
css: Optional[str] = None,
wrapper_class: Optional[str] = None,
body_id: Optional[str] = None,
on_navigate: Optional[Callable[..., None]] = None,
on_hide: Optional[Callable[..., None]] = None
) -> None:
css = css if css is not None else lsp_css().popups
wrapper_class = wrapper_class if wrapper_class is not None else lsp_css().popups_classname
contents += LSP_POPUP_SPACER_HTML
body_wrapper = '<body id="{}">{{}}</body>'.format(body_id) if body_id else '<body>{}</body>'
mdpopups.show_popup(
view,
body_wrapper.format(contents),
css=css,
md=md,
flags=flags,
location=location,
wrapper_class=wrapper_class,
max_width=int(view.em_width() * float(userprefs().popup_max_characters_width)),
max_height=int(view.line_height() * float(userprefs().popup_max_characters_height)),
on_navigate=on_navigate,
on_hide=on_hide)
def update_lsp_popup(
view: sublime.View,
contents: str,
*,
md: bool = False,
css: Optional[str] = None,
wrapper_class: Optional[str] = None,
body_id: Optional[str] = None
) -> None:
css = css if css is not None else lsp_css().popups
wrapper_class = wrapper_class if wrapper_class is not None else lsp_css().popups_classname
contents += LSP_POPUP_SPACER_HTML
body_wrapper = '<body id="{}">{{}}</body>'.format(body_id) if body_id else '<body>{}</body>'
mdpopups.update_popup(view, body_wrapper.format(contents), css=css, md=md, wrapper_class=wrapper_class)
FORMAT_STRING = 0x1
FORMAT_MARKED_STRING = 0x2
FORMAT_MARKUP_CONTENT = 0x4
def minihtml(
view: sublime.View,
content: Union[MarkedString, MarkupContent, List[MarkedString]],
allowed_formats: int,
language_id_map: Optional[MarkdownLangMap] = None
) -> str:
"""
Formats provided input content into markup accepted by minihtml.
Content can be in one of those formats:
- string: treated as plain text
- MarkedString: string or { language: string; value: string }
- MarkedString[]
- MarkupContent: { kind: MarkupKind, value: string }
We can't distinguish between plain text string and a MarkedString in a string form so
FORMAT_STRING and FORMAT_MARKED_STRING can't both be specified at the same time.
:param view
:param content
:param allowed_formats: Bitwise flag specifying which formats to parse.
:returns: Formatted string
"""
if allowed_formats == 0:
raise ValueError("Must specify at least one format")
parse_string = bool(allowed_formats & FORMAT_STRING)
parse_marked_string = bool(allowed_formats & FORMAT_MARKED_STRING)
parse_markup_content = bool(allowed_formats & FORMAT_MARKUP_CONTENT)
if parse_string and parse_marked_string:
raise ValueError("Not allowed to specify FORMAT_STRING and FORMAT_MARKED_STRING at the same time")
is_plain_text = True
result = ''
if (parse_string or parse_marked_string) and isinstance(content, str):
# plain text string or MarkedString
is_plain_text = parse_string
result = content
if parse_marked_string and isinstance(content, list):
# MarkedString[]
formatted = []
for item in content:
value = ""
language = None
if isinstance(item, str):
value = item
else:
value = item.get("value") or ""
language = item.get("language")
if language:
formatted.append("```{}\n{}\n```\n".format(language, value))
else:
formatted.append(value)
is_plain_text = False
result = "\n".join(formatted)
if (parse_marked_string or parse_markup_content) and isinstance(content, dict):
# MarkupContent or MarkedString (dict)
language = content.get("language")
kind = content.get("kind")
value = content.get("value") or ""
if parse_markup_content and kind:
# MarkupContent
is_plain_text = kind != "markdown"
result = value
if parse_marked_string and language:
# MarkedString (dict)
is_plain_text = False
result = "```{}\n{}\n```\n".format(language, value)
if is_plain_text:
return "<p>{}</p>".format(text2html(result)) if result else ''
else:
frontmatter = {
"allow_code_wrap": True,
"markdown_extensions": [
"markdown.extensions.admonition",
{
"pymdownx.magiclink": {
# links are displayed without the initial ftp://, http://, https://, or ftps://.
"hide_protocol": True,
# GitHub, Bitbucket, and GitLab commit, pull, and issue links are are rendered in a shorthand
# syntax.
"repo_url_shortener": True
}
}
]
}
if isinstance(language_id_map, dict):
frontmatter["language_map"] = language_id_map
# Workaround CommonMark deficiency: two spaces followed by a newline should result in a new paragraph.
result = re.sub('(\\S) \n', '\\1\n\n', result)
return mdpopups.md2html(view, mdpopups.format_frontmatter(frontmatter) + result)
REPLACEMENT_MAP = {
"&": "&",
"<": "<",
">": ">",
"\t": 4 * " ",
"\n": "<br>",
"\xa0": " ", # non-breaking space
"\xc2": " ", # control character
}
PATTERNS = [
r'(?P<special>[{}])'.format(''.join(REPLACEMENT_MAP.keys())),
r'(?P<url>https?://(?:[\w\d:#@%/;$()~_?\+\-=\\\.&](?:#!)?)*)',
r'(?P<multispace> {2,})',
]
REPLACEMENT_RE = re.compile('|'.join(PATTERNS), flags=re.IGNORECASE)
def _replace_match(match: Any) -> str:
special_match = match.group('special')
if special_match:
return REPLACEMENT_MAP[special_match]
url = match.group('url')
if url:
return "<a href='{}'>{}</a>".format(url, url)
return len(match.group('multispace')) * ' '
def text2html(content: str) -> str:
return re.sub(REPLACEMENT_RE, _replace_match, content)
def make_link(href: str, text: Any, class_name: Optional[str] = None, tooltip: Optional[str] = None) -> str:
link = "<a href='{}'".format(href)
if class_name:
link += " class='{}'".format(class_name)
if tooltip:
link += " title='{}'".format(html.escape(tooltip))
text = text2html(str(text)).replace(' ', ' ')
link += ">{}</a>".format(text)
return link
def make_command_link(
command: str,
text: str,
command_args: Optional[Dict[str, Any]] = None,
class_name: Optional[str] = None,
tooltip: Optional[str] = None,
view_id: Optional[int] = None
) -> str:
if view_id is not None:
cmd = "lsp_run_text_command_helper"
args = {"view_id": view_id, "command": command, "args": command_args} # type: Optional[Dict[str, Any]]
else:
cmd = command
args = command_args
return make_link(sublime.command_url(cmd, args), text, class_name, tooltip)
class LspRunTextCommandHelperCommand(sublime_plugin.WindowCommand):
def run(self, view_id: int, command: str, args: Optional[Dict[str, Any]] = None) -> None:
view = sublime.View(view_id)
if view.is_valid():
view.run_command(command, args)
COLOR_BOX_HTML = """
<style>
html {{
padding: 0;
background-color: transparent;
}}
a {{
display: inline-block;
height: 0.8rem;
width: 0.8rem;
margin-top: 0.1em;
border: 1px solid color(var(--foreground) alpha(0.25));
background-color: {color};
text-decoration: none;
}}
</style>
<body id='lsp-color-box'>
<a href='{command}'> </a>
</body>"""
def color_to_hex(color: Color) -> str:
red = round(color['red'] * 255)
green = round(color['green'] * 255)
blue = round(color['blue'] * 255)
alpha_dec = color['alpha']
if alpha_dec < 1:
return "#{:02x}{:02x}{:02x}{:02x}".format(red, green, blue, round(alpha_dec * 255))
return "#{:02x}{:02x}{:02x}".format(red, green, blue)
def lsp_color_to_html(color_info: ColorInformation) -> str:
command = sublime.command_url('lsp_color_presentation', {'color_information': color_info})
return COLOR_BOX_HTML.format(command=command, color=color_to_hex(color_info['color']))
def lsp_color_to_phantom(view: sublime.View, color_info: ColorInformation) -> sublime.Phantom:
region = range_to_region(color_info['range'], view)
return sublime.Phantom(region, lsp_color_to_html(color_info), sublime.LAYOUT_INLINE)
def document_color_params(view: sublime.View) -> DocumentColorParams:
return {"textDocument": text_document_identifier(view)}
def format_severity(severity: int) -> str:
if 1 <= severity <= len(DIAGNOSTIC_SEVERITY):
return DIAGNOSTIC_SEVERITY[severity - 1][0]
return "???"
def diagnostic_severity(diagnostic: Diagnostic) -> DiagnosticSeverity:
return diagnostic.get("severity", DiagnosticSeverity.Error)
def format_diagnostics_for_annotation(
diagnostics: List[Diagnostic], severity: DiagnosticSeverity, view: sublime.View
) -> Tuple[List[str], str]:
css_class = DIAGNOSTIC_SEVERITY[severity - 1][1]
scope = DIAGNOSTIC_SEVERITY[severity - 1][2]
color = view.style_for_scope(scope).get('foreground') or 'red'
annotations = []
for diagnostic in diagnostics:
message = text2html(diagnostic.get('message') or '')
source = diagnostic.get('source')
line = "[{}] {}".format(text2html(source), message) if source else message
content = '<body id="annotation" class="{1}"><style>{0}</style><div class="{2}">{3}</div></body>'.format(
lsp_css().annotations, lsp_css().annotations_classname, css_class, line)
annotations.append(content)
return (annotations, color)
def format_diagnostic_for_panel(diagnostic: Diagnostic) -> Tuple[str, Optional[int], Optional[str], Optional[str]]:
"""
Turn an LSP diagnostic into a string suitable for an output panel.
:param diagnostic: The diagnostic
:returns: Tuple of (content, optional offset, optional code, optional href)
When the last three elements are optional, don't show an inline phantom
When the last three elements are not optional, show an inline phantom
using the information given.
"""
formatted, code, href = diagnostic_source_and_code(diagnostic)
lines = diagnostic["message"].splitlines() or [""]
result = " {:>4}:{:<4}{:<8}{}".format(
diagnostic["range"]["start"]["line"] + 1,
diagnostic["range"]["start"]["character"] + 1,
format_severity(diagnostic_severity(diagnostic)),
lines[0]
)
if formatted != "" or code is not None:
# \u200B is the zero-width space
result += " \u200B{}".format(formatted)
offset = len(result) if href else None
for line in itertools.islice(lines, 1, None):
result += "\n" + 18 * " " + line
return result, offset, code, href
def format_diagnostic_source_and_code(diagnostic: Diagnostic) -> str:
formatted, code, href = diagnostic_source_and_code(diagnostic)
if href is None or code is None:
return formatted
return formatted + "({})".format(code)
def diagnostic_source_and_code(diagnostic: Diagnostic) -> Tuple[str, Optional[str], Optional[str]]:
formatted = diagnostic.get("source", "")
href = None
code = diagnostic.get("code")
if code is not None:
code = str(code)
code_description = diagnostic.get("codeDescription")
if code_description:
href = code_description["href"]
else:
formatted += "({})".format(code)
return formatted, code, href
def location_to_human_readable(
config: ClientConfig,
base_dir: Optional[str],
location: Union[Location, LocationLink]
) -> str:
"""
Format an LSP Location (or LocationLink) into a string suitable for a human to read
"""
uri, position = get_uri_and_position_from_location(location)
scheme, _ = parse_uri(uri)
if scheme == "file":
fmt = "{}:{}"
pathname = config.map_server_uri_to_client_path(uri)
if base_dir and is_subpath_of(pathname, base_dir):
pathname = pathname[len(os.path.commonprefix((pathname, base_dir))) + 1:]
elif scheme == "res":
fmt = "{}:{}"
pathname = uri
else:
# https://tools.ietf.org/html/rfc5147
fmt = "{}#line={}"
pathname = uri
return fmt.format(pathname, position["line"] + 1)
def location_to_href(config: ClientConfig, location: Union[Location, LocationLink]) -> str:
"""
Encode an LSP Location (or LocationLink) into a string suitable as a hyperlink in minihtml
"""
uri, position = get_uri_and_position_from_location(location)
return "location:{}@{}#{},{}".format(config.name, uri, position["line"], position["character"])
def unpack_href_location(href: str) -> Tuple[str, str, int, int]:
"""
Return the session name, URI, row, and col_utf16 from an encoded href.
"""
session_name, uri_with_fragment = href[len("location:"):].split("@")
uri, fragment = uri_with_fragment.split("#")
row, col_utf16 = map(int, fragment.split(","))
return session_name, uri, row, col_utf16
def is_location_href(href: str) -> bool:
"""
Check whether this href is an encoded location.
"""
return href.startswith("location:")
def _format_diagnostic_related_info(
config: ClientConfig,
info: DiagnosticRelatedInformation,
base_dir: Optional[str] = None
) -> str:
location = info["location"]
return '<a href="{}">{}</a>: {}'.format(
location_to_href(config, location),
text2html(location_to_human_readable(config, base_dir, location)),
text2html(info["message"])
)
def _html_element(name: str, text: str, class_name: Optional[str] = None, escape: bool = True) -> str:
return '<{0}{2}>{1}</{0}>'.format(
name,
text2html(text) if escape else text,
' class="{}"'.format(text2html(class_name)) if class_name else ''
)
def format_diagnostic_for_html(config: ClientConfig, diagnostic: Diagnostic, base_dir: Optional[str] = None) -> str:
html = _html_element('span', diagnostic["message"])
code = diagnostic.get("code")
source = diagnostic.get("source")
if source or code is not None:
meta_info = ""
if source:
meta_info += text2html(source)
if code is not None:
code_description = diagnostic.get("codeDescription")
meta_info += "({})".format(
make_link(code_description["href"], str(code)) if code_description else text2html(str(code)))
html += " " + _html_element("span", meta_info, class_name="color-muted", escape=False)
related_infos = diagnostic.get("relatedInformation")
if related_infos:
info = "<br>".join(_format_diagnostic_related_info(config, info, base_dir) for info in related_infos)
html += '<br>' + _html_element("pre", info, class_name="related_info", escape=False)
severity_class = DIAGNOSTIC_SEVERITY[diagnostic_severity(diagnostic) - 1][1]
return _html_element("pre", html, class_name=severity_class, escape=False)
def format_code_actions_for_quick_panel(
session_actions: Iterable[Tuple[str, Union[CodeAction, Command]]]
) -> Tuple[List[sublime.QuickPanelItem], int]:
items = [] # type: List[sublime.QuickPanelItem]
selected_index = -1
for idx, (config_name, code_action) in enumerate(session_actions):
lsp_kind = code_action.get("kind", "")
first_kind_component = cast(CodeActionKind, str(lsp_kind).split(".")[0])
kind = CODE_ACTION_KINDS.get(first_kind_component, sublime.KIND_AMBIGUOUS)
items.append(sublime.QuickPanelItem(code_action["title"], annotation=config_name, kind=kind))
if code_action.get('isPreferred', False):
selected_index = idx
return items, selected_index