Esempio n. 1
0
def test_register_feature_with_valid_options(feature_manager):
    options = CompletionOptions(trigger_characters=['!'])

    @feature_manager.feature(methods.COMPLETION, options)
    def completions():
        pass

    reg_features = feature_manager.features.keys()
    reg_feature_options = feature_manager.feature_options.keys()

    assert methods.COMPLETION in reg_features
    assert methods.COMPLETION in reg_feature_options

    assert feature_manager.features[methods.COMPLETION] is completions
    assert feature_manager.feature_options[methods.COMPLETION] is options
Esempio n. 2
0
    def setUpClass(cls):
        cls.client_server = ClientServer()
        cls.client, cls.server = cls.client_server

        @cls.server.feature(COMPLETION,
                            CompletionOptions(trigger_characters=[','],
                                              all_commit_characters=[':'],
                                              resolve_provider=True))
        def f(params: CompletionParams) -> CompletionList:
            return CompletionList(is_incomplete=False,
                                  items=[
                                      CompletionItem(
                                          label='test1',
                                          kind=CompletionItemKind.Method,
                                          preselect=True,
                                      ),
                                  ])

        cls.client_server.start()
Esempio n. 3
0
 def _with_completion(self):
     value = self._provider_options(COMPLETION, default=CompletionOptions())
     if value is not None:
         self.server_cap.completion_provider = value
     return self
Esempio n. 4
0
    params: DidChangeTextDocumentParams,
) -> None:
    buildout.clearCache(params.text_document.uri)
    await parseAndSendDiagnostics(ls, params.text_document.uri)


@server.feature(WORKSPACE_DID_CHANGE_WATCHED_FILES)
async def did_change_watched_file(
    ls: LanguageServer,
    params: DidChangeWatchedFilesParams,
) -> None:
    for change in params.changes:
        buildout.clearCache(change.uri)


@server.feature(COMPLETION, CompletionOptions(trigger_characters=["= "]))
async def lsp_completion(
    ls: LanguageServer,
    params: CompletionParams,
) -> Optional[List[CompletionItem]]:
    await asyncio.sleep(DEBOUNCE_DELAY)
    items: List[CompletionItem] = []

    ast = await buildout.parse(ls, params.text_document.uri, True)
    for line in ast.lines:
        pos = params.position
        (var_name, var_type, value) = line
        ci = CompletionItem(label=var_name,
                            text_edit=TextEdit(
                                range=Range(
                                    start=Position(line=pos.line,
Esempio n. 5
0
# 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(
    COMPLETION,
    CompletionOptions(trigger_characters=[".", "'", '"'],
                      resolve_provider=True),
)
def completion(server: JediLanguageServer,
               params: CompletionParams) -> Optional[CompletionList]:
    """Returns completion items."""
    document = server.workspace.get_document(params.text_document.uri)
    jedi_script = jedi_utils.script(server.project, document)
    jedi_lines = jedi_utils.line_column(jedi_script, params.position)
    completions_jedi = jedi_script.complete(**jedi_lines)
    snippet_support = server.client_capabilities.get_capability(
        "text_document.completion.completion_item.snippet_support", False)
    snippet_disable = server.initialization_options.completion.disable_snippets
    resolve_eagerly = server.initialization_options.completion.resolve_eagerly
    markup_kind = _choose_markup(server)
    is_import_context = jedi_utils.is_import(
        script_=jedi_script,
Esempio n. 6
0
def _configure_lsp_methods(server: RstLanguageServer) -> RstLanguageServer:
    @server.feature(INITIALIZE)
    def on_initialize(ls: RstLanguageServer, params: InitializeParams):
        ls.initialize(params)

        for feature in ls._features.values():
            feature.initialize(params)

    @server.feature(INITIALIZED)
    def on_initialized(ls: RstLanguageServer, params: InitializedParams):
        ls.initialized(params)

        for feature in ls._features.values():
            feature.initialized(params)

    @server.feature(SHUTDOWN)
    def on_shutdown(ls: RstLanguageServer, *args):
        ls.on_shutdown(*args)

        for feature in ls._features.values():
            feature.on_shutdown(*args)

    @server.feature(TEXT_DOCUMENT_DID_OPEN)
    def on_open(ls: RstLanguageServer, params: DidOpenTextDocumentParams):
        pass

    @server.feature(TEXT_DOCUMENT_DID_CHANGE)
    def on_change(ls: RstLanguageServer, params: DidChangeTextDocumentParams):
        pass

    @server.feature(TEXT_DOCUMENT_DID_SAVE)
    def on_save(ls: RstLanguageServer, params: DidSaveTextDocumentParams):
        ls.save(params)

        for feature in ls._features.values():
            feature.save(params)

    @server.feature(
        WORKSPACE_DID_DELETE_FILES,
        FileOperationRegistrationOptions(filters=[
            FileOperationFilter(pattern=FileOperationPattern(
                glob="**/*.rst"), )
        ]),
    )
    def on_delete_files(ls: RstLanguageServer, params: DeleteFilesParams):
        ls.delete_files(params)

        for feature in ls._features.values():
            feature.delete_files(params)

    @server.feature(CODE_ACTION)
    def on_code_action(ls: RstLanguageServer, params: CodeActionParams):
        actions = []

        for feature in ls._features.values():
            actions += feature.code_action(params)

        return actions

    @server.feature(HOVER)
    def on_hover(ls: RstLanguageServer, params: HoverParams):
        uri = params.text_document.uri
        doc = ls.workspace.get_document(uri)
        pos = params.position
        line = ls.line_at_position(doc, pos)
        location = ls.get_location_type(doc, pos)

        hover_values = []
        for feature in ls._features.values():
            for pattern in feature.hover_triggers:
                for match in pattern.finditer(line):
                    if not match:
                        continue

                    # only trigger hover if the position of the request is within
                    # the match
                    start, stop = match.span()
                    if start <= pos.character <= stop:
                        context = HoverContext(
                            doc=doc,
                            location=location,
                            match=match,
                            position=pos,
                            capabilities=ls.client_capabilities,
                        )
                        ls.logger.debug("Hover context: %s", context)

                        hover_value = feature.hover(context)
                        hover_values.append(hover_value)

        hover_content_values = "\n".join(hover_values)

        return Hover(contents=MarkupContent(
            kind=MarkupKind.Markdown,
            value=hover_content_values,
        ))

    # <engine-example>
    @server.feature(
        COMPLETION,
        CompletionOptions(trigger_characters=[">", ".", ":", "`", "<", "/"],
                          resolve_provider=True),
    )
    def on_completion(ls: RstLanguageServer, params: CompletionParams):
        uri = params.text_document.uri
        pos = params.position

        doc = ls.workspace.get_document(uri)
        line = ls.line_at_position(doc, pos)
        location = ls.get_location_type(doc, pos)

        items = []

        for name, feature in ls._features.items():
            for pattern in feature.completion_triggers:
                for match in pattern.finditer(line):
                    if not match:
                        continue

                    # Only trigger completions if the position of the request is within
                    # the match.
                    start, stop = match.span()
                    if start <= pos.character <= stop:
                        context = CompletionContext(
                            doc=doc,
                            location=location,
                            match=match,
                            position=pos,
                            capabilities=ls.client_capabilities,
                        )
                        ls.logger.debug("Completion context: %s", context)

                        for item in feature.complete(context):
                            item.data = {
                                "source_feature": name,
                                **(item.data or {})
                            }
                            items.append(item)

        return CompletionList(is_incomplete=False, items=items)

    # </engine-example>

    @server.feature(COMPLETION_ITEM_RESOLVE)
    def on_completion_resolve(ls: RstLanguageServer,
                              item: CompletionItem) -> CompletionItem:
        source = (item.data or {}).get("source_feature", "")
        feature = ls.get_feature(source)

        if not feature:
            ls.logger.error(
                "Unable to resolve completion item, unknown source: '%s'",
                source)
            return item

        return feature.completion_resolve(item)

    @server.feature(DEFINITION)
    def on_definition(ls: RstLanguageServer, params: DefinitionParams):
        uri = params.text_document.uri
        pos = params.position

        doc = ls.workspace.get_document(uri)
        line = ls.line_at_position(doc, pos)
        location = ls.get_location_type(doc, pos)

        definitions = []

        for feature in ls._features.values():
            for pattern in feature.definition_triggers:
                for match in pattern.finditer(line):
                    if not match:
                        continue

                    start, stop = match.span()
                    if start <= pos.character and pos.character <= stop:
                        context = DefinitionContext(doc=doc,
                                                    location=location,
                                                    match=match,
                                                    position=pos)
                        definitions += feature.definition(context)

        return definitions

    @server.feature(DOCUMENT_LINK)
    def on_document_link(ls: RstLanguageServer, params: DocumentLinkParams):
        uri = params.text_document.uri
        doc = ls.workspace.get_document(uri)
        context = DocumentLinkContext(doc=doc,
                                      capabilities=ls.client_capabilities)

        links = []
        for feature in ls._features.values():
            links += feature.document_link(context) or []

        return links

    @server.feature(DOCUMENT_SYMBOL)
    def on_document_symbol(ls: RstLanguageServer,
                           params: DocumentSymbolParams):

        doctree = ls.get_initial_doctree(uri=params.text_document.uri)
        if doctree is None:
            return []

        visitor = SymbolVisitor(ls, doctree)
        doctree.walkabout(visitor)

        return visitor.symbols

    @server.command(ESBONIO_SERVER_CONFIGURATION)
    def get_configuration(ls: RstLanguageServer, *args):
        """Get the server's configuration.

        Not to be confused with the ``workspace/configuration`` request where the server
        can request the client's configuration. This is so clients can ask for sphinx's
        output path for example.

        As far as I know, there isn't anything built into the spec to cater for this?
        """
        config = ls.configuration
        ls.logger.debug("%s: %s", ESBONIO_SERVER_CONFIGURATION, dump(config))

        return config

    @server.command(ESBONIO_SERVER_PREVIEW)
    def preview(ls: RstLanguageServer, *args) -> Dict[str, Any]:
        """Start/Generate a preview of the project"""
        params = {} if not args[0] else args[0][0]._asdict()
        ls.logger.debug("%s: %s", ESBONIO_SERVER_PREVIEW, params)

        return ls.preview(params) or {}

    return server
Esempio n. 7
0
        msg = err.msg
        col = err.colno
        line = err.lineno

        d = Diagnostic(range=Range(start=Position(line=line - 1,
                                                  character=col - 1),
                                   end=Position(line=line - 1, character=col)),
                       message=msg,
                       source=type(json_server).__name__)

        diagnostics.append(d)

    return diagnostics


@json_server.feature(COMPLETION, CompletionOptions(trigger_characters=[',']))
def completions(params: Optional[CompletionParams] = None) -> CompletionList:
    """Returns completion items."""
    return CompletionList(is_incomplete=False,
                          items=[
                              CompletionItem(label='"'),
                              CompletionItem(label='['),
                              CompletionItem(label=']'),
                              CompletionItem(label='{'),
                              CompletionItem(label='}'),
                          ])


@json_server.command(JsonLanguageServer.CMD_COUNT_DOWN_BLOCKING)
def count_down_10_seconds_blocking(ls, *args):
    """Starts counting down and showing message synchronously.
Esempio n. 8
0
 def _with_completion(self):
     self.server_cap.completion_provider = \
         self._provider_options(COMPLETION, default=CompletionOptions())
     return self
@language_server.feature(INITIALIZED)
async def initialized(server: GalaxyToolsLanguageServer, params: InitializeParams) -> None:
    """Loads the client configuration after initialization."""
    await _load_client_config_async(server)
    server.service.set_workspace(server.workspace)


@language_server.feature(WORKSPACE_DID_CHANGE_CONFIGURATION)
async def did_change_configuration(server: GalaxyToolsLanguageServer, params: DidChangeConfigurationParams) -> None:
    """Loads the client configuration after a change."""
    await _load_client_config_async(server)
    server.show_message("Settings updated")


@language_server.feature(COMPLETION, CompletionOptions(trigger_characters=["<", " "]))
def completions(server: GalaxyToolsLanguageServer, params: CompletionParams) -> Optional[CompletionList]:
    """Returns completion items depending on the current document context."""
    if server.configuration.completion.mode == CompletionMode.DISABLED:
        return None
    document = _get_valid_document(server, params.text_document.uri)
    if document:
        xml_document = _get_xml_document(document)
        return server.service.get_completion(xml_document, params, server.configuration.completion.mode)
    return None


@language_server.feature(HOVER)
def hover(server: GalaxyToolsLanguageServer, params: TextDocumentPositionParams) -> Optional[Hover]:
    """Displays Markdown documentation for the element under the cursor."""
    document = _get_valid_document(server, params.text_document.uri)