Skip to content

Commit

Permalink
Resolve completions completion item before applying additional text e…
Browse files Browse the repository at this point in the history
…dits (#1651)

Co-authored-by: Rafał Chłodnicki <rchl2k@gmail.com>
  • Loading branch information
predragnikolic and rchl authored May 1, 2021
1 parent 37b0ca8 commit 988cd02
Show file tree
Hide file tree
Showing 5 changed files with 125 additions and 100 deletions.
3 changes: 1 addition & 2 deletions boot.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,8 @@

# Please keep this list sorted (Edit -> Sort Lines)
from .plugin.code_actions import LspCodeActionsCommand
from .plugin.completion import LspCompleteInsertTextCommand
from .plugin.completion import LspCompleteTextEditCommand
from .plugin.completion import LspResolveDocsCommand
from .plugin.completion import LspSelectCompletionItemCommand
from .plugin.configuration import LspDisableLanguageServerGloballyCommand
from .plugin.configuration import LspDisableLanguageServerInProjectCommand
from .plugin.configuration import LspEnableLanguageServerGloballyCommand
Expand Down
94 changes: 48 additions & 46 deletions plugin/completion.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import sublime
import sublime_plugin
import webbrowser
from .core.logging import debug
from .core.edit import parse_text_edit
from .core.protocol import Request, InsertTextFormat, Range, CompletionItem
from .core.registry import LspTextCommand
from .core.typing import Any, List, Dict, Optional, Generator, Union
from .core.typing import List, Dict, Optional, Generator, Union
from .core.views import FORMAT_STRING, FORMAT_MARKUP_CONTENT, minihtml
from .core.views import range_to_region
from .core.views import show_lsp_popup
Expand Down Expand Up @@ -67,52 +66,27 @@ def _on_navigate(self, url: str) -> None:
webbrowser.open(url)


class LspCompleteCommand(sublime_plugin.TextCommand):

def epilogue(self, item: CompletionItem, session_name: Optional[str] = None) -> None:
additional_edits = item.get('additionalTextEdits')
if additional_edits:
edits = [parse_text_edit(additional_edit) for additional_edit in additional_edits]
self.view.run_command("lsp_apply_document_edit", {'changes': edits})
command = item.get("command")
if command:
debug('Running server command "{}" for view {}'.format(command, self.view.id()))
args = {
"command_name": command["command"],
"command_args": command.get("arguments"),
"session_name": session_name
}
self.view.run_command("lsp_execute", args)


class LspCompleteInsertTextCommand(LspCompleteCommand):

def run(self, edit: sublime.Edit, item: Any, session_name: Optional[str] = None) -> None:
insert_text = item.get("insertText") or item["label"]
if item.get("insertTextFormat", InsertTextFormat.PlainText) == InsertTextFormat.Snippet:
self.view.run_command("insert_snippet", {"contents": insert_text})
else:
self.view.run_command("insert", {"characters": insert_text})
self.epilogue(item, session_name)


class LspCompleteTextEditCommand(LspCompleteCommand):

def run(self, edit: sublime.Edit, item: CompletionItem, session_name: Optional[str] = None) -> None:
class LspSelectCompletionItemCommand(LspTextCommand):
def run(self, edit: sublime.Edit, item: CompletionItem, session_name: str) -> None:
text_edit = item.get("textEdit")
if not text_edit:
return
new_text = text_edit["newText"]
edit_region = range_to_region(Range.from_lsp(text_edit['range']), self.view)
if item.get("insertTextFormat", InsertTextFormat.PlainText) == InsertTextFormat.Snippet:
for region in self.translated_regions(edit_region):
self.view.erase(edit, region)
self.view.run_command("insert_snippet", {"contents": new_text})
if text_edit:
new_text = text_edit["newText"]
edit_region = range_to_region(Range.from_lsp(text_edit['range']), self.view)
if item.get("insertTextFormat", InsertTextFormat.PlainText) == InsertTextFormat.Snippet:
for region in self.translated_regions(edit_region):
self.view.erase(edit, region)
self.view.run_command("insert_snippet", {"contents": new_text})
else:
for region in self.translated_regions(edit_region):
# NOTE: Cannot do .replace, because ST will select the replacement.
self.view.erase(edit, region)
self.view.insert(edit, region.a, new_text)
else:
for region in self.translated_regions(edit_region):
# NOTE: Cannot do .replace, because ST will select the replacement.
self.view.erase(edit, region)
self.view.insert(edit, region.a, new_text)
insert_text = item.get("insertText") or item.get("label")
if item.get("insertTextFormat", InsertTextFormat.PlainText) == InsertTextFormat.Snippet:
self.view.run_command("insert_snippet", {"contents": insert_text})
else:
self.view.run_command("insert", {"characters": insert_text})
self.epilogue(item, session_name)

def translated_regions(self, edit_region: sublime.Region) -> Generator[sublime.Region, None, None]:
Expand All @@ -125,3 +99,31 @@ def translated_regions(self, edit_region: sublime.Region) -> Generator[sublime.R
translation = region.b - primary_cursor_position
translated_edit_region = sublime.Region(edit_region.a + translation, edit_region.b + translation)
yield translated_edit_region

def epilogue(self, item: CompletionItem, session_name: str) -> None:
session = self.session_by_name(session_name, 'completionProvider.resolveProvider')

def resolve_on_main_thread(item: CompletionItem, session_name: str) -> None:
sublime.set_timeout(lambda: self.on_resolved(item, session_name))

additional_text_edits = item.get('additionalTextEdits')
if session and not additional_text_edits:
request = Request.resolveCompletionItem(item, self.view)
session.send_request_async(request, lambda response: resolve_on_main_thread(response, session_name))
else:
self.on_resolved(item, session_name)

def on_resolved(self, item: CompletionItem, session_name: str) -> None:
additional_edits = item.get('additionalTextEdits')
if additional_edits:
edits = [parse_text_edit(additional_edit) for additional_edit in additional_edits]
self.view.run_command("lsp_apply_document_edit", {'changes': edits})
command = item.get("command")
if command:
debug('Running server command "{}" for view {}'.format(command, self.view.id()))
args = {
"command_name": command["command"],
"command_args": command.get("arguments"),
"session_name": session_name
}
self.view.run_command("lsp_execute", args)
3 changes: 3 additions & 0 deletions plugin/core/sessions.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,9 @@ def get_initialize_params(variables: Dict[str, str], workspace_folders: List[Wor
"documentationFormat": ["markdown", "plaintext"],
"tagSupport": {
"valueSet": completion_tag_value_set
},
"resolveSupport": {
"properties": ["detail", "documentation", "additionalTextEdits"]
}
},
"completionItemKind": {
Expand Down
40 changes: 9 additions & 31 deletions plugin/core/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
from .protocol import Diagnostic
from .protocol import DiagnosticRelatedInformation
from .protocol import DiagnosticSeverity
from .protocol import InsertTextFormat
from .protocol import Location
from .protocol import LocationLink
from .protocol import Notification
Expand Down Expand Up @@ -718,34 +717,13 @@ def format_completion(
else:
st_trigger = lsp_label

# NOTE: Some servers return "textEdit": null. We have to check if it's truthy.
if item.get("textEdit") or item.get("additionalTextEdits") or item.get("command"):
command = "lsp_complete_text_edit" if item.get("textEdit") else "lsp_complete_insert_text"
args = {"item": item} # type: Dict[str, Any]
if item.get("command"):
# If there is a "command", we'll have to run the command on the same session so store the name.
args["session_name"] = session_name
completion = sublime.CompletionItem.command_completion(
trigger=st_trigger,
command=command,
args=args,
annotation=st_annotation,
kind=kind,
details=st_details)
if item.get("textEdit"):
completion.flags = sublime.COMPLETION_FLAG_KEEP_PREFIX
else:
# A plain old completion suffices for insertText with no additionalTextEdits and no command.
if item.get("insertTextFormat", InsertTextFormat.PlainText) == InsertTextFormat.PlainText:
st_format = sublime.COMPLETION_FORMAT_TEXT
else:
st_format = sublime.COMPLETION_FORMAT_SNIPPET
completion = sublime.CompletionItem(
trigger=st_trigger,
annotation=st_annotation,
completion=item.get("insertText") or item["label"],
completion_format=st_format,
kind=kind,
details=st_details)

completion = sublime.CompletionItem.command_completion(
trigger=st_trigger,
command="lsp_select_completion_item",
args={"item": item, "session_name": session_name},
annotation=st_annotation,
kind=kind,
details=st_details)
if item.get("textEdit"):
completion.flags = sublime.COMPLETION_FLAG_KEEP_PREFIX
return completion
85 changes: 64 additions & 21 deletions tests/test_completion.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from copy import deepcopy
from LSP.plugin.core.protocol import CompletionItemTag
from LSP.plugin.core.typing import Any, Generator, List, Dict, Callable
from LSP.plugin.core.views import format_completion
Expand Down Expand Up @@ -25,8 +26,7 @@
}


class QueryCompletionsTests(TextDocumentTestCase):

class CompletionsTestsBase(TextDocumentTestCase):
@classmethod
def init_view_settings(cls) -> None:
super().init_view_settings()
Expand Down Expand Up @@ -75,6 +75,8 @@ def verify(self, *, completion_items: List[Dict[str, Any]], insert_text: str, ex
yield from self.await_message("textDocument/completion")
self.assertEqual(self.read_file(), expected_text)


class QueryCompletionsTests(CompletionsTestsBase):
def test_none(self) -> 'Generator':
self.set_response("textDocument/completion", None)
self.view.run_command('auto_complete')
Expand Down Expand Up @@ -353,26 +355,30 @@ def test_filter_text_is_not_a_prefix_of_label(self) -> 'Generator':
insert_text='e',
expected_text='def foo: Int \u003d ???\n def boo: Int \u003d ???')

def test_additional_edits(self) -> 'Generator':
yield from self.verify(
completion_items=[{
'label': 'asdf',
'additionalTextEdits': [
{
'range': {
'start': {
'line': 0,
'character': 0
},
'end': {
'line': 0,
'character': 0
}
def test_additional_edits_if_session_has_the_resolve_capability(self) -> 'Generator':
completion_item = {
'label': 'asdf'
}
self.set_response("completionItem/resolve", {
'label': 'asdf',
'additionalTextEdits': [
{
'range': {
'start': {
'line': 0,
'character': 0
},
'newText': 'import asdf;\n'
}
]
}],
'end': {
'line': 0,
'character': 0
}
},
'newText': 'import asdf;\n'
}
]
})
yield from self.verify(
completion_items=[completion_item],
insert_text='',
expected_text='import asdf;\nasdf')

Expand Down Expand Up @@ -598,3 +604,40 @@ def test_show_deprecated_tag(self) -> 'Generator':
formatted_completion_item = format_completion(item_with_deprecated_tags, 0, False, "")
self.assertEqual('⚠', formatted_completion_item.kind[1])
self.assertEqual('⚠ Method - Deprecated', formatted_completion_item.kind[2])


class QueryCompletionsNoResolverTests(CompletionsTestsBase):
'''
The difference between QueryCompletionsTests and QueryCompletionsNoResolverTests
is that QueryCompletionsTests has the completion item resolve capability enabled
and the QueryCompletionsNoResolverTests has the resolve capability disabled
'''
@classmethod
def get_test_server_capabilities(cls) -> dict:
capabilities = deepcopy(super().get_test_server_capabilities())
capabilities['capabilities']['completionProvider']['resolveProvider'] = False
return capabilities

def test_additional_edits_if_session_does_not_have_the_resolve_capability(self) -> 'Generator':
completion_item = {
'label': 'ghjk',
'additionalTextEdits': [
{
'range': {
'start': {
'line': 0,
'character': 0
},
'end': {
'line': 0,
'character': 0
}
},
'newText': 'import ghjk;\n'
}
]
}
yield from self.verify(
completion_items=[completion_item],
insert_text='',
expected_text='import ghjk;\nghjk')

0 comments on commit 988cd02

Please sign in to comment.