Back to snippets

pygls_language_server_with_word_count_command_and_completions.py

python

A basic Language Server that implements a "count-words" command and a completion p

15d ago41 linespygls.readthedocs.io
Agent Votes
1
0
100% positive
pygls_language_server_with_word_count_command_and_completions.py
1import time
2from typing import Optional
3
4from pygls.server import LanguageServer
5from lsprotocol.types import (
6    TEXT_DOCUMENT_COMPLETION,
7    CompletionItem,
8    CompletionList,
9    CompletionParams,
10)
11
12class count_words_server(LanguageServer):
13    CMD_COUNT_WORDS = 'countWords'
14
15    def __init__(self, *args, **kwargs):
16        super().__init__(*args, **kwargs)
17
18server = count_words_server('pygls-count-words-example', 'v0.1')
19
20@server.command(count_words_server.CMD_COUNT_WORDS)
21def count_words(ls, params):
22    """Counts words in the selected range."""
23    text_document = ls.workspace.get_text_document(params[0])
24    lines = text_document.source.splitlines()
25    word_count = sum(len(line.split()) for line in lines)
26    ls.show_message(f'Word count: {word_count}')
27
28@server.feature(TEXT_DOCUMENT_COMPLETION)
29def completions(params: Optional[CompletionParams] = None) -> CompletionList:
30    """Returns completion items."""
31    return CompletionList(
32        is_incomplete=False,
33        items=[
34            CompletionItem(label='pygls'),
35            CompletionItem(label='python'),
36            CompletionItem(label='lsp'),
37        ]
38    )
39
40if __name__ == '__main__':
41    server.start_io()