Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove Range class and rename RangeLsp to Range #2058

Merged
merged 3 commits into from
Sep 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions plugin/code_lens.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from .core.protocol import CodeLens, Error, Range
from .core.protocol import CodeLens, Error
from .core.typing import List, Tuple, Dict, Iterable, Generator, Union
from .core.registry import LspTextCommand
from .core.registry import windows
Expand All @@ -20,7 +20,7 @@ class CodeLensData:

def __init__(self, data: CodeLens, view: sublime.View, session_name: str) -> None:
self.data = data
self.region = range_to_region(Range.from_lsp(data['range']), view)
self.region = range_to_region(data['range'], view)
self.session_name = session_name
self.annotation = '...'
self.resolve_annotation()
Expand Down Expand Up @@ -63,7 +63,7 @@ def resolve(self, view: sublime.View, code_lens_or_error: Union[CodeLens, Error]
self.annotation = html_escape(str(code_lens_or_error))
return
self.data = code_lens_or_error
self.region = range_to_region(Range.from_lsp(code_lens_or_error['range']), view)
self.region = range_to_region(code_lens_or_error['range'], view)
self.resolve_annotation()


Expand Down
6 changes: 3 additions & 3 deletions plugin/completion.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from .core.edit import parse_text_edit
from .core.logging import debug
from .core.protocol import InsertReplaceEdit, TextEdit, RangeLsp, Request, InsertTextFormat, Range, CompletionItem
from .core.protocol import InsertReplaceEdit, TextEdit, Range, Request, InsertTextFormat, CompletionItem
from .core.registry import LspTextCommand
from .core.settings import userprefs
from .core.typing import List, Dict, Optional, Generator, Union, cast
Expand All @@ -17,7 +17,7 @@
SessionName = str


def get_text_edit_range(text_edit: Union[TextEdit, InsertReplaceEdit]) -> RangeLsp:
def get_text_edit_range(text_edit: Union[TextEdit, InsertReplaceEdit]) -> Range:
if 'insert' in text_edit and 'replace' in text_edit:
text_edit = cast(InsertReplaceEdit, text_edit)
insert_mode = userprefs().completion_insert_mode
Expand Down Expand Up @@ -103,7 +103,7 @@ def run(self, edit: sublime.Edit, item: CompletionItem, session_name: str) -> No
text_edit = item.get("textEdit")
if text_edit:
new_text = text_edit["newText"].replace("\r", "")
edit_region = range_to_region(Range.from_lsp(get_text_edit_range(text_edit)), self.view)
edit_region = range_to_region(get_text_edit_range(text_edit), self.view)
for region in self._translated_regions(edit_region):
self.view.erase(edit, region)
else:
Expand Down
13 changes: 6 additions & 7 deletions plugin/core/open.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from .promise import ResolveFunc
from .protocol import DocumentUri
from .protocol import Range
from .protocol import RangeLsp
from .protocol import UINT_MAX
from .typing import Dict, Tuple, Optional
from .typing import cast
Expand All @@ -25,10 +24,10 @@ def open_file_uri(
window: sublime.Window, uri: DocumentUri, flags: int = 0, group: int = -1
) -> Promise[Optional[sublime.View]]:

def parse_fragment(fragment: str) -> Optional[RangeLsp]:
def parse_fragment(fragment: str) -> Optional[Range]:
match = FRAGMENT_PATTERN.match(fragment)
if match:
selection = {'start': {'line': 0, 'character': 0}, 'end': {'line': 0, 'character': 0}} # type: RangeLsp
selection = {'start': {'line': 0, 'character': 0}, 'end': {'line': 0, 'character': 0}} # type: Range
# Line and column numbers in the fragment are assumed to be 1-based and need to be converted to 0-based
# numbers for the LSP Position structure.
start_line, start_column, end_line, end_column = [max(0, int(g) - 1) if g else None for g in match.groups()]
Expand All @@ -52,11 +51,11 @@ def parse_fragment(fragment: str) -> Optional[RangeLsp]:
if parsed.fragment:
selection = parse_fragment(parsed.fragment)
if selection:
return open_promise.then(lambda view: _select_and_center(view, cast(RangeLsp, selection)))
return open_promise.then(lambda view: _select_and_center(view, cast(Range, selection)))
return open_promise


def _select_and_center(view: Optional[sublime.View], r: RangeLsp) -> Optional[sublime.View]:
def _select_and_center(view: Optional[sublime.View], r: Range) -> Optional[sublime.View]:
if view:
return center_selection(view, r)
return None
Expand Down Expand Up @@ -111,8 +110,8 @@ def fullfill(resolve: ResolveFunc[Optional[sublime.View]]) -> None:
return promise


def center_selection(v: sublime.View, r: RangeLsp) -> sublime.View:
selection = range_to_region(Range.from_lsp(r), v)
def center_selection(v: sublime.View, r: Range) -> sublime.View:
selection = range_to_region(r, v)
v.run_command("lsp_selection_set", {"regions": [(selection.a, selection.a)]})
window = v.window()
if window:
Expand Down
87 changes: 22 additions & 65 deletions plugin/core/protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ class SemanticTokenModifiers:
'character': int
})

