### Python Language Server Quickstart Source: https://github.com/openlawlibrary/pygls/blob/main/README.md This snippet demonstrates how to set up a basic language server using pygls. It includes a completion provider that suggests 'world' or 'friend' when a line ends with 'hello.'. Ensure you have pygls and lsprotocol installed. ```python from pygls.lsp.server import LanguageServer from lsprotocol import types server = LanguageServer("example-server", "v0.1") @server.feature(types.TEXT_DOCUMENT_COMPLETION) def completions(params: types.CompletionParams): items = [] document = server.workspace.get_text_document(params.text_document.uri) current_line = document.lines[params.position.line].strip() if current_line.endswith("hello."): items = [ types.CompletionItem(label="world"), types.CompletionItem(label="friend"), ] return types.CompletionList(is_incomplete=False, items=items) server.start_io() ``` -------------------------------- ### Start pygls server with CLI helper Source: https://context7.com/openlawlibrary/pygls/llms.txt Use `start_server` to wrap a LanguageServer instance with a CLI that supports STDIO, TCP, and WebSocket transports. This is the standard entry point for example servers. ```python from pygls.cli import start_server from pygls.lsp.server import LanguageServer from lsprotocol import types server = LanguageServer("my-server", "v1") @server.feature(types.TEXT_DOCUMENT_COMPLETION) def completions(params: types.CompletionParams) -> types.CompletionList: return types.CompletionList( is_incomplete=False, items=[types.CompletionItem(label="hello"), types.CompletionItem(label="world")], ) if __name__ == "__main__": start_server(server) # Usage: # python server.py → STDIO (default, used by most editors) # python server.py --tcp → TCP on 127.0.0.1:8888 # python server.py --tcp --host 0.0.0.0 --port 9000 # python server.py --ws → WebSocket on 127.0.0.1:8888 ``` -------------------------------- ### LanguageServer Initialization and Start Source: https://context7.com/openlawlibrary/pygls/llms.txt Demonstrates how to initialize a LanguageServer instance and start it using different transport methods (STDIO, TCP, WebSocket). ```APIDOC ## LanguageServer Initialization and Start ### Description Initialize a `LanguageServer` instance with a name, version, and optional text document synchronization kind. Then, start the server using `start_io()` for STDIO, `start_tcp(host, port)` for TCP, or `start_ws(host, port)` for WebSocket connections. ### Method `LanguageServer(name, version, text_document_sync_kind=None, notebook_document_sync=None)` `start_io()` `start_tcp(host: str, port: int)` `start_ws(host: str, port: int)` ### Parameters #### LanguageServer Constructor Parameters - **name** (str) - The name of the language server. - **version** (str) - The version of the language server. - **text_document_sync_kind** (TextDocumentSyncKind | None) - Specifies how text documents are synchronized (None, Full, or Incremental). - **notebook_document_sync** (NotebookDocumentSyncOptions | None) - Options for notebook document synchronization. #### start_tcp Parameters - **host** (str) - The host address to bind to. - **port** (int) - The port number to listen on. #### start_ws Parameters - **host** (str) - The host address to bind to. - **port** (int) - The port number to listen on. ### Request Example ```python from pygls.lsp.server import LanguageServer from lsprotocol import types server = LanguageServer( name="my-lang-server", version="v1.0", text_document_sync_kind=types.TextDocumentSyncKind.Incremental, ) if __name__ == "__main__": server.start_io() # reads from stdin / writes to stdout # TCP variant (editor connects to localhost:8888): # server.start_tcp("127.0.0.1", 8888) # WebSocket variant (requires pip install pygls[ws]): # server.start_ws("127.0.0.1", 8888) ``` ``` -------------------------------- ### Start Server with WebSocket Connection Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/servers/howto/run-a-server.md Use `start_ws()` to run the server in WEBSOCKET mode, enabling connections from web browser clients. Ensure the `ws` extra is installed. ```python from pygls.lsp.server import LanguageServer server = LanguageServer('example-server', 'v0.1') if __name__ == '__main__': server.start_ws('0.0.0.0', 1234) ``` -------------------------------- ### Server Start Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/servers/examples/goto.md This snippet shows how to initialize and start the language server. It configures basic logging and calls the start_server function with the server instance. ```python import logging # Assuming start_server and server are defined elsewhere # def start_server(server): # ... # server = ... if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(message)s") start_server(server) ``` -------------------------------- ### Start JSON Server Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/servers/examples/json-server.md Initializes and starts the JSON language server. This is the main entry point for the server. ```python if __name__ == "__main__": start_server(json_server) ``` -------------------------------- ### Start Server using CLI Wrapper Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/servers/howto/run-a-server.md Pass your server instance to `start_server()` to utilize the command-line wrapper for starting the language server. ```python from pygls.cli import run_server from pygls.lsp.server import LanguageServer server = LanguageServer('example-server', 'v0.1') if __name__ == '__main__': start_server(server) ``` -------------------------------- ### Start IO Server Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/api-reference/servers.md Starts the server using standard input and output streams. Useful for environments where direct I/O is preferred. ```APIDOC ## start_io(stdin=None, stdout=None) Starts an IO server. * **Parameters:** * **stdin** (*Optional* *[**BinaryIO* *]*) * **stdout** (*Optional* *[**BinaryIO* *]*) ``` -------------------------------- ### Server Start Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/servers/examples/semantic-tokens.md Configures logging and starts the language server when the script is executed directly. This is the entry point for running the server. ```python if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(message)s") start_server(server) ``` -------------------------------- ### Minimal Logging Setup for pygls Server Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/reference/logging.md Configure basic logging with a custom message format and DEBUG level before starting the server. This setup is essential for observing server behavior. ```python import logging from pygls.lsp.server import LanguageServer server = LanguageServer('example-server', 'v0.1') if __name__ == '__main__': logging.basicConfig(message="[%(levelname)s]: %(message)s", level=logging.DEBUG) server.start_io() ``` -------------------------------- ### Start IO Server Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/api-reference/servers.md Starts the Language Server using standard input and output streams. This is typically used in environments where direct stream access is available. ```python ls.start_io(stdin=sys.stdin.buffer, stdout=sys.stdout.buffer) ``` -------------------------------- ### Start WebSocket Server Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/api-reference/servers.md Starts the server listening on a specified WebSocket host and port. This enables WebSocket-based communication. ```APIDOC ## start_ws(host, port) Starts WebSocket server. * **Parameters:** * **host** (*str*) * **port** (*int*) * **Return type:** None ``` -------------------------------- ### start_io Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/api-reference/servers.md Starts an IO server with specified stdin and stdout streams. ```APIDOC ## start_io(stdin=None, stdout=None) ### Description Starts an IO server. ### Parameters * **stdin** (*Optional* *[**BinaryIO* *]*) * **stdout** (*Optional* *[**BinaryIO* *]*) ``` -------------------------------- ### Server Startup Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/servers/examples/threaded-handlers.md The main entry point for starting the language server. It uses the `start_server` function from `pygls.cli`. ```python if __name__ == "__main__": start_server(server) ``` -------------------------------- ### Start TCP Server Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/api-reference/servers.md Starts the server listening on a specified TCP host and port. This allows clients to connect over the network. ```APIDOC ## start_tcp(host, port) Starts TCP server. * **Parameters:** * **host** (*str*) * **port** (*int*) * **Return type:** None ``` -------------------------------- ### Start Server with STDIO Connection Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/servers/howto/run-a-server.md Use `start_io()` to run the server in STDIO mode, which is the default for most editors and IDEs. The client starts the server as a child process and communicates via stdin/stdout. ```python from pygls.lsp.server import LanguageServer server = LanguageServer('example-server', 'v0.1') if __name__ == '__main__': server.start_io() ``` -------------------------------- ### Install Node Dependencies Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/contributing/howto/run-pyodide-test-suite.md Install the required node dependencies for Pyodide testing. Navigate to the 'tests/pyodide' directory before running this command. ```bash cd tests/pyodide tests/pyodide $ npm ci ``` -------------------------------- ### Start TCP Server Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/api-reference/servers.md Starts the Language Server listening on a specified TCP host and port. This allows clients to connect to the server over the network. ```python ls.start_tcp('localhost', 2000) ``` -------------------------------- ### Start the Language Server Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/servers/examples/code-lens.md This is the main entry point for the server. It configures basic logging and starts the pygls LanguageServer instance. This code should be placed within an `if __name__ == "__main__":` block to ensure it only runs when the script is executed directly. ```python if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(message)s") start_server(server) ``` -------------------------------- ### start_ws Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/api-reference/servers.md Starts a WebSocket server on the specified host and port. ```APIDOC ## start_ws(host, port) ### Description Starts WebSocket server. ### Parameters * **host** (*str*) * **port** (*int*) ### Return type None ``` -------------------------------- ### Starting a Language Server via TCP Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/api-reference/clients.md Establishes a connection to a Language Server listening on a specified host and port using TCP. ```python await ls.start_tcp(host, port) ``` -------------------------------- ### Minimal STDIO Server with LanguageServer Source: https://context7.com/openlawlibrary/pygls/llms.txt This is a minimal example of a STDIO server. Launch it using `python server.py`. It reads from stdin and writes to stdout. ```python from pygls.lsp.server import LanguageServer from lsprotocol import types # Minimal STDIO server — launch with: python server.py server = LanguageServer( name="my-lang-server", version="v1.0", text_document_sync_kind=types.TextDocumentSyncKind.Incremental, ) if __name__ == "__main__": server.start_io() # reads from stdin / writes to stdout # TCP variant (editor connects to localhost:8888): # server.start_tcp("127.0.0.1", 8888) # WebSocket variant (requires pip install pygls[ws]): # server.start_ws("127.0.0.1", 8888) ``` -------------------------------- ### Install pygls with WebSocket Support Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/servers/howto/run-a-server.md To use WEBSOCKET connections, install pygls with the `ws` extra. ```default pip install pygls[ws] ``` -------------------------------- ### Start WebSocket Server Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/api-reference/servers.md Starts the Language Server listening on a specified WebSocket host and port. This is commonly used for web-based clients. ```python ls.start_ws('localhost', 2000) ``` -------------------------------- ### start_tcp Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/api-reference/servers.md Starts a TCP server on the specified host and port. ```APIDOC ## start_tcp(host, port) ### Description Starts TCP server. ### Parameters * **host** (*str*) * **port** (*int*) ### Return type None ``` -------------------------------- ### Install pygls Locally Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/howto/use-the-pygls-playground.md Install the pygls library in editable mode within your activated virtual environment. This allows for direct use of the installed package. ```bash (env) $ python -m pip install -e . ``` -------------------------------- ### Starting a Language Server via WebSockets Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/api-reference/clients.md Connects to a Language Server that is accessible via WebSockets on a given host and port. ```python await ls.start_ws(host, port) ``` -------------------------------- ### Starting a Language Server via Stdio Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/api-reference/clients.md Initiates communication with a Language Server by executing a command and interacting over standard input/output. ```python await ls.start_io(cmd, *args, **kwargs) ``` -------------------------------- ### Language Server Setup and Completion Handler Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/servers/examples/threaded-handlers.md Sets up the LanguageServer instance and defines a completion handler. This handler provides static completion items when triggered. ```python import time import threading from lsprotocol import types from pygls.cli import start_server from pygls.lsp.server import LanguageServer server = LanguageServer("threaded-server", "v1") @server.feature( types.TEXT_DOCUMENT_COMPLETION, types.CompletionOptions(trigger_characters=["."]), ) def completions(params: types.CompletionParams | None = None) -> types.CompletionList: """Returns completion items.""" return types.CompletionList( is_incomplete=False, items=[ types.CompletionItem(label="one"), types.CompletionItem(label="two"), types.CompletionItem(label="three"), types.CompletionItem(label="four"), types.CompletionItem(label="five"), ], ) ``` -------------------------------- ### Vim Configuration with vim-lsp Source: https://github.com/openlawlibrary/pygls/blob/main/examples/hello-world/README.md Register the Pygls Hello World server with vim-lsp. This setup allows vim-lsp to manage the server connection. ```vim augroup HelloWorldPythonExample au! autocmd User lsp_setup call lsp#register_server({ \ 'name': 'hello-world-pygls-example', \ 'cmd': {server_info->['python', 'path-to-hello-world-example/main.py']}, \ 'allowlist': ['*'] \ }) augroup END ``` -------------------------------- ### Legacy Command Handler Example Source: https://context7.com/openlawlibrary/pygls/llms.txt An example of a command handler that accepts arguments as positional parameters without explicit type annotations, representing a legacy style. ```python @server.command("math.subtract") def math_subtract(ls: LanguageServer, left, right): ls.window_show_message( types.ShowMessageParams( message=f"Result: {left - right}", type=types.MessageType.Info, ) ) if __name__ == "__main__": server.start_io() ``` -------------------------------- ### Start Server with TCP Connection Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/servers/howto/run-a-server.md Use `start_tcp()` to run the server in TCP mode, allowing it to run independently from the client. The client then connects using the provided host and port. ```python from pygls.lsp.server import LanguageServer server = LanguageServer('example-server', 'v0.1') if __name__ == '__main__': server.start_tcp('127.0.0.1', 8080) ``` -------------------------------- ### Starting Server After Log File is Open Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/servers/howto/run-a-server-in-pyodide.md Ensures the server only starts after the log file has been successfully opened, using an event listener. This is crucial because Node.js's `fs` API is asynchronous. ```javascript logFile.once('open', (fd) => { runServer(serverCode).then(() => { logFile.end(); process.exit(0) }).catch(err => { logFile.write(`Error in server process\n${err}`) logFile.end(); process.exit(1); }) }) ``` -------------------------------- ### Semantic Tokens Server Initialization Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/servers/examples/semantic-tokens.md Initializes the SemanticTokensServer instance. This is the starting point for the language server. ```python server = SemanticTokensServer("semantic-tokens-server", "v1") ``` -------------------------------- ### InitializeRequest Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/api-reference/types.md Represents the initialize request sent from the client to the server. This is typically sent once after the server starts. ```APIDOC ## InitializeRequest ### Description The initialize request is sent from the client to the server. It is sent once as the request after starting up the server. The requests parameter is of type [`InitializeParams`](#lsprotocol.types.InitializeParams) the response if of type [`InitializeResult`](#lsprotocol.types.InitializeResult) of a Thenable that resolves to such. ### Method initialize ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Neovim Lua Configuration for Pygls Server Source: https://github.com/openlawlibrary/pygls/blob/main/examples/hello-world/README.md Configure Neovim to start the Pygls Hello World server manually. Ensure the python path to your main.py is correct. ```lua vim.api.nvim_create_autocmd({ "BufEnter" }, { -- NB: You must remember to manually put the file extension pattern matchers for each LSP filetype pattern = { "*" }, callback = function() vim.lsp.start({ name = "hello-world-pygls-example", cmd = { "python path-to-hello-world-example/main.py" }, root_dir = vim.fs.dirname(vim.fs.find({ ".git" }, { upward = true })[1]) }) end, }) ``` -------------------------------- ### Configure Notebook Document Synchronization Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/servers/howto/add-notebook-support.md Provide an instance of `NotebookDocumentSyncOptions` to declare interest in specific notebook types. This example configures the server to synchronize Python notebooks. ```python server = LanguageServer( name="example-server", version="v0.1", notebook_document_sync=types.NotebookDocumentSyncOptions( notebook_selector=[ types.NotebookDocumentFilterWithCells( cells=[ types.NotebookCellLanguage( language="python" ), ], ), ], ), ) ``` -------------------------------- ### Glob Pattern Example Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/api-reference/types.md Illustrates glob patterns used for matching file paths. Supports relative patterns with LSP v3.18.0. ```plaintext ** ``` ```plaintext * ``` -------------------------------- ### Run All Linters Locally Source: https://github.com/openlawlibrary/pygls/blob/main/PULL_REQUEST_TEMPLATE.md Execute all automated linters locally using the provided command. Ensure you have the necessary environment setup with `uv`. ```sh uv run --all-extras poe lint ``` -------------------------------- ### Range Definition Example Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/api-reference/types.md Illustrates how to define a range within a text document, specifying start and end positions. The end position should denote the start of the next line to include the current line's ending characters. ```typescript { start: { line: 5, character: 23 } end : { line 6, character : 0 } } ``` -------------------------------- ### Get word at client position Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/api-reference/workspace.md Retrieves the word at a given client position. It uses regular expressions to find the start and end of the word, allowing for customizable word boundary definitions. ```python document.word_at_position(position) ``` -------------------------------- ### Handle Server Configuration Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/servers/examples/json-server.md Processes configuration settings sent from the client, specifically looking for 'exampleConfiguration'. It then displays this value using a window message. ```python def handle_config(ls: JsonLanguageServer, config): """Handle the configuration sent by the client.""" try: example_config = config[0].get("exampleConfiguration") ls.window_show_message( lsp.ShowMessageParams( message=f"jsonServer.exampleConfiguration value: {example_config}", ``` -------------------------------- ### Install npm Dependencies for Playground Extension Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/howto/use-the-pygls-playground.md Install the necessary Node.js dependencies for the pygls-playground VSCode extension. This is required before compiling the extension. ```bash .vscode/extensions/pygls-playground/ $ npm install --no-save ``` -------------------------------- ### Implementation Provider Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/api-reference/types.md The server provides Goto Implementation support. ```APIDOC ## implementation_provider ### Description The server provides Goto Implementation support. ### Type `bool | ImplementationOptions | ImplementationRegistrationOptions | None` ``` -------------------------------- ### initialize Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/api-reference/clients.md Make an initialize request to the language server. ```APIDOC ## initialize(params, callback=None) ### Description Make a [initialize](https://microsoft.github.io/language-server-protocol/specification.html#initialize) request. The initialize request is sent from the client to the server. It is sent once as the request after starting up the server. The requests parameter is of type [`InitializeParams`](types.md#lsprotocol.types.InitializeParams) the response if of type [`InitializeResult`](types.md#lsprotocol.types.InitializeResult) of a Thenable that resolves to such. ### Parameters * **params** ([*types.InitializeParams*](types.md#lsprotocol.types.InitializeParams)) * **callback** (*Optional* *[**Callable* *[* *[*[*types.InitializeResult*](types.md#lsprotocol.types.InitializeResult) *]* *,* *None* *]* *]*) ### Return type Future[[types.InitializeResult](types.md#lsprotocol.types.InitializeResult)] ``` -------------------------------- ### Semantic Token Representation Example Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/protocol/howto/interpret-semantic-tokens.md This example shows the raw integer sequence representing semantic tokens. Each group of 5 integers corresponds to a single token. ```default [0, 2, 1, 0, 3, 0, 4, 2, 1, 0, ...] ^-----------^ ^-----------^ 1st token 2nd token etc. ``` -------------------------------- ### JsonRPCClient.start_io Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/api-reference/clients.md Asynchronous method to initiate communication with a language server via its standard input/output streams. ```APIDOC #### *async* start_io(cmd, \*args, \*\*kwargs) Start the given server and communicate with it over stdio. * **Parameters:** **cmd** (*str*) ``` -------------------------------- ### text_document_hover Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/api-reference/clients.md Make a textDocument/hover request to get hover information at a specific position. ```APIDOC ## text_document_hover(params, callback=None) ### Description Make a [textDocument/hover](https://microsoft.github.io/language-server-protocol/specification.html#textDocument_hover) request. Request to request hover information at a given text document position. The request’s parameter is of type `TextDocumentPosition` the response is of type [`Hover`](types.md#lsprotocol.types.Hover) or a Thenable that resolves to such. ### Parameters * **params** ([*types.HoverParams*](types.md#lsprotocol.types.HoverParams)) * **callback** (*Optional* *[**Callable* *[* *[**Optional* *[*[*types.Hover*](types.md#lsprotocol.types.Hover) *]* *]* *,* *None* *]* *]*) ### Return type Future[Optional[[types.Hover](types.md#lsprotocol.types.Hover)]] ``` -------------------------------- ### document_link_resolve Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/api-reference/clients.md Make a documentLink/resolve request to get additional information for a document link. ```APIDOC ## document_link_resolve(params, callback=None) ### Description Make a [documentLink/resolve](https://microsoft.github.io/language-server-protocol/specification.html#documentLink_resolve) request. Request to resolve additional information for a given document link. The request’s parameter is of type [`DocumentLink`](types.md#lsprotocol.types.DocumentLink) the response is of type [`DocumentLink`](types.md#lsprotocol.types.DocumentLink) or a Thenable that resolves to such. ### Parameters * **params** ([*types.DocumentLink*](types.md#lsprotocol.types.DocumentLink)) * **callback** (*Optional* *[**Callable* *[* *[*[*types.DocumentLink*](types.md#lsprotocol.types.DocumentLink) *]* *,* *None* *]* *]*) ### Return type Future[[types.DocumentLink](types.md#lsprotocol.types.DocumentLink)] ``` -------------------------------- ### NodeJS Wrapper Script for Pyodide Server Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/servers/howto/run-a-server-in-pyodide.md This script initializes Pyodide, installs 'pygls' using micropip, and runs a Python server script. It assumes the Python script calls `start_io()` and is executed via `node run_server.js /path/to/server.py`. ```javascript const fs = require('fs'); const { loadPyodide } = require('pyodide'); async function runServer(serverCode) { // Initialize pyodide. const pyodide = await loadPyodide() // Install dependencies await pyodide.loadPackage("micropip") const micropip = pyodide.pyimport("micropip") await micropip.install("pygls") // Run the server await pyodide.runPythonAsync(serverCode) } if (process.argv.length < 3) { console.error("Missing server.py file") process.exit(1) } // Read the contents of the given `server.py` file. const serverCode = fs.readFileSync(process.argv[2], 'utf8') runServer(serverCode).then(() => { process.exit(0) }).catch(err => { process.exit(1); }) ``` -------------------------------- ### completion_item_resolve Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/api-reference/clients.md Make a completionItem/resolve request to get additional information for a completion item. ```APIDOC ## completion_item_resolve(params, callback=None) ### Description Make a [completionItem/resolve](https://microsoft.github.io/language-server-protocol/specification.html#completionItem_resolve) request. Request to resolve additional information for a given completion item.The request’s parameter is of type [`CompletionItem`](types.md#lsprotocol.types.CompletionItem) the response is of type [`CompletionItem`](types.md#lsprotocol.types.CompletionItem) or a Thenable that resolves to such. ### Parameters * **params** ([*types.CompletionItem*](types.md#lsprotocol.types.CompletionItem)) * **callback** (*Optional* *[**Callable* *[* *[*[*types.CompletionItem*](types.md#lsprotocol.types.CompletionItem) *]* *,* *None* *]* *]*) ### Return type Future[[types.CompletionItem](types.md#lsprotocol.types.CompletionItem)] ``` -------------------------------- ### initialize_async Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/api-reference/clients.md Sends an 'initialize' request to the language server. This is typically the first request sent after server startup. ```APIDOC ## initialize_async(params) ### Description Sends an 'initialize' request to the language server. This is typically the first request sent after server startup. ### Method async ### Parameters * **params** ([*InitializeParams*](types.md#lsprotocol.types.InitializeParams)) - Description of the initialization parameters. ### Return type [*InitializeResult*](types.md#lsprotocol.types.InitializeResult) - The result of the initialization. ``` -------------------------------- ### work_done_progress Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/api-reference/servers.md Property to get the object responsible for managing the client's progress bar. ```APIDOC ## *property* work_done_progress *: [Progress](#pygls.progress.Progress)* Gets the object to manage client’s progress bar. ``` -------------------------------- ### pygls.cli.start_server Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/api-reference/servers.md A helper function that implements a simple CLI wrapper for a pygls server, allowing users to select between supported transports. ```APIDOC ### pygls.cli.start_server(server, args=None) A helper function that implements a simple cli wrapper for a pygls server allowing the user to select between the supported transports. * **Parameters:** * **server** ([*JsonRPCServer*](#pygls.server.JsonRPCServer)) * **args** (*list* *[**str* *]* *|* *None*) ``` -------------------------------- ### Python Inlay Hints Server Implementation Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/servers/examples/inlay-hints.md This Python code implements a language server that provides inlay hints. It scans for numbers and displays their binary representation. The inlayHint/resolve feature is used to defer tooltip computation. ```python import re from typing import Optional from lsprotocol import types from pygls.cli import start_server from pygls.lsp.server import LanguageServer NUMBER = re.compile(r"\d+") server = LanguageServer("inlay-hint-server", "v1") def parse_int(chars: str) -> Optional[int]: try: return int(chars) except Exception: return None @server.feature(types.TEXT_DOCUMENT_INLAY_HINT) def inlay_hints(params: types.InlayHintParams): items = [] document_uri = params.text_document.uri document = server.workspace.get_text_document(document_uri) start_line = params.range.start.line end_line = params.range.end.line lines = document.lines[start_line : end_line + 1] for lineno, line in enumerate(lines): for match in NUMBER.finditer(line): if not match: continue number = parse_int(match.group(0)) if number is None: continue binary_num = bin(number).split("b")[1] items.append( types.InlayHint( label=f":{binary_num}", kind=types.InlayHintKind.Type, padding_left=False, padding_right=True, position=types.Position(line=lineno, character=match.end()), ) ) return items @server.feature(types.INLAY_HINT_RESOLVE) def inlay_hint_resolve(hint: types.InlayHint): try: n = int(hint.label[1:], 2) hint.tooltip = f"Binary representation of the number: {n}" except Exception: pass return hint if __name__ == "__main__": start_server(server) ``` -------------------------------- ### FoldingRange Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/api-reference/types.md Represents a folding range within a document, specifying start and end lines and characters. ```APIDOC ## class lsprotocol.types.FoldingRange(start_line, end_line, start_character=None, end_character=None, kind=None, collapsed_text=None) ### Description Represents a folding range. To be valid, start and end line must be bigger than zero and smaller than the number of lines in the document. Clients are free to ignore invalid ranges. ### Parameters * **start_line** (*int*) The zero-based start line of the range to fold. The folded area starts after the line’s last character. To be valid, the end must be zero or larger and smaller than the number of lines in the document. * **end_line** (*int*) The zero-based end line of the range to fold. The folded area ends with the line’s last character. To be valid, the end must be zero or larger and smaller than the number of lines in the document. * **start_character** (*int* *|* *None*) The zero-based character offset from where the folded range starts. If not defined, defaults to the length of the start line. * **end_character** (*int* *|* *None*) The zero-based character offset before the folded range ends. If not defined, defaults to the length of the end line. * **kind** ([*FoldingRangeKind*](#lsprotocol.types.FoldingRangeKind) *|* *str* *|* *None*) Describes the kind of the folding range such as ‘comment’ or ‘region’. The kind is used to categorize folding ranges and used by commands like ‘Fold all comments’. See [`FoldingRangeKind`](#lsprotocol.types.FoldingRangeKind) for an enumeration of standardized kinds. * **collapsed_text** (*str* *|* *None*) The text that the client should show when the specified range is collapsed. If not defined or not supported by the client, a default will be chosen by the client. LSP v3.17.0 ``` -------------------------------- ### JsonRPCClient.start_ws Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/api-reference/clients.md Asynchronous method to initiate communication with a language server over a WebSocket connection. ```APIDOC #### *async* start_ws(host, port) Start communicating with a server over WebSockets. * **Parameters:** * **host** (*str*) * **port** (*int*) ``` -------------------------------- ### Basic Language Server Implementation in Python Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/index.md This snippet demonstrates the fundamental structure for creating a language server using pygls. It includes setting up the server, defining a completion feature, and starting the server. ```python from pygls.lsp.server import LanguageServer from lsprotocol import types server = LanguageServer("example-server", "v0.1") @server.feature( types.TEXT_DOCUMENT_COMPLETION, types.CompletionOptions(trigger_characters=["."]), ) def completions(params: types.CompletionParams): document = server.workspace.get_text_document(params.text_document.uri) current_line = document.lines[params.position.line].strip() if not current_line.endswith("hello."): return [] return [ types.CompletionItem(label="world"), types.CompletionItem(label="friend"), ] if __name__ == "__main__": server.start_io() ``` -------------------------------- ### text_document_moniker_async Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/api-reference/clients.md Make an asynchronous textDocument/moniker request to get the moniker of a symbol at a given text document position. ```APIDOC ## text_document_moniker_async(params) ### Description Make a [textDocument/moniker](https://microsoft.github.io/language-server-protocol/specification.html#textDocument_moniker) request. A request to get the moniker of a symbol at a given text document position. The request parameter is of type [`TextDocumentPositionParams`](types.md#lsprotocol.types.TextDocumentPositionParams). The response is of type [{@link](mailto:{@link) Moniker Moniker[]} or `null` . ### Parameters **params** ([*types.MonikerParams*](types.md#lsprotocol.types.MonikerParams)) ### Return type Optional[Sequence[[types.Moniker](types.md#lsprotocol.types.Moniker)]] ``` -------------------------------- ### code_action_resolve Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/api-reference/clients.md Makes a codeAction/resolve request to the Language Server to get additional information for a given code action. ```APIDOC ## code_action_resolve(params, callback=None) ### Description Make a [codeAction/resolve](https://microsoft.github.io/language-server-protocol/specification.html#codeAction_resolve) request. Request to resolve additional information for a given code action.The request’s parameter is of type [`CodeAction`](types.md#lsprotocol.types.CodeAction) the response is of type [`CodeAction`](types.md#lsprotocol.types.CodeAction) or a Thenable that resolves to such. ### Parameters * **params** (types.CodeAction) - The code action to resolve. * **callback** (Optional[Callable[[Sequence[types.CodeAction]], None]]) - An optional callback function to handle the response. ``` -------------------------------- ### NotebookCellArrayChange Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/api-reference/types.md Describes changes to a NotebookCell array, specifying the start index, number of cells to delete, and the new cells to insert. ```APIDOC ## NotebookCellArrayChange ### Description A change describing how to move a `NotebookCell` array from state S to S’. **LSP v3.17.0** ### Parameters #### start - **start** (int) - Required - The start of the cell that changed. #### delete_count - **delete_count** (int) - Required - The number of cells deleted. #### cells - **cells** (Sequence[[NotebookCell](#lsprotocol.types.NotebookCell)] | None) - Optional - The new cells, if any. ``` -------------------------------- ### Instantiate LanguageServer with Custom Protocol Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/howto/send-custom-messages.md Pass your custom protocol class to the `LanguageServer` constructor to use it. ```default server = LanguageServer( name="my-language-server", version="v1.0", protocol_cls=MyCustomExtension, ) ``` -------------------------------- ### Show Configuration with Callback Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/servers/examples/json-server.md Retrieves workspace configuration using a callback function. This is useful for handling responses in a non-blocking manner. ```python def show_configuration_callback(ls: JsonLanguageServer, *args): """Gets exampleConfiguration from the client settings using callback.""" ls.workspace_configuration( lsp.ConfigurationParams( items=[ lsp.ConfigurationItem( scope_uri="", section=JsonLanguageServer.CONFIGURATION_SECTION, ), ] ), callback=partial(handle_config, ls), ) ``` -------------------------------- ### Server Initialization and Formatting Features Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/servers/examples/formatting.md Initializes the LanguageServer and registers features for document, range, and on-type formatting. The on-type formatting is triggered by the '|' character. ```python import logging from typing import Dict from typing import List from typing import Optional import attrs from lsprotocol import types from pygls.cli import start_server from pygls.lsp.server import LanguageServer from pygls.workspace import TextDocument @attrs.define class Row: """Represents a row in the table""" cells: List[str] cell_widths: List[int] line_number: int server = LanguageServer("formatting-server", "v1") @server.feature(types.TEXT_DOCUMENT_FORMATTING) def format_document(ls: LanguageServer, params: types.DocumentFormattingParams): """Format the entire document""" logging.debug("%s", params) doc = ls.workspace.get_text_document(params.text_document.uri) rows = parse_document(doc) return format_table(rows) @server.feature(types.TEXT_DOCUMENT_RANGE_FORMATTING) def format_range(ls: LanguageServer, params: types.DocumentRangeFormattingParams): """Format the given range within a document""" logging.debug("%s", params) doc = ls.workspace.get_text_document(params.text_document.uri) rows = parse_document(doc, params.range) return format_table(rows, params.range) @server.feature( types.TEXT_DOCUMENT_ON_TYPE_FORMATTING, types.DocumentOnTypeFormattingOptions(first_trigger_character="|"), ) def format_on_type(ls: LanguageServer, params: types.DocumentOnTypeFormattingParams): """Format the document while the user is typing""" logging.debug("%s", params) doc = ls.workspace.get_text_document(params.text_document.uri) rows = parse_document(doc) return format_table(rows) ``` -------------------------------- ### TextDocumentFilter Example (Typescript Files) Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/api-reference/types.md A document filter that applies to typescript files on disk. It specifies the language and the scheme of the resource. ```json { language: 'typescript', scheme: 'file' } ``` -------------------------------- ### CLI Wrapper Usage Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/servers/howto/run-a-server.md The CLI wrapper allows users to select connection types (STDIO, TCP, WebSocket) via command-line arguments. By default, it starts the server in STDIO mode. ```none usage: my-lsp-server [-h] [--tcp] [--ws] [--host HOST] [--port PORT] start a LanguageServer instance options: -h, --help show this help message and exit --tcp start a TCP server --ws start a WebSocket server --host HOST bind to this address --port PORT bind to this port ``` -------------------------------- ### SymbolTag Enum Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/api-reference/types.md Provides extra annotations for symbols, influencing their rendering. For example, the Deprecated tag indicates a symbol is obsolete. ```APIDOC ## SymbolTag Enum Symbol tags are extra annotations that tweak the rendering of a symbol. ### Members - **Deprecated** = 1 ``` -------------------------------- ### InlayHintOptions Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/api-reference/types.md Configuration options for inlay hints when registered statically, including whether a resolve provider is available and support for work done progress reporting. ```APIDOC ## InlayHintOptions ### Description Inlay hint options used during static registration. **LSP v3.17.0** ### Parameters - **resolve_provider** (bool | None) - The server provides support to resolve additional information for an inlay hint item. - **work_done_progress** (bool | None) - Indicates whether the server supports reporting work done progress. ### Fields - **resolve_provider** (bool | None) - The server provides support to resolve additional information for an inlay hint item. - **work_done_progress** (bool | None) - Indicates whether the server supports reporting work done progress. ``` -------------------------------- ### text_document_prepare_rename Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/api-reference/clients.md Make a textDocument/prepareRename request to test and perform the setup necessary for a rename. Supports default behavior for LSP v3.16. ```APIDOC ## text_document_prepare_rename(params, callback=None) ### Description Make a [textDocument/prepareRename](https://microsoft.github.io/language-server-protocol/specification.html#textDocument_prepareRename) request. A request to test and perform the setup necessary for a rename. **LSP v3.16** - support for default behavior ### Parameters * **params** ([*types.PrepareRenameParams*](types.md#lsprotocol.types.PrepareRenameParams)) * **callback** (*Optional* *[**Callable** *[* *[**Union** *[*[*types.Range*](types.md#lsprotocol.types.Range) *,* [*types.PrepareRenamePlaceholder*](types.md#lsprotocol.types.PrepareRenamePlaceholder) *,* [*types.PrepareRenameDefaultBehavior*](types.md#lsprotocol.types.PrepareRenameDefaultBehavior) *,* *None* *]* *]* *,* *None* *]* *]*) ### Return type Future[Union[[types.Range](types.md#lsprotocol.types.Range), [types.PrepareRenamePlaceholder](types.md#lsprotocol.types.PrepareRenamePlaceholder), [types.PrepareRenameDefaultBehavior](types.md#lsprotocol.types.PrepareRenameDefaultBehavior), None]] ``` -------------------------------- ### CompletionRequest Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/api-reference/types.md Represents a request to get completion suggestions at a specific position in a text document. The response can be a list of CompletionItem or a CompletionList. ```APIDOC ## CompletionRequest ### Description Request to request completion at a given text document position. The request’s parameter is of type `TextDocumentPosition` the response is of type `CompletionItem CompletionItem[]` or [{@link](mailto:{@link) CompletionList} or a Thenable that resolves to such. The request can delay the computation of the [{@link](mailto:{@link) CompletionItem.detail `detail` } and [{@link](mailto:{@link) CompletionItem.documentation `documentation` } properties to the completionItem/resolve request. However, properties that are needed for the initial sorting and filtering, like `sortText` , `filterText` , insertText, and textEdit, must not be changed during resolve. ### Method POST ### Endpoint /textDocument/completion ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **id** (int | str) - Required - The request id. * **params** (CompletionParams) - Required - Parameters for the completion request. * **method** (Literal['textDocument/completion']) - Required - The method to be invoked. * **jsonrpc** (str) - Required - JSON RPC version, defaults to '2.0'. ### Request Example ```json { "jsonrpc": "2.0", "id": 1, "method": "textDocument/completion", "params": { "textDocument": { "uri": "file:///path/to/document.txt" }, "position": { "line": 0, "character": 0 } } } ``` ### Response #### Success Response (200) * **id** (int | str | None) - The request id. * **result** (Sequence[CompletionItem] | CompletionList | None) - The result of the completion request. * **jsonrpc** (str) - JSON RPC version. #### Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": [ { "label": "Item 1", "kind": 1, "detail": "Details for item 1" }, { "label": "Item 2", "kind": 2, "documentation": "Documentation for item 2" } ] } ``` ``` -------------------------------- ### text_document_moniker Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/api-reference/clients.md Make a textDocument/moniker request to get the moniker of a symbol at a given text document position. This is a synchronous version of the request. ```APIDOC ## text_document_moniker(params, callback=None) ### Description Make a [textDocument/moniker](https://microsoft.github.io/language-server-protocol/specification.html#textDocument_moniker) request. A request to get the moniker of a symbol at a given text document position. The request parameter is of type [`TextDocumentPositionParams`](types.md#lsprotocol.types.TextDocumentPositionParams). The response is of type [{@link](mailto:{@link) Moniker Moniker[]} or `null` . ### Parameters * **params** ([*types.MonikerParams*](types.md#lsprotocol.types.MonikerParams)) * **callback** (*Optional* *[**Callable* *[* *[**Optional* *[**Sequence* *[*[*types.Moniker*](types.md#lsprotocol.types.Moniker) *]* *]* *]* *,* *None* *]* *]*) ### Return type Future[Optional[Sequence[[types.Moniker](types.md#lsprotocol.types.Moniker)]]] ``` -------------------------------- ### JsonRPCClient.start_tcp Source: https://github.com/openlawlibrary/pygls/blob/main/docs/source/pygls/api-reference/clients.md Asynchronous method to establish a connection and begin communication with a language server over a TCP socket. ```APIDOC #### *async* start_tcp(host, port) Start communicating with a server over TCP. * **Parameters:** * **host** (*str*) * **port** (*int*) ```