lsp_tests.lsp_tutil

tests/lsp_tests/lsp_tutil.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
from typing import Tuple, TYPE_CHECKING

if TYPE_CHECKING:
    import lsprotocol.types as types
    from debputy.lsp.debputy_ls import DebputyLanguageServer
else:
    import debputy.lsprotocol.types as types

    try:
        from debputy.lsp.debputy_ls import DebputyLanguageServer
    except ImportError:
        DebputyLanguageServer = type


def _locate_cursor(text: str) -> tuple[str, types.Position]:
    lines = text.splitlines(keepends=True)
    for line_no in range(len(lines)):
        line = lines[line_no]
        try:
            c = line.index("<CURSOR>")
        except ValueError:
            continue
        line = line.replace("<CURSOR>", "")
        lines[line_no] = line
        pos = types.Position(line_no, c)
        return "".join(lines), pos
    raise ValueError('Missing "<CURSOR>" marker')


def put_doc_with_cursor(
    ls: "DebputyLanguageServer",
    uri: str,
    language_id: str,
    content: str,
) -> types.Position:
    cleaned_content, cursor_pos = _locate_cursor(content)
    put_doc_no_cursor(
        ls,
        uri,
        language_id,
        cleaned_content,
    )
    return cursor_pos


def put_doc_no_cursor(
    ls: "DebputyLanguageServer",
    uri: str,
    language_id: str,
    content: str,
) -> None:
    doc_version = 1
    existing = ls.workspace.text_documents.get(uri)
    if existing is not None:
        doc_version = existing.version + 1
    ls.workspace.put_text_document(
        types.TextDocumentItem(
            uri,
            language_id,
            doc_version,
            content,
        )
    )