RangeLsp = TypedDict('RangeLsp', {
Range = TypedDict('Range', {
'start': Position,
'end': Position
})
Expand All @@ -178,7 +178,7 @@ class SemanticTokenModifiers:
ExperimentalTextDocumentRangeParams = TypedDict('ExperimentalTextDocumentRangeParams', {
'textDocument': TextDocumentIdentifier,
'position': Position,
'range': RangeLsp,
'range': Range,
}, total=True)

CodeDescription = TypedDict('CodeDescription', {
Expand All @@ -205,7 +205,7 @@ class SemanticTokenModifiers:


CodeLens = TypedDict('CodeLens', {
'range': RangeLsp,
'range': Range,
'command': Optional[Command],
'data': Any,
# Custom property to bring along the name of the session
Expand Down Expand Up @@ -244,7 +244,7 @@ class SemanticTokenModifiers:

Location = TypedDict('Location', {
'uri': DocumentUri,
'range': RangeLsp
'range': Range
}, total=True)

DocumentSymbol = TypedDict('DocumentSymbol', {
Expand All @@ -253,8 +253,8 @@ class SemanticTokenModifiers:
'kind': int,
'tags': Optional[List[int]],
'deprecated': Optional[bool],
'range': RangeLsp,
'selectionRange': RangeLsp,
'range': Range,
'selectionRange': Range,
'children': Optional[List[Any]] # mypy doesn't support recurive types like Optional[List['DocumentSymbol']]
}, total=True)

Expand All @@ -268,10 +268,10 @@ class SemanticTokenModifiers:
}, total=True)

LocationLink = TypedDict('LocationLink', {
'originSelectionRange': Optional[RangeLsp],
'originSelectionRange': Optional[Range],
'targetUri': DocumentUri,
'targetRange': RangeLsp,
'targetSelectionRange': RangeLsp
'targetRange': Range,
'targetSelectionRange': Range
}, total=False)

DiagnosticRelatedInformation = TypedDict('DiagnosticRelatedInformation', {
Expand All @@ -280,7 +280,7 @@ class SemanticTokenModifiers:
}, total=False)

Diagnostic = TypedDict('Diagnostic', {
'range': RangeLsp,
'range': Range,
'severity': int,
'code': Union[int, str],
'codeDescription': CodeDescription,
Expand Down Expand Up @@ -309,13 +309,13 @@ class SemanticTokenModifiers:

CodeActionParams = TypedDict('CodeActionParams', {
'textDocument': TextDocumentIdentifier,
'range': RangeLsp,
'range': Range,
'context': CodeActionContext,
}, total=True)

TextEdit = TypedDict('TextEdit', {
'newText': str,
'range': RangeLsp
'range': Range
}, total=True)

CompletionItemLabelDetails = TypedDict('CompletionItemLabelDetails', {
Expand All @@ -325,8 +325,8 @@ class SemanticTokenModifiers:

InsertReplaceEdit = TypedDict('InsertReplaceEdit', {
'newText': str,
'insert': RangeLsp,
'replace': RangeLsp
'insert': Range,
'replace': Range
}, total=True)

CompletionItem = TypedDict('CompletionItem', {
Expand Down Expand Up @@ -356,7 +356,7 @@ class SemanticTokenModifiers:
}, total=True)

DocumentLink = TypedDict('DocumentLink', {
'range': RangeLsp,
'range': Range,
'target': DocumentUri,
'tooltip': str,
'data': Any
Expand All @@ -368,7 +368,7 @@ class SemanticTokenModifiers:

Hover = TypedDict('Hover', {
'contents': Union[MarkedString, MarkupContent, List[MarkedString]],
'range': RangeLsp,
'range': Range,
}, total=False)

PublishDiagnosticsParams = TypedDict('PublishDiagnosticsParams', {
Expand All @@ -389,7 +389,7 @@ class SemanticTokenModifiers:

InlayHintParams = TypedDict('InlayHintParams', {
'textDocument': TextDocumentIdentifier,
'range': RangeLsp,
'range': Range,
}, total=True)

InlayHintLabelPart = TypedDict('InlayHintLabelPart', {
Expand Down Expand Up @@ -672,54 +672,6 @@ def to_lsp(self) -> Position:
}


class Range(object):
def __init__(self, start: Point, end: Point) -> None:
self.start = start
self.end = end

def __repr__(self) -> str:
return "({} {})".format(self.start, self.end)

def __eq__(self, other: object) -> bool:
if not isinstance(other, Range):
raise NotImplementedError()

return self.start == other.start and self.end == other.end

@classmethod
def from_lsp(cls, range: RangeLsp) -> 'Range':
return Range(Point.from_lsp(range['start']), Point.from_lsp(range['end']))

def to_lsp(self) -> RangeLsp:
return {
'start': self.start.to_lsp(),
'end': self.end.to_lsp()
}

def contains(self, point: Point) -> bool:
return self.start.row <= point.row <= self.end.row and \
(self.end.row > point.row or self.start.col <= point.col <= self.end.col)

def intersects(self, rge: 'Range') -> bool:
return self.contains(rge.start) or self.contains(rge.end) or \
rge.contains(self.start) or rge.contains(self.end)

def extend(self, rge: 'Range') -> 'Range':
"""
Extends current range to fully include another range. If another range is already fully
enclosed within the current range then nothing changes.

:param rge: The region to extend current with

:returns: The extended region (itself)
"""
if rge.contains(self.start):
self.start = rge.start
if rge.contains(self.end):
self.end = rge.end
return self


class WorkspaceFolder:

__slots__ = ('name', 'path')
Expand Down Expand Up @@ -754,3 +706,8 @@ def uri(self) -> str:

def includes_uri(self, uri: str) -> bool:
return uri.startswith(self.uri())


# Temporary for backward compatibility with LSP packages.

RangeLsp = Range
8 changes: 4 additions & 4 deletions plugin/core/sessions.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
from .protocol import ExecuteCommandParams
from .protocol import FileEvent
from .protocol import Notification
from .protocol import RangeLsp
from .protocol import Range
from .protocol import Request
from .protocol import Response
from .protocol import SemanticTokenModifiers
Expand Down Expand Up @@ -1467,7 +1467,7 @@ def run_code_action_async(self, code_action: Union[Command, CodeAction], progres
def open_uri_async(
self,
uri: DocumentUri,
r: Optional[RangeLsp] = None,
r: Optional[Range] = None,
flags: int = 0,
group: int = -1
) -> Promise[Optional[sublime.View]]:
Expand All @@ -1489,7 +1489,7 @@ def open_uri_async(
def _open_file_uri_async(
self,
uri: DocumentUri,
r: Optional[RangeLsp] = None,
r: Optional[Range] = None,
flags: int = 0,
group: int = -1
) -> Promise[Optional[sublime.View]]:
Expand All @@ -1507,7 +1507,7 @@ def _open_uri_with_plugin_async(
self,
plugin: AbstractPlugin,
uri: DocumentUri,
r: Optional[RangeLsp],
r: Optional[Range],
flags: int,
group: int,
) -> Promise[Optional[sublime.View]]:
Expand Down
28 changes: 17 additions & 11 deletions plugin/core/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
from .protocol import Point
from .protocol import Position
from .protocol import Range
from .protocol import RangeLsp
from .protocol import Request
from .protocol import SymbolKind
from .protocol import TextDocumentIdentifier
Expand Down Expand Up @@ -315,22 +314,29 @@ def position(view: sublime.View, offset: int) -> Position:


def range_to_region(range: Range, view: sublime.View) -> sublime.Region:
return sublime.Region(point_to_offset(range.start, view), point_to_offset(range.end, view))
start = Point.from_lsp(range['start'])
end = Point.from_lsp(range['end'])
return sublime.Region(point_to_offset(start, view), point_to_offset(end, view))


def region_to_range(view: sublime.View, region: sublime.Region) -> Range:
return Range(
offset_to_point(view, region.begin()),
offset_to_point(view, region.end())
)
return {
'start': offset_to_point(view, region.begin()).to_lsp(),
'end': offset_to_point(view, region.end()).to_lsp(),
}


def is_range_equal(lhs: Range, rhs: Range) -> bool:
return lhs['start']['line'] == rhs['start']['line'] and lhs['start']['character'] == rhs['start']['character'] and \
lhs['end']['line'] == rhs['end']['line'] and lhs['end']['character'] == rhs['end']['character']


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, RangeLsp]:
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"]
Expand Down Expand Up @@ -428,7 +434,7 @@ def text_document_range_params(view: sublime.View, location: int,
return {
"textDocument": text_document_identifier(view),
"position": position(view, location),
"range": region_to_range(view, region).to_lsp()
"range": region_to_range(view, region)
}


Expand Down Expand Up @@ -533,7 +539,7 @@ def text_document_range_formatting(view: sublime.View, region: sublime.Region) -
return Request("textDocument/rangeFormatting", {
"textDocument": text_document_identifier(view),
"options": formatting_options(view.settings()),
"range": region_to_range(view, region).to_lsp()
"range": region_to_range(view, region)
}, view, progress=True)


Expand All @@ -559,7 +565,7 @@ def text_document_code_action_params(
context["only"] = on_save_actions
return {
"textDocument": text_document_identifier(view),
"range": region_to_range(view, region).to_lsp(),
"range": region_to_range(view, region),
"context": context
}

Expand Down Expand Up @@ -783,7 +789,7 @@ def lsp_color_to_html(color_info: Dict[str, Any]) -> str:


def lsp_color_to_phantom(view: sublime.View, color_info: Dict[str, Any]) -> sublime.Phantom:
region = range_to_region(Range.from_lsp(color_info['range']), view)
region = range_to_region(color_info['range'], view)
return sublime.Phantom(region, lsp_color_to_html(color_info), sublime.LAYOUT_INLINE)


Expand Down
Loading