### Install pylspclient Source: https://github.com/yeger00/pylspclient/blob/main/README.md Install the pylspclient package using pip. This is the primary method for users to get started with the library. ```bash pip install pylspclient ``` -------------------------------- ### LspClient.initialize Source: https://context7.com/yeger00/pylspclient/llms.txt Starts an LSP session by sending the mandatory 'initialize' request to the language server. This method must be called exactly once before any other LSP methods. ```APIDOC ## `LspClient.initialize` — Start an LSP session `initialize(processId, rootPath, rootUri, initializationOptions, capabilities, trace, workspaceFolders)` sends the mandatory `initialize` request to the language server, starts the `LspEndpoint` background thread, and returns the server's capability negotiation result. `capabilities` is required. This must be called exactly once before any other LSP methods. ### Parameters - **processId** (any) - Optional - The process ID of the client. - **rootPath** (string) - Optional - The root path of the workspace. - **rootUri** (string) - Required - The root URI of the workspace. - **initializationOptions** (any) - Optional - Options for initialization. - **capabilities** (any) - Required - The client's capabilities. - **trace** (string) - Optional - The trace level ('off', 'messages', 'verbose'). - **workspaceFolders** (list) - Optional - The workspace folders. ### Request Example ```python client.initialize( processId=None, rootPath=None, rootUri="file:///home/user/myproject", initializationOptions=None, capabilities=capabilities, trace="off", workspaceFolders=None, ) ``` ### Response #### Success Response (200) - **serverInfo** (object) - Information about the server. ### Response Example ```json { "serverInfo": {"name": "pylsp", "version": "..."} } ``` ``` -------------------------------- ### Initialize LSP Session with pylspclient Source: https://context7.com/yeger00/pylspclient/llms.txt Starts an LSP session by sending the mandatory 'initialize' request. 'capabilities' is required and must be called once before other LSP methods. Ensure to send the 'initialized()' notification afterward. ```python import subprocess import pylspclient server = subprocess.Popen( ["python", "-m", "pylsp"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) json_rpc = pylspclient.JsonRpcEndpoint(server.stdin, server.stdout) lsp_endpoint = pylspclient.LspEndpoint(json_rpc) client = pylspclient.LspClient(lsp_endpoint) capabilities = { "textDocument": { "completion": { "completionItem": { "snippetSupport": True, "documentationFormat": ["markdown", "plaintext"], } } } } result = client.initialize( processId=None, rootPath=None, rootUri="file:///home/user/myproject", initializationOptions=None, capabilities=capabilities, trace="off", workspaceFolders=None, ) print(result["serverInfo"]) # {"name": "pylsp", "version": "..."} client.initialized() # send the required follow-up notification # ... use the client ... client.shutdown() client.exit() server.kill() server.communicate() ``` -------------------------------- ### Get Function Signature Information with LspClient.signatureHelp Source: https://context7.com/yeger00/pylspclient/llms.txt Sends a textDocument/signatureHelp request to retrieve function signature details. Returns a SignatureHelp object with SignatureInformation entries. Useful for inline parameter hints. ```python from pylspclient.lsp_pydantic_strcuts import TextDocumentIdentifier, Position uri = "file:///home/user/myproject/main.py" position = Position(line=10, character=15) # inside a function call's argument list sig_help = client.signatureHelp(TextDocumentIdentifier(uri=uri), position) for sig in sig_help.signatures: print(f"Signature: {sig.label}") if sig.documentation: print(f" Docs: {sig.documentation}") # Signature: open(file, mode='r', buffering=-1, ...) # Docs: Open file and return a stream. ``` -------------------------------- ### Run Tests with make Source: https://github.com/yeger00/pylspclient/blob/main/README.md Execute the test suite for the project using the provided Makefile. This command ensures code quality and functionality. ```bash make test ``` -------------------------------- ### New Release Workflow with make Source: https://github.com/yeger00/pylspclient/blob/main/README.md Commands to manage new releases, including bumping the version, building the package, and publishing it. These are part of the release process. ```bash make bump make build make publish ``` -------------------------------- ### Graceful Teardown: shutdown() and exit() Source: https://context7.com/yeger00/pylspclient/llms.txt Demonstrates the correct sequence for shutting down an LspClient to ensure a clean lifecycle. Always call shutdown() before exit(). ```APIDOC ## `LspClient.shutdown` and `LspClient.exit` — Graceful teardown `shutdown()` stops the `LspEndpoint` background thread and sends the LSP `shutdown` request, asking the server to clean up. `exit()` sends the `exit` notification, which causes the server process to terminate. Always call `shutdown()` before `exit()` to ensure a clean lifecycle. ```python # Proper teardown sequence client.shutdown() # stops background thread, sends shutdown request client.exit() # sends exit notification, server process terminates server.kill() # ensure process is reaped server.communicate() ``` ``` -------------------------------- ### Run Linter with make Source: https://github.com/yeger00/pylspclient/blob/main/README.md Run the linter to check for code style and potential issues using the Makefile. This helps maintain code consistency. ```bash make lint ``` -------------------------------- ### Go to Declaration with LspClient.declaration Source: https://context7.com/yeger00/pylspclient/llms.txt Sends a textDocument/declaration request to find symbol declaration sites. Results can be Location, list[Location], or list[LocationLink]. Useful for languages distinguishing declaration from definition. ```python from pylspclient.lsp_pydantic_strcuts import TextDocumentIdentifier, Position uri = "file:///home/user/myproject/main.py" position = Position(line=3, character=10) result = client.declaration(TextDocumentIdentifier(uri=uri), position) if isinstance(result, list): for loc in result: print(f"Declared at {loc.uri}:{loc.range.start.line}") else: print(f"Declared at {result.uri}:{result.range.start.line}") ``` -------------------------------- ### List Symbols in a File with pylspclient Source: https://context7.com/yeger00/pylspclient/llms.txt Sends a 'textDocument/documentSymbol' request to list all symbols in a file. The server returns either hierarchical 'DocumentSymbol' or flat 'SymbolInformation' objects. The document must be opened first. ```python from pylspclient.lsp_pydantic_strcuts import TextDocumentIdentifier, TextDocumentItem, LanguageIdentifier uri = "file:///home/user/myproject/main.py" # Must open the document first with open("/home/user/myproject/main.py") as f: text = f.read() client.didOpen(TextDocumentItem(uri=uri, languageId=LanguageIdentifier.PYTHON, version=1, text=text)) symbols = client.documentSymbol(TextDocumentIdentifier(uri=uri)) for sym in symbols: print(f"{sym.name} [{sym.kind.name}] @ line {sym.range.start.line}") # hello [Function] @ line 0 # MyClass [Class] @ line 4 ``` -------------------------------- ### Go to Definition with pylspclient Source: https://context7.com/yeger00/pylspclient/llms.txt Sends a 'textDocument/definition' request to resolve the definition of a symbol at a specific cursor position. The response can be a 'Location', 'list[Location]', or 'list[LocationLink]'. ```python from pylspclient.lsp_pydantic_strcuts import TextDocumentIdentifier, Position uri = "file:///home/user/myproject/main.py" # cursor is on line 5, character 4 (over a function call) position = Position(line=5, character=4) definitions = client.definition(TextDocumentIdentifier(uri=uri), position) for loc in definitions: print(f"Defined in {loc.uri} at line {loc.range.start.line}") # Defined in file:///home/user/myproject/utils.py at line 12 ``` -------------------------------- ### LspEndpoint: Async Message Dispatching and Callbacks Source: https://context7.com/yeger00/pylspclient/llms.txt LspEndpoint manages message dispatching in a background thread, allowing registration of callbacks for server notifications and providing a method to call server methods with a timeout. Use this for handling asynchronous LSP communication. ```python import subprocess import pylspclient server = subprocess.Popen( ["python", "-m", "pylsp"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) json_rpc = pylspclient.JsonRpcEndpoint(server.stdin, server.stdout) # Register a callback for server-push diagnostics notifications diagnostics_log = [] def on_publish_diagnostics(params): diagnostics_log.append(params) lsp_endpoint = pylspclient.LspEndpoint( json_rpc, notify_callbacks={"textDocument/publishDiagnostics": on_publish_diagnostics}, timeout=5, # seconds to wait for a response before raising TimeoutError ) lsp_endpoint.start() # starts the background reader thread # call_method blocks until the server responds (or timeout is exceeded) result = lsp_endpoint.call_method( "initialize", processId=None, rootUri="file:///my/project", capabilities={}, ) print(result["serverInfo"]["name"]) # e.g., "pylsp" # send_notification is fire-and-forget lsp_endpoint.send_notification("initialized") lsp_endpoint.stop() server.kill() server.communicate() ``` -------------------------------- ### LspClient.definition Source: https://context7.com/yeger00/pylspclient/llms.txt Sends a 'textDocument/definition' request to resolve where a symbol at a given cursor position is defined. ```APIDOC ## `LspClient.definition` — Go to definition `definition(textDocument, position)` sends a `textDocument/definition` request and returns a `Location`, `list[Location]`, or `list[LocationLink]` depending on the server response. Used to resolve where a symbol at a given cursor position is defined. ### Parameters - **textDocument** (TextDocumentIdentifier) - Required - The document containing the symbol. - **position** (Position) - Required - The cursor position. ### Request Example ```python client.definition(TextDocumentIdentifier(uri=uri), position) ``` ### Response #### Success Response (200) - **definitions** (Location | list[Location] | list[LocationLink]) - The location(s) where the symbol is defined. ### Response Example ```python # Example output structure (actual content depends on the symbol) [ { "uri": "file:///home/user/myproject/utils.py", "range": { "start": {"line": 12, "character": 0}, "end": {"line": 15, "character": 0} } } ] ``` ``` -------------------------------- ### Request Code Completions with LspClient.completion Source: https://context7.com/yeger00/pylspclient/llms.txt Sends a textDocument/completion request for code suggestions. Returns a CompletionList or list[CompletionItem]. The CompletionContext can specify how the completion was triggered. ```python from pylspclient.lsp_pydantic_strcuts import ( TextDocumentIdentifier, Position, CompletionContext, CompletionTriggerKind ) uri = "file:///home/user/myproject/main.py" position = Position(line=2, character=8) # cursor after "os.path." context = CompletionContext(triggerKind=CompletionTriggerKind.TriggerCharacter, triggerCharacter=".") result = client.completion(TextDocumentIdentifier(uri=uri), position, context) if hasattr(result, "items"): items = result.items # CompletionList print(f"Incomplete: {result.isIncomplete}") else: items = result # list[CompletionItem] for item in items[:5]: print(f"{item.label} ({item.kind.name if item.kind else 'unknown'})") # join (Function) # exists (Function) # dirname (Function) ``` -------------------------------- ### LspClient.completion Source: https://context7.com/yeger00/pylspclient/llms.txt Requests code completions for a given text document and position. Optionally includes context on how the completion was triggered. Returns a CompletionList or a list of CompletionItem objects. ```APIDOC ## `LspClient.completion` — Request code completions `completion(textDocument, position, context)` sends a `textDocument/completion` request and returns either a `CompletionList` (when `isIncomplete` is present) or a `list[CompletionItem]`. The `CompletionContext` specifies how the completion was triggered (invoked manually or by a trigger character). ```python from pylspclient.lsp_pydantic_strcuts import ( TextDocumentIdentifier, Position, CompletionContext, CompletionTriggerKind ) uri = "file:///home/user/myproject/main.py" position = Position(line=2, character=8) # cursor after "os.path." context = CompletionContext(triggerKind=CompletionTriggerKind.TriggerCharacter, triggerCharacter=".") result = client.completion(TextDocumentIdentifier(uri=uri), position, context) if hasattr(result, "items"): items = result.items # CompletionList print(f"Incomplete: {result.isIncomplete}") else: items = result # list[CompletionItem] for item in items[:5]: print(f"{item.label} ({item.kind.name if item.kind else 'unknown'})") # join (Function) # exists (Function) # dirname (Function) ``` ``` -------------------------------- ### LspClient.signatureHelp Source: https://context7.com/yeger00/pylspclient/llms.txt Sends a textDocument/signatureHelp request to retrieve signature information for a function or method at a given position. Returns a SignatureHelp object. ```APIDOC ## `LspClient.signatureHelp` — Get function signature information `signatureHelp(textDocument, position)` sends a `textDocument/signatureHelp` request and returns a `SignatureHelp` object containing a list of `SignatureInformation` entries. Each entry describes a function's signature label, optional documentation, and parameter list. Useful for displaying inline parameter hints as a user types a function call. ```python from pylspclient.lsp_pydantic_strcuts import TextDocumentIdentifier, Position uri = "file:///home/user/myproject/main.py" position = Position(line=10, character=15) # inside a function call's argument list sig_help = client.signatureHelp(TextDocumentIdentifier(uri=uri), position) for sig in sig_help.signatures: print(f"Signature: {sig.label}") if sig.documentation: print(f" Docs: {sig.documentation}") # Signature: open(file, mode='r', buffering=-1, ...) # Docs: Open file and return a stream. ``` ``` -------------------------------- ### LspClient.didOpen Source: https://context7.com/yeger00/pylspclient/llms.txt Sends a 'textDocument/didOpen' notification, handing ownership of the document's content to the client. The server will begin tracking the document and may immediately publish diagnostics. ```APIDOC ## `LspClient.didOpen` — Notify server of an opened document `didOpen(textDocument: TextDocumentItem)` sends a `textDocument/didOpen` notification, handing ownership of the document's content to the client. The server will begin tracking the document and may immediately publish diagnostics. A matching `didChange` or `didClose` notification must be sent if the document changes or is closed. ### Parameters - **textDocument** (TextDocumentItem) - Required - The document to open. ### Request Example ```python client.didOpen( TextDocumentItem( uri=f"file://{file_path}", languageId=LanguageIdentifier.PYTHON, version=1, text=source, ) ) ``` ``` -------------------------------- ### Graceful Teardown with shutdown() and exit() Source: https://context7.com/yeger00/pylspclient/llms.txt Always call `shutdown()` before `exit()` to ensure a clean lifecycle. `shutdown()` stops the background thread and sends the LSP `shutdown` request, while `exit()` sends the `exit` notification to terminate the server process. ```python # Proper teardown sequence client.shutdown() # stops background thread, sends shutdown request client.exit() # sends exit notification, server process terminates server.kill() # ensure process is reaped server.communicate() ``` -------------------------------- ### Error Handling: ResponseError and ErrorCodes Source: https://context7.com/yeger00/pylspclient/llms.txt Illustrates how to catch and handle errors returned by the language server using ResponseError and provides access to standard JSON-RPC and LSP error codes via ErrorCodes. ```APIDOC ## `ResponseError` and `ErrorCodes` — Error handling `ResponseError(code, message, data)` is raised by `LspEndpoint.call_method` when the server returns an error response. `ErrorCodes` is an `IntEnum` covering all standard JSON-RPC and LSP error codes. Catching `ResponseError` allows fine-grained handling of server-side failures. ```python from pylspclient.lsp_errors import ResponseError, ErrorCodes from pylspclient.lsp_pydantic_strcuts import TextDocumentIdentifier, Position try: result = client.definition( TextDocumentIdentifier(uri="file:///nonexistent.py"), Position(line=0, character=0), ) except ResponseError as e: print(f"LSP error {e.code} ({ErrorCodes(e.code).name}): {e.message}") except TimeoutError: print("Server did not respond in time") # LSP error -32603 (InternalError): ... ``` ``` -------------------------------- ### LspClient.declaration Source: https://context7.com/yeger00/pylspclient/llms.txt Sends a textDocument/declaration request to find the declaration site(s) of a symbol at a given position. Results can be a Location, list[Location], or list[LocationLink]. ```APIDOC ## `LspClient.declaration` — Go to declaration `declaration(textDocument, position)` sends a `textDocument/declaration` request and returns the declaration site(s) of a symbol. Results are returned as `Location`, `list[Location]`, or `list[LocationLink]`. Particularly useful in languages that distinguish declaration from definition (e.g., C/C++ header vs. implementation). ```python from pylspclient.lsp_pydantic_strcuts import TextDocumentIdentifier, Position uri = "file:///home/user/myproject/main.py" position = Position(line=3, character=10) result = client.declaration(TextDocumentIdentifier(uri=uri), position) if isinstance(result, list): for loc in result: print(f"Declared at {loc.uri}:{loc.range.start.line}") else: print(f"Declared at {result.uri}:{result.range.start.line}") ``` ``` -------------------------------- ### Go to Type Definition with LspClient.typeDefinition Source: https://context7.com/yeger00/pylspclient/llms.txt Sends a textDocument/typeDefinition request to find where a type is defined. Returns a list of Location objects. Useful for navigating to type declarations from variable usage sites. ```python from pylspclient.lsp_pydantic_strcuts import TextDocumentIdentifier, Position uri = "file:///home/user/myproject/main.py" position = Position(line=8, character=6) # cursor on a typed variable locations = client.typeDefinition(TextDocumentIdentifier(uri=uri), position) for loc in locations: print(f"Type defined at {loc.uri}:{loc.range.start.line}") ``` -------------------------------- ### Using Pydantic Data Structures for LSP Models Source: https://context7.com/yeger00/pylspclient/llms.txt pylspclient exposes LSP data structures as Pydantic v2 `BaseModel` subclasses. These models can be constructed directly or used to validate raw dictionaries from server responses. ```python from pylspclient.lsp_pydantic_strcuts import ( Position, Range, Location, TextDocumentItem, LanguageIdentifier, DocumentSymbol, SymbolKind, CompletionItem, CompletionItemKind, ) # Construct a position pos = Position(line=10, character=5) # Construct a range rng = Range(start=Position(line=10, character=0), end=Position(line=10, character=20)) # Construct a document item for opening doc = TextDocumentItem( uri="file:///home/user/project/app.py", languageId=LanguageIdentifier.PYTHON, version=1, text="def main(): pass\n", ) # Validate a raw dict (e.g., from a server response) into a typed model raw = {"name": "main", "kind": 12, "range": {"start": {"line": 0, "character": 0}, "end": {"line": 0, "character": 16}}, "selectionRange": {"start": {"line": 0, "character": 4}, "end": {"line": 0, "character": 8}}} sym = DocumentSymbol.model_validate(raw) print(sym.name, sym.kind.name) # main Function ``` -------------------------------- ### LspClient.documentSymbol Source: https://context7.com/yeger00/pylspclient/llms.txt Sends a 'textDocument/documentSymbol' request and returns a list of DocumentSymbol or SymbolInformation objects, useful for building outlines or navigation trees. ```APIDOC ## `LspClient.documentSymbol` — List all symbols in a file `documentSymbol(textDocument: TextDocumentIdentifier)` sends a `textDocument/documentSymbol` request and returns either a list of `DocumentSymbol` (hierarchical) or `SymbolInformation` (flat) objects, automatically discriminated via Pydantic validation. Useful for building outlines, navigation trees, or code analysis tools. ### Parameters - **textDocument** (TextDocumentIdentifier) - Required - The document to get symbols from. ### Request Example ```python client.documentSymbol(TextDocumentIdentifier(uri=uri)) ``` ### Response #### Success Response (200) - **symbols** (list) - A list of DocumentSymbol or SymbolInformation objects. ### Response Example ```python # Example output structure (actual content depends on the file) [ { "name": "hello", "kind": 12, # SymbolKind.Function "range": { "start": {"line": 0, "character": 0}, "end": {"line": 3, "character": 0} } } ] ``` ``` -------------------------------- ### LspClient.rename Source: https://context7.com/yeger00/pylspclient/llms.txt Initiates a textDocument/rename request to rename a symbol across the workspace. Returns a WorkspaceEdit object detailing the necessary changes. ```APIDOC ## `LspClient.rename` — Rename a symbol across the workspace `rename(text_document, position, new_name)` sends a `textDocument/rename` request and returns a `WorkspaceEdit` containing a dictionary mapping file URIs to lists of `TextEdit` objects representing all changes required to rename the symbol. The caller is responsible for applying these edits to the actual files. ```python from pylspclient.lsp_pydantic_strcuts import TextDocumentIdentifier, Position uri = "file:///home/user/myproject/main.py" position = Position(line=0, character=4) # cursor on the name "hello" in `def hello():` workspace_edit = client.rename( text_document=TextDocumentIdentifier(uri=uri), position=position, new_name="greet", ) for file_uri, edits in workspace_edit.changes.items(): print(f"Changes in {file_uri}:") for edit in edits: print(f" Replace [{edit.range_start.line}:{edit.range_start.character}" f"-{edit.range_end.line}:{edit.range_end.character}] with '{edit.new_text}'") # Changes in file:///home/user/myproject/main.py: # Replace [0:4-0:9] with 'greet' # Changes in file:///home/user/myproject/other.py: # Replace [7:0-7:5] with 'greet' ``` ``` -------------------------------- ### JsonRpcEndpoint: Send and Receive Raw LSP Messages Source: https://context7.com/yeger00/pylspclient/llms.txt Use JsonRpcEndpoint to wrap stdio pipes for a language server, enabling manual sending of requests and receiving of raw JSON-RPC responses. This is useful for direct interaction with the transport layer. ```python import subprocess import pylspclient # Launch a language server (e.g., pylsp for Python) server = subprocess.Popen( ["python", "-m", "pylsp"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) # Create the low-level JSON-RPC endpoint json_rpc = pylspclient.JsonRpcEndpoint(server.stdin, server.stdout) # Manually send an initialize request and read the raw response json_rpc.send_request({ "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"processId": None, "rootUri": None, "capabilities": {}}, }) response = json_rpc.recv_response() # response = {"jsonrpc": "2.0", "id": 1, "result": {"capabilities": {...}, "serverInfo": {...}}} print(response["result"]["serverInfo"]) server.kill() server.communicate() ``` -------------------------------- ### Notify Server of Opened Document with pylspclient Source: https://context7.com/yeger00/pylspclient/llms.txt Sends a 'textDocument/didOpen' notification to the server, transferring document content ownership. The server will track the document and may publish diagnostics. A matching 'didChange' or 'didClose' must follow if the document is modified or closed. ```python from pylspclient.lsp_pydantic_strcuts import TextDocumentItem, LanguageIdentifier file_path = "/home/user/myproject/main.py" with open(file_path) as f: source = f.read() client.didOpen( TextDocumentItem( uri=f"file://{file_path}", languageId=LanguageIdentifier.PYTHON, version=1, text=source, ) ) # Server now tracks the document; diagnostics may arrive via publishDiagnostics callback ``` -------------------------------- ### Pydantic Data Structures for LSP Models Source: https://context7.com/yeger00/pylspclient/llms.txt Details the Pydantic v2 BaseModel subclasses provided by pylspclient for LSP data structures, allowing for type-safe interaction with language server responses. ```APIDOC ## Pydantic Data Structures — LSP model types pylspclient exposes all LSP data structures as Pydantic v2 `BaseModel` subclasses in `lsp_pydantic_strcuts`. Key models include `TextDocumentItem`, `TextDocumentIdentifier`, `Position`, `Range`, `Location`, `DocumentSymbol`, `SymbolInformation`, `CompletionItem`, `CompletionList`, `SignatureHelp`, and `WorkspaceEdit`. All are importable directly from `pylspclient.lsp_pydantic_strcuts`. ```python from pylspclient.lsp_pydantic_strcuts import ( Position, Range, Location, TextDocumentItem, LanguageIdentifier, DocumentSymbol, SymbolKind, CompletionItem, CompletionItemKind, ) # Construct a position pos = Position(line=10, character=5) # Construct a range rng = Range(start=Position(line=10, character=0), end=Position(line=10, character=20)) # Construct a document item for opening doc = TextDocumentItem( uri="file:///home/user/project/app.py", languageId=LanguageIdentifier.PYTHON, version=1, text="def main(): pass\n", ) # Validate a raw dict (e.g., from a server response) into a typed model raw = {"name": "main", "kind": 12, "range": {"start": {"line": 0, "character": 0}, "end": {"line": 0, "character": 16}}, "selectionRange": {"start": {"line": 0, "character": 4}, "end": {"line": 0, "character": 8}}} sym = DocumentSymbol.model_validate(raw) print(sym.name, sym.kind.name) # main Function ``` ``` -------------------------------- ### Notify Server of Document Changes with pylspclient Source: https://context7.com/yeger00/pylspclient/llms.txt Sends a 'textDocument/didChange' notification with a list of change events to keep the server's document view synchronized with the client's. ```python from pylspclient.lsp_pydantic_strcuts import TextDocumentItem, LanguageIdentifier new_source = "def hello():\n print('world')\n" client.didChange( textDocument=TextDocumentItem( uri="file:///home/user/myproject/main.py", languageId=LanguageIdentifier.PYTHON, version=2, text=new_source, ), contentChanges=[{"text": new_source}], ) ``` -------------------------------- ### LspClient.didChange Source: https://context7.com/yeger00/pylspclient/llms.txt Sends a 'textDocument/didChange' notification with a list of change events to keep the server's view of the document in sync with the client's. ```APIDOC ## `LspClient.didChange` — Notify server of document changes `didChange(textDocument, contentChanges)` sends a `textDocument/didChange` notification with a list of change events. This keeps the server's view of the document in sync with the client's. ### Parameters - **textDocument** (TextDocumentItem) - Required - The document that changed. - **contentChanges** (list) - Required - A list of changes made to the document. ### Request Example ```python client.didChange( textDocument=TextDocumentItem( uri="file:///home/user/myproject/main.py", languageId=LanguageIdentifier.PYTHON, version=2, text=new_source, ), contentChanges=[{"text": new_source}], ) ``` ``` -------------------------------- ### Rename Symbol Across Workspace with LspClient.rename Source: https://context7.com/yeger00/pylspclient/llms.txt Sends a textDocument/rename request to rename a symbol. Returns a WorkspaceEdit object with changes to apply to files. The caller must apply these edits. ```python from pylspclient.lsp_pydantic_strcuts import TextDocumentIdentifier, Position uri = "file:///home/user/myproject/main.py" position = Position(line=0, character=4) # cursor on the name "hello" in `def hello():` workspace_edit = client.rename( text_document=TextDocumentIdentifier(uri=uri), position=position, new_name="greet", ) for file_uri, edits in workspace_edit.changes.items(): print(f"Changes in {file_uri}:") for edit in edits: print(f" Replace [{edit.range_start.line}:{edit.range_start.character}" f"-{edit.range_end.line}:{edit.range_end.character}] with '{edit.new_text}'") # Changes in file:///home/user/myproject/main.py: # Replace [0:4-0:9] with 'greet' # Changes in file:///home/user/myproject/other.py: # Replace [7:0-7:5] with 'greet' ``` -------------------------------- ### LspClient.typeDefinition Source: https://context7.com/yeger00/pylspclient/llms.txt Sends a textDocument/typeDefinition request to retrieve the definition location(s) of the type of a symbol at a specific position. Returns a list of Location objects. ```APIDOC ## `LspClient.typeDefinition` — Go to type definition `typeDefinition(textDocument, position)` sends a `textDocument/typeDefinition` request and returns a list of `Location` objects pointing to where the type of the symbol at the given position is defined. Useful for navigating to class or type declarations from variable usage sites. ```python from pylspclient.lsp_pydantic_strcuts import TextDocumentIdentifier, Position uri = "file:///home/user/myproject/main.py" position = Position(line=8, character=6) # cursor on a typed variable locations = client.typeDefinition(TextDocumentIdentifier(uri=uri), position) for loc in locations: print(f"Type defined at {loc.uri}:{loc.range.start.line}") ``` ``` -------------------------------- ### Handling LSP ResponseError and ErrorCodes Source: https://context7.com/yeger00/pylspclient/llms.txt Catch `ResponseError` raised by `LspEndpoint.call_method` when the server returns an error. `ErrorCodes` provides standard JSON-RPC and LSP error codes for fine-grained error handling. ```python from pylspclient.lsp_errors import ResponseError, ErrorCodes from pylspclient.lsp_pydantic_strcuts import TextDocumentIdentifier, Position try: result = client.definition( TextDocumentIdentifier(uri="file:///nonexistent.py"), Position(line=0, character=0), ) except ResponseError as e: print(f"LSP error {e.code} ({ErrorCodes(e.code).name}): {e.message}") except TimeoutError: print("Server did not respond in time") # LSP error -32603 (InternalError): ... ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.