Repository navigation
LSP Helpers
TurboFrame speaks the Language Server Protocol in three layers. Use the one you need:
| Layer | Module | Needs | For |
|---|---|---|---|
| Helpers | turboframe.lsp |
nothing more | positions, snippets and hovers, for any client |
| A session | turboframe.lsp.session |
the lsp extra (pygls) |
starting a server and asking it, without any user interface |
| In the editor |
turboframe.ui.lsp (LspMixin) |
the lsp extra |
completion, signatures, hovers, definitions, references and problems in your editors: see The Editor |
pip install "turboframe[lsp] @ git+https://github.com/divengine/turboframe@v0.3.0"turboframe.lsp has what an editor needs to speak with a language server, without any server or protocol library.
from turboframe import lsp
line, column = lsp.to_position(text, offset) # character offset -> (line, UTF-16 column)
offset = lsp.to_offset(text, line, column) # and back
inserted = lsp.from_snippet("f(${1:a}, ${2:b})$0", "|") # 'f(a, b)|': the snippet as text, | at $0
hover = lsp.clean_hover(lsp.plain_markup(contents)) # a hover's Markdown as plain textThe protocol counts columns in UTF-16 code units; Python counts characters. An emoji is one character and two units. line_starts(text) gives the offsets of each line; pass it as starts= to to_position and to_offset for many conversions on the same text.
API: turboframe.lsp.
turboframe.lsp.session speaks to a language server on pygls's client. Describe your servers, find one, and subclass LspSession to name your application:
from turboframe.lsp.session import LspSession, ServerSpec, diagnostics_in, find_command
PYRIGHT = ServerSpec("basedpyright", ("basedpyright-langserver", "--stdio"), language="python",
section="basedpyright", project_bins=(".venv/bin/basedpyright-langserver",))
class Session(LspSession):
CLIENT_NAME = "myapp" # what the server is told (with CLIENT_VERSION)
APP_NAME = "myapp" # its temporary directories: ~/.cache/myapp/tmp (%LOCALAPPDATA%\myapp\tmp on Windows)
def settings(self) -> dict: # what the server asks for (workspace/configuration)
return {"basedpyright": {"analysis": {"typeCheckingMode": "standard"}}}
command = find_command(PYRIGHT, root) # the user's, the project's, then the PATH's
session = Session(PYRIGHT, command, root, on_diagnostics=show)
if not await session.start():
notify(session.failed) # "basedpyright did not answer: <its last stderr line>"
session.open(path, text) # then change(), save(), close(), with the whole text
items, incomplete = await session.complete(path, offset) # raises LspTimeout, LspRequestFailed
hover = await session.hover(path, offset)
places = await session.definition(path, offset) # Locations, columns in UTF-16: to_offset() them
uses = await session.references(path, offset) # None when the server did not answer in time
await session.stop()ServerSpec(name, command, language="", section="", url="", project_bins=(), init_options={}) describes a server:
| Field | |
|---|---|
name |
how you and the user call it |
command |
the program and its arguments; the program is looked for |
language |
your name for the language it serves; LspMixin matches it with the editor's language ("python") |
section |
its own settings' section, for workspace/configuration
|
url |
where to get it, to tell a user who does not have it |
project_bins |
where a project may carry it, relative to its root; each is an exact file, so name Windows' too (.venv/Scripts/basedpyright-langserver.exe) |
init_options |
its initializationOptions
|
find_command(server, root, override=None, *, folders=()) is the command line to start: override (the user's, from your settings), else a project_bins copy under root, else one in folders (an environment's bin), else the PATH's. None when there is none.
LspSession(server, command, root, on_diagnostics=None, on_message=None, on_progress=None):
| Member | |
|---|---|
await start(timeout=60.0) |
start and initialize it; False (with the reason in failed) when it does not |
running |
it started and has not stopped |
await stop() |
shut it down; its process group, its children and its temporary directory go |
open(path, text, language=""), change(path, text), save(path), close(path)
|
keep it informed of a document, the whole text each time |
await complete(path, offset, trigger=None, timeout=10.0) |
(items, incomplete); ([], False) is the server's empty answer, never a missing one: no answer raises LspTimeout or LspRequestFailed (since v0.3.0) |
await completion(path, offset, trigger=None, timeout=10.0) |
(items, incomplete), with no answer as ([], False) too, as in v0.2 |
await request(method, params, timeout) |
any request's answer; raises LspTimeout or LspRequestFailed; out of time or cancelled, the server is told to drop it (since v0.3.0) |
await resolve(item, timeout=5.0) |
a completion item with its documentation |
await signature(path, offset, timeout=5.0) |
the call's SignatureHelp, or None |
await hover(path, offset, timeout=10.0) |
the Hover, or None |
await definition(path, offset, timeout=15.0) |
Locations |
await references(path, offset, timeout=60.0) |
Locations, or None when it did not answer in time |
trigger_characters, signature_characters
|
what the server says opens completion and the signature |
A slow server and a server with nothing to offer used to look the same. Now:
-
LspNoAnsweris the base of the two ways a request gets no answer to use:LspTimeout(the server did not answer in time) andLspRequestFailed(it answered with an error, or the request could not be sent). - A request that runs out of time, or whose awaiting task is cancelled (a newer one superseded it), is cancelled in
the server too, with
$/cancelRequest. pygls does not do it by itself, so a slow server would otherwise still compute every request nobody waits for. -
complete()raises;completion()keeps v0.2's answer,([], False), for code that does not care.
from turboframe.lsp.session import LspRequestFailed, LspTimeout
try:
items, incomplete = await session.complete(path, offset, timeout=10.0)
except LspTimeout:
notify(f"{session.server.name} did not answer in time")
except LspRequestFailed as exc:
notify(f"{session.server.name} could not complete: {exc}")The hooks of a subclass:
| Class attribute or method | Default |
|---|---|
CLIENT_NAME, CLIENT_VERSION
|
"turboframe" and TurboFrame's version: what the server is told |
APP_NAME |
"turboframe": the servers' temporary directories are <cache>/<APP_NAME>/tmp (temp_root(app)), the cache being $XDG_CACHE_HOME when set, else %LOCALAPPDATA% on Windows (since v0.2.1) and ~/.cache elsewhere |
settings() |
{}: the settings the server asks for, by section; section_of(settings, "python.analysis") gives each part asked |
prepare(temp) |
nothing: runs before the server starts, with its temporary directory, to put files it should find there |
- Offsets are the editor's character offsets; the session converts them to the protocol's positions.
- Diagnostics come to
on_diagnostics(path, items);diagnostics_in(text, items, source, *, keep=None)turns them intoServerDiagnostic(start, end, severity, message, line, column), text ranges of the errors and warnings (not hints).keep(text, items)drops what your language's idioms make a server misread. - The server never prompts: its questions are answered as dismissed. Its own messages (errors, warnings) go to
on_message(text), its progress toon_progress(token, title, percentage)(titleNone when the work ends). The callbacks run on the event loop. - It ends with your application. It runs in a process group of its own, tracked by
turboframe.process(see Processes); astop()while it is starting, or a cancelledstart(), ends it too, its children included. Each server has a temporary directory of its own (TMPDIR,TEMP,TMP), removed when it stops; those of applications no longer running are removed when the next server starts.
API: turboframe.lsp.session.
LspMixin drives sessions for your editors: it starts the server a file needs, keeps it informed as you type, and answers the editor's completion, signatures and hovers. Its settings (LSP_SERVERS, lsp_store, lsp_session_class = Session) and hooks are in The Editor; the completion list and the signature box it fills are in Completion.
API: turboframe.ui.lsp.
TurboFrame · part of Divengine · GPL-3.0-or-later · report an issue
Tutorial
Examples
The desktop
- The Desktop
- Application Mixins
- Windows and Lists
- Dialogs
- Histories
- Progress
- Themes and Colors
- Glyphs
- Settings and Recent Files
- Command Palette
Editing
Tasks
Languages
Running
Reference
Links