Example #1
0
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,
                                                   character=pos.character),
                                    end=Position(line=pos.line,
                                                 character=pos.character +
                                                 len(var_name))),
                                new_text=var_name,
                            ),
                            kind=CompletionItemKind.Variable,
                            documentation=MarkupContent(
                                kind=MarkupKind.Markdown,
                                value=f"{var_name} : {var_type} = {value}",
                            ))
        items.append(ci)
    return items
Example #2
0
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_document(params.text_document.uri)
    jedi_script = jedi_utils.script(server.project, document)
    jedi_lines = jedi_utils.line_column(jedi_script, params.position)
    signatures_jedi = jedi_script.get_signatures(**jedi_lines)
    markup_kind = _choose_markup(server)
    signatures = [
        SignatureInformation(
            label=signature.to_string(),
            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)
Example #3
0
        def f(params: HoverParams) -> Optional[Hover]:
            range = Range(
                start=Position(line=0, character=0),
                end=Position(line=1, character=1),
            )

            return {
                'file://return.marked_string':
                Hover(
                    range=range,
                    contents=MarkedString(
                        language='language',
                        value='value',
                    ),
                ),
                'file://return.marked_string_list':
                Hover(
                    range=range,
                    contents=[
                        MarkedString(
                            language='language',
                            value='value',
                        ), 'str type'
                    ],
                ),
                'file://return.markup_content':
                Hover(
                    range=range,
                    contents=MarkupContent(kind=MarkupKind.Markdown,
                                           value='value'),
                ),
            }.get(params.text_document.uri, None)
Example #4
0
    def completion_resolve_option(self,
                                  item: CompletionItem) -> CompletionItem:

        # We need the detail field set to the implementation's fully qualified name.
        if not item.detail or not item.data:
            return item

        directive, option = item.detail.split(":")
        name = typing.cast(Dict, item.data).get("for_directive", "")

        documentation = self.get_documentation(name, directive)
        if not documentation:
            return item

        description = documentation.get("options", {}).get(option, None)
        if not description:
            return item

        source = documentation.get("source", "")
        license = documentation.get("license", "")

        if source:
            description += f"\n\n[Source]({source})"

        if license:
            description += f"\n\n[License]({license})"

        kind = MarkupKind.PlainText
        if documentation.get("is_markdown", False):
            kind = MarkupKind.Markdown

        item.documentation = MarkupContent(kind=kind, value=description)
        return item
Example #5
0
def hover(
    server: JediLanguageServer, params: TextDocumentPositionParams
) -> Optional[Hover]:
    """Support Hover."""
    document = server.workspace.get_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)
    # jedi's help function is buggy when the column is 0. For this reason, as a
    # rote fix, we simply set the column to 1 if params.position returns column
    # 0.
    hover_text = jedi_utils.hover_text(
        jedi_script.help(
            line=jedi_lines[0],
            column=1 if jedi_lines[1] == 0 else jedi_lines[1],
        ),
        markup_kind,
        server.initialization_options,
    )
    if not hover_text:
        return None
    contents = MarkupContent(kind=markup_kind, value=hover_text)
    document = server.workspace.get_document(params.text_document.uri)
    _range = pygls_utils.current_word_range(document, params.position)
    return Hover(contents=contents, range=_range)
Example #6
0
def lsp_completion_item_resolve(
    item: CompletionItem,
    markup_kind: MarkupKind,
) -> CompletionItem:
    """Resolve completion item using cached jedi completion data."""
    completion = _MOST_RECENT_COMPLETIONS[item.label]
    item.detail = completion.description
    docstring = convert_docstring(completion.docstring(), markup_kind)
    item.documentation = MarkupContent(kind=markup_kind, value=docstring)
    return item
Example #7
0
def lsp_completion_item_resolve(
    item: CompletionItem,
    markup_kind: MarkupKind,
) -> CompletionItem:
    """Resolve completion item using cached jedi completion data."""
    completion = _MOST_RECENT_COMPLETIONS[item.label]
    item.detail = next(get_full_signatures(completion), completion.name)
    docstring = convert_docstring(completion.docstring(raw=True), markup_kind)
    item.documentation = MarkupContent(kind=markup_kind, value=docstring)
    return item
    def get_doc(self, lang: str = "en") -> MarkupContent:
        """Gets the Markdown documentation associated with this element
        from the XSD schema.

        If there is no documentation in the schema for the element,
        a message indicating this will be returned instead.

        Args:
            lang (str, optional): The language code of the documentation
            to retrieve. Defaults to "en" (English).

        Returns:
            [str]: The documentation text or a message indicating
            there is no documentation.
        """
        doc = self._get_doc_text_of_element(
            self.xsd_element, lang) or self._get_doc_text_of_element(
                self.xsd_type, lang)
        if doc:
            return MarkupContent(kind=MarkupKind.Markdown, value=doc)
        return MarkupContent(kind=MarkupKind.Markdown,
                             value=MSG_NO_DOCUMENTATION_AVAILABLE)
Example #9
0
def hover(server: JediLanguageServer,
          params: TextDocumentPositionParams) -> Optional[Hover]:
    """Support Hover."""
    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)
    markup_kind = _choose_markup(server)
    hover_text = jedi_utils.hover_text(jedi_script.help(**jedi_lines),
                                       markup_kind)
    if not hover_text:
        return None
    contents = MarkupContent(kind=markup_kind, value=hover_text)
    document = server.workspace.get_document(params.text_document.uri)
    _range = pygls_utils.current_word_range(document, params.position)
    return Hover(contents=contents, range=_range)
Example #10
0
    def completion_resolve_role(self, item: CompletionItem) -> CompletionItem:

        # We need the detail field set to the role implementation's fully qualified name
        if not item.detail:
            return item

        documentation = self.get_documentation(item.label, item.detail)
        if not documentation:
            return item

        description = documentation.get("description", "")
        is_markdown = documentation.get("is_markdown", False)
        kind = MarkupKind.Markdown if is_markdown else MarkupKind.PlainText

        item.documentation = MarkupContent(kind=kind, value=description)
        return item
Example #11
0
def hover(server: JediLanguageServer,
          params: TextDocumentPositionParams) -> Optional[Hover]:
    """Support Hover."""
    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)
    markup_kind = _choose_markup(server)
    for name in jedi_script.help(**jedi_lines):
        docstring = name.docstring()
        if not docstring:
            continue
        docstring_clean = jedi_utils.convert_docstring(docstring, markup_kind)
        contents = MarkupContent(kind=markup_kind, value=docstring_clean)
        document = server.workspace.get_document(params.text_document.uri)
        _range = pygls_utils.current_word_range(document, params.position)
        return Hover(contents=contents, range=_range)
    return None
Example #12
0
    def _index_lexers(self):
        self._lexers = []

        for (name, labels, files, mimes) in get_all_lexers():
            for label in labels:
                documentation = f"""\
                ### {name}

                Filenames:  {', '.join(files)}

                MIME Types: {', '.join(mimes)}
                """

                item = CompletionItem(
                    label=label,
                    kind=CompletionItemKind.Constant,
                    documentation=MarkupContent(
                        kind=MarkupKind.Markdown,
                        value=textwrap.dedent(documentation)),
                )

                self._lexers.append(item)
Example #13
0
 def get_documentation(self, xml_document: XmlDocument,
                       position: Position) -> Optional[Hover]:
     """Gets the documentation about the element at the given position."""
     context = self.xml_context_service.get_xml_context(
         xml_document, position)
     if context.node:
         if context.is_tag or context.is_attribute_key:
             documentation = self.xsd_service.get_documentation_for(context)
             context_range = self.xml_context_service.get_range_for_context(
                 xml_document, context)
             return Hover(contents=documentation, range=context_range)
         # Try to get token
         word = xml_document.document.word_at_position(position)
         token = self.definitions_provider.get_token_definition(
             xml_document, word)
         if token:
             return Hover(
                 contents=MarkupContent(kind=MarkupKind.Markdown,
                                        value=token.value),
                 range=Range(start=position, end=position),
             )
     return None
Example #14
0
    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,
        ))
information from the XSD schema.
"""

from typing import List, Optional

from lxml import etree
from pygls.lsp.types import Diagnostic, MarkupContent, MarkupKind

from galaxyls.services.context import XmlContext
from galaxyls.services.xml.document import XmlDocument
from galaxyls.services.xsd.constants import MSG_NO_DOCUMENTATION_AVAILABLE, TOOL_XSD_FILE
from galaxyls.services.xsd.parser import GalaxyToolXsdParser
from galaxyls.services.xsd.types import XsdBase
from galaxyls.services.xsd.validation import GalaxyToolValidationService

NO_DOC_MARKUP = MarkupContent(kind=MarkupKind.Markdown,
                              value=MSG_NO_DOCUMENTATION_AVAILABLE)


class GalaxyToolXsdService:
    """Galaxy tool Xml Schema Definition service.

    This service provides functionality to extract information from
    the XSD schema and validate XML files against it.
    """
    def __init__(self, server_name: str) -> None:
        """Initializes the validator by loading the XSD."""
        self.server_name = server_name
        self.xsd_doc: etree._ElementTree = etree.parse(str(TOOL_XSD_FILE))
        self.xsd_schema = etree.XMLSchema(self.xsd_doc)
        self.xsd_parser = GalaxyToolXsdParser(self.xsd_doc.getroot())
        self.validator = GalaxyToolValidationService(server_name,