API Reference#

Warning

While we will try not to break the API outlined below, until the language server reaches v1.0 we do not offer any stability guarantees.

Language Servers#

esbonio.lsp.create_language_server(server_cls, modules, *args, **kwargs)[source]#

Create a new language server instance.

Parameters:
  • server_cls (Type[RstLanguageServer]) – The class definition to create the server from.

  • modules (Iterable[str]) – The list of modules that should be loaded.

  • args – Any additional arguments that should be passed to the language server’s constructor.

  • kwargs – Any additional arguments that should be passed to the language server’s constructor.

RstLanguageServer#

class esbonio.lsp.rst.RstLanguageServer(logger=None, *args, **kwargs)[source]#

Bases: LanguageServer

A generic reStructuredText language server.

add_diagnostics(source, uri, diagnostic)[source]#

Add a diagnostic to the given source and uri.

Parameters:
  • source (str) – The source the diagnostics are from

  • uri – The uri the diagnostics are associated with

  • diagnostic (Diagnostic) – The diagnostic to add

add_feature(feature)[source]#

Register a language feature with the server.

Parameters:

feature (LanguageFeature) – The language feature

clear_diagnostics(source, uri=None)[source]#

Clear diagnostics from the given source.

Parameters:
  • source (str) – The source from which to clear diagnostics.

  • uri (str | None) – If given, clear diagnostics from within just this uri. Otherwise, all diagnostics from the given source are cleared.

get_default_role()[source]#

Return the default role for the project.

get_directive_options(name)[source]#

Return the options specification for the given directive.

Deprecated since version 0.14.2: This will be removed in v1.0

get_directives()[source]#

Return a dictionary of the known directives

Deprecated since version 0.14.2: This will be removed in v1.0. Use the get_directives() method instead.

get_feature(key: str) LanguageFeature | None[source]#
get_feature(key: Type[LF]) LF | None

Returns the requested language feature if it exists, otherwise it returns None.

Parameters:

key (str | Type[LanguageFeature]) –

A feature can be referenced either by its class definition (preferred) or by a string representing the language feature’s dotted name e.g. a.b.c.ClassName.

Deprecated since version 0.14.0: Passing a string key to this method is deprecated and will become an error in v1.0.

get_initial_doctree(uri)[source]#

Return the initial doctree corresponding to the specified document.

An “initial” doctree can be thought of as the abstract syntax tree of a reStructuredText document. This method disables all role and directives from being executed, instead they are replaced with nodes that simply represent that they exist.

Parameters:

uri (str) – Returns the doctree that corresponds with the given uri.

get_location_type(document, position)[source]#

Given a document and a position, return the type of location.

Returns one of the following values:

  • rst: Indicates that the position is within an reStructuredText document

  • py: Indicates that the position is within code in a Python file

  • docstring: Indicates that the position is within a docstring in a Python file.

If the location type cannot be determined, this function will fall back to rst.

Parameters:
  • doc – The document associated with the given position

  • position (Position) – The position to determine the type of

get_roles()[source]#

Return a dictionary of known roles.

Deprecated since version 0.15.0: This will be removed in v1.0. Use the get_roles() method instead.

line_at_position(doc, position)[source]#

Return the contents of the line corresponding to the given position.

Parameters:
  • doc (TextDocument) – The document associated with the given position

  • position (Position) – The position representing the line to retrieve

line_to_position(doc, position)[source]#

Return the contents of the line up until the given position.

Parameters:
  • doc (TextDocument) – The document associated with the given position.

  • position (Position) – The position representing the line to retrieve.

load_extension(name, setup)[source]#

Load the given setup function as an extension.

If an extension with the given name already exists, the given setup function will be ignored.

The setup function can declare dependencies in the form of type annotations.

from esbonio.lsp.roles import Roles
from esbonio.lsp.sphinx import SphinxLanguageServer

def esbonio_setup(rst: SphinxLanguageServer, roles: Roles):
    ...

In this example the setup function is requesting instances of the SphinxLanguageServer and the Roles language feature.

Parameters:
  • name (str) – The name to give the extension

  • setup (Callable) – The setup function to call

preview(options)[source]#

Generate a preview of the documentation.

set_diagnostics(source, uri, diagnostics)[source]#

Set the diagnostics for the given source and uri.

Parameters:
  • source (str) – The source the diagnostics are from

  • uri (str) – The uri the diagnostics are associated with

  • diagnostics (List[Diagnostic]) – The diagnostics themselves

sync_diagnostics()[source]#

Update the client with the currently stored diagnostics.

text_to_position(doc, position)[source]#

Return the contents of the document up until the given position.

Parameters:
  • doc (TextDocument) – The document associated with the given position

  • position (Position) – The position representing the point at which to stop gathering text.

property configuration: Dict[str, Any]#

Return the server’s actual configuration.

converter#

The cattrs converter instance we should use.

logger#

The base logger that should be used for all language sever log entries.

user_config: InitializationOptions#

The user’s configuration.

class esbonio.lsp.rst.InitializationOptions(server=_Nothing.NOTHING)[source]#

The initialization options we can expect to receive from a client.

server: ServerConfig#

The esbonio.server.* namespace of options.

class esbonio.lsp.rst.config.ServerConfig(completion=_Nothing.NOTHING, enable_scroll_sync=False, enable_live_preview=False, log_filter=_Nothing.NOTHING, log_level='error', show_deprecation_warnings=False)[source]#

Configuration options for the server.

completion: ServerCompletionConfig#

Configuration values that affect completion

enable_live_preview: bool#

Set it to True if you want to build Sphinx app on change event

enable_scroll_sync: bool#

Enable custom transformation to add classes with line numbers

log_filter: List[str]#

A list of logger names to restrict output to.

log_level: str#

The logging level of server messages to display.

show_deprecation_warnings: bool#

Developer flag to enable deprecation warnings.

class esbonio.lsp.rst.config.ServerCompletionConfig(preferred_insert_behavior='replace')[source]#

Configuration options for the server that control completion behavior.

preferred_insert_behavior: Literal['insert', 'replace']#

This option indicates if the user prefers we use insertText or textEdit when rendering CompletionItems.

SphinxLanguageServer#

class esbonio.lsp.sphinx.SphinxLanguageServer(*args, **kwargs)[source]#

Bases: RstLanguageServer

A language server dedicated to working with Sphinx projects.

build(force_all=False, filenames=None)[source]#

Trigger sphinx build. Force complete rebuild with flag or build only selected files in the list.

cb_build_finished(app, exception)[source]#

Callback handling build-finished event.

cb_env_before_read_docs(app, env, docnames)[source]#

Callback handling env-before-read-docs event.

cb_source_read(app, docname, source)[source]#

Callback handling source_read event.

create_sphinx_app(options)[source]#

Create a Sphinx application instance with the given config.

get_default_role()[source]#

Return the project’s default role

get_directive_options(name)[source]#

Return the options specification for the given directive.

Deprecated since version 0.14.2: This will be removed in v1.0

get_doctree(*, docname=None, uri=None)[source]#

Return the initial doctree corresponding to the specified document.

The docname of a document is its path relative to the project’s srcdir minus the extension e.g. the docname of the file docs/lsp/features.rst would be lsp/features.

Parameters:
  • docname (str | None) – Returns the doctree that corresponds with the given docname

  • uri (str | None) – Returns the doctree that corresponds with the given uri.

get_domain(name)[source]#

Return the domain with the given name.

Deprecated since version 0.15.0: This will be removed in v1.0

If a domain with the given name cannot be found, this method will return None.

Parameters:

name (str) – The name of the domain

get_domains()[source]#

Get all the domains registered with an applications.

Deprecated since version 0.15.0: This will be removed in v1.0

Returns a generator that iterates through all of an application’s domains, taking into account configuration variables such as primary_domain. Yielded values will be a tuple of the form (prefix, domain) where

  • prefix is the namespace that should be used when referencing items in the domain

  • domain is the domain object itself.

get_intersphinx_projects()[source]#

Return the list of configured intersphinx project names.

Deprecated since version 0.15.0: This will be removed in v.1.0

get_intersphinx_targets(project, name, domain='')[source]#

Return the intersphinx objects targeted by the given role.

Deprecated since version 0.15.0: This will be removed in v1.0

Parameters:
  • project (str) – The project to return targets from

  • name (str) – The name of the role

  • domain (str) – The domain the role is a part of, if applicable.

get_role_target_types(name, domain_name='')[source]#

Return a map indicating which object types a role is capable of linking with.

Deprecated since version 0.15.0: This will be removed in v1.0

For example

{
    "func": ["function"],
    "class": ["class", "exception"]
}
get_role_targets(name, domain='')[source]#

Return a list of objects targeted by the given role.

Parameters:
  • name (str) – The name of the role

  • domain (str) – The domain the role is a part of, if applicable.

has_intersphinx_targets(project, name, domain='')[source]#

Return True if the given intersphinx project has targets targeted by the given role.

Deprecated since version 0.15.0: This will be removed in v1.0

Parameters:
  • project (str) – The project to check

  • name (str) – The name of the role

  • domain (str) – The domain the role is a part of, if applicable.

preview(options)[source]#

Generate a preview of the documentation.

app: Sphinx | None#

The Sphinx application instance.

property configuration: Dict[str, Any]#

Return the server’s actual configuration.

file_list_pending_build_version_updates: List[Tuple[str, int]]#

List of all the files that need an updated last_build_version

preview_port: int | None#

The port the preview server is running on.

preview_process: Process | None#

The process hosting the preview server.

sphinx_args: Dict[str, Any]#

The current Sphinx configuration will all variables expanded.

sphinx_log: SphinxLogHandler | None#

Logging handler for sphinx messages.

class esbonio.lsp.sphinx.InitializationOptions(sphinx=_Nothing.NOTHING, server=_Nothing.NOTHING)[source]#

The initialization options we can expect to receive from a client.

server: SphinxServerConfig#

The esbonio.server.* namespace of options.

sphinx: SphinxConfig#

The esbonio.sphinx.* namespace of options.

class esbonio.lsp.sphinx.SphinxServerConfig(completion=_Nothing.NOTHING, enable_scroll_sync=False, enable_live_preview=False, log_filter=_Nothing.NOTHING, log_level='error', show_deprecation_warnings=False, hide_sphinx_output=False)[source]#

Deprecated since version 0.12.0: This will be removed in v1.0. Use sphinx.quiet (boolean) and sphinx.silent (boolean) options instead.

hide_sphinx_output: bool#

A flag to indicate if Sphinx build output should be omitted from the log.

class esbonio.lsp.sphinx.SphinxConfig(build_dir=None, builder_name='html', conf_dir=None, config_overrides=_Nothing.NOTHING, doctree_dir=None, force_full_build=False, keep_going=False, make_mode=True, num_jobs=1, quiet=False, silent=False, src_dir=None, tags=_Nothing.NOTHING, verbosity=0, version=None, warning_is_error=False)[source]#

Configuration values to pass to the Sphinx application instance.

classmethod from_arguments(*, cli_args=None, sphinx_args=None)[source]#

Return the SphinxConfig instance that’s equivalent to the given arguments.

Note

Only cli_args or sphinx_args may be given.

Warning

This method is unable to determine the value of the SphinxConfig.make_mode setting when passing sphinx_args

Parameters:
  • cli_args (List[str] | None) – The cli arguments you would normally pass to sphinx-build

  • sphinx_args (Dict[str, Any] | None) – The arguments you would use to create a Sphinx application instance.

resolve_build_dir(root_uri, actual_conf_dir)[source]#

Get the build dir to use based on the user’s config.

If nothing is specified in the given config, this will choose a location within the user’s cache dir (as determined by platformdirs <https://pypi.org/project/platformdirs>). The directory name will be a hash derived from the given conf_dir for the project.

Alternatively the user (or least language client) can override this by setting either an absolute path, or a path based on the following “variables”.

  • ${workspaceRoot} which expands to the workspace root as provided by the language client.

  • ${workspaceFolder} alias for ${workspaceRoot}, placeholder ready for multi-root support.

  • ${confDir} which expands to the configured config dir.

Parameters:
  • root_uri (str) – The workspace root uri

  • actual_conf_dir (str) – The fully resolved conf dir for the project

resolve_conf_dir(root_uri)[source]#

Get the conf dir to use based on the user’s config.

If conf_dir is not set, this method will attempt to find it by searching within the root_uri for a conf.py file. If multiple files are found, the first one found will be chosen.

If conf_dir is set the following “variables” are handled by this method

  • ${workspaceRoot} which expands to the workspace root as provided by the language client.

  • ${workspaceFolder} alias for ${workspaceRoot}, placeholder ready for multi-root support.

Parameters:

root_uri (str) – The workspace root uri

resolve_doctree_dir(root_uri, actual_conf_dir, actual_build_dir)[source]#

Get the directory to use for doctrees based on the user’s config.

If doctree_dir is not set, this method will follow what sphinx-build does.

  • If make_mode is true, this will be set to ${buildDir}/doctrees

  • If make_mode is false, this will be set to ${buildDir}/.doctrees

Otherwise, if doctree_dir is set the following “variables” are handled by this method.

  • ${workspaceRoot} which expands to the workspace root as provided by the language client.

  • ${workspaceFolder} alias for ${workspaceRoot}, placeholder ready for multi-root support.

  • ${confDir} which expands to the configured config dir.

  • ${buildDir} which expands to the configured build dir.

Parameters:
  • root_uri (str) – The workspace root uri

  • actual_conf_dir (str) – The fully resolved conf dir for the project

  • actual_build_dir (str) – The fully resolved build dir for the project.

resolve_src_dir(root_uri, actual_conf_dir)[source]#

Get the src dir to use based on the user’s config.

By default the src dir will be the same as the conf dir, but this can be overriden by setting the src_dir field.

There are a number of “variables” that can be included in the path, currently we support

  • ${workspaceRoot} which expands to the workspace root as provided by the language client.

  • ${workspaceFolder} alias for ${workspaceRoot}, placeholder ready for multi-root support.

  • ${confDir} which expands to the configured config dir.

Parameters:
  • root_uri (str) – The workspace root uri

  • actual_conf_dir (str) – The fully resolved conf dir for the project

to_application_args()[source]#

Convert this into the equivalent Sphinx application arguments.

to_cli_args()[source]#

Convert this into the equivalent sphinx-build cli arguments.

build_dir: str | None#

The directory to write build outputs into.

builder_name: str#

The currently used builder name.

conf_dir: str | None#

The directory containing the project’s conf.py.

config_overrides: Dict[str, Any]#

Any overrides to configuration values.

doctree_dir: str | None#

The directory to write doctrees into.

force_full_build: bool#

Force a full build on startup.

keep_going: bool#

Continue building when errors (from warnings) are encountered.

make_mode: bool#

Flag indicating if the server should align to “make mode” behavior.

num_jobs: Literal['auto'] | int#

The number of jobs to use for parallel builds.

property parallel: int#

The parsed value of the num_jobs field.

quiet: bool#

Hide standard Sphinx output messages

silent: bool#

Hide all Sphinx output.

src_dir: str | None#

The directory containing the project’s source.

tags: List[str]#

Tags to enable during a build.

verbosity: int#

The verbosity of Sphinx’s output.

version: str | None#

Sphinx’s version number.

warning_is_error: bool#

Treat any warning as an error

class esbonio.lsp.sphinx.MissingConfigError[source]#

Indicates that we couldn’t locate the project’s ‘conf.py’

Language Features#

class esbonio.lsp.LanguageFeature(rst)[source]#

Base class for language features.

code_action(params)[source]#

Called when code actions should be computed.

complete(context)[source]#

Called if any of the given completion_triggers match the current line.

This method should return a list of CompletionItem objects.

Parameters:

context (CompletionContext) – The context of the completion request

completion_resolve(item)[source]#

Called with a completion item the user has selected in the UI, allowing for additional details to be provided e.g. documentation.

Parameters:

item (CompletionItem) – The completion item to provide additional details for.

definition(context)[source]#

Called if any of the given definition_triggers match the current line.

This method should return a list of Location objects.

Parameters:

context (DefinitionContext) – The context of the definition request.

delete_files(params)[source]#

Called each time files are deleted.

Called whenever a textDocument/documentLink request is received.

hover(context)[source]#

Called when request textDocument/hover is sent.

This method shall return the contents value of textDocument/hover response.

implementation(context)[source]#

Called if any of the given implementation_triggers match the current line.

This method should return a list of Location objects.

Parameters:

context (ImplementationContext) – The context of the implementation request.

initialize(options)[source]#

Called once when the server is first initialized.

initialized(params)[source]#

Called once upon receipt of the initialized notification from the client.

on_shutdown(*args)[source]#

Called as the server is shutting down.

save(params)[source]#

Called each time a document is saved.

completion_triggers: List[Pattern] = []#

A list of regular expressions used to determine if the :meth`~esbonio.lsp.rst.LanguageFeature.complete` method should be called on the current line.

definition_triggers: List[Pattern] = []#

A list of regular expressions used to determine if the definition() method should be called.

implementation_triggers: List[Pattern] = []#

A list of regular expressions used to determine if the implementation() method should be called.

class esbonio.lsp.CompletionContext(*, doc, location, match, position, config, capabilities)[source]#

Captures the context within which a completion request has been made.

property commit_characters_support: bool#

Indicates if the client supports commit characters.

config: ServerCompletionConfig#

User supplied configuration options.

property deprecated_support: bool#

Indicates if the client supports the deprecated field on a CompletionItem.

doc: TextDocument#

The document within which the completion request was made.

property documentation_formats: List[MarkupKind]#

The list of documentation formats supported by the client.

property insert_replace_support: bool#

Indicates if the client supports InsertReplaceEdit.

location: str#

The location type where the request was made. See get_location_type() for details.

match: Match#

The match object describing the site of the completion request.

position: Position#

The position at which the completion request was made.

property preselect_support: bool#

Indicates if the client supports the preselect field on a CompletionItem.

property snippet_support: bool#

Indicates if the client supports snippets

property supported_tags: List[CompletionItemTag]#

The list of CompletionItemTags supported by the client.

class esbonio.lsp.DefinitionContext(*, doc, location, match, position)[source]#

A class that captures the context within which a definition request has been made.

doc#

The document within which the definition request was made.

location#

The location type where the request was made. See get_location_type() for details.

match#

The match object describing the site of the definition request.

position#

The position at which the definition request was made.

class esbonio.lsp.DocumentLinkContext(*, doc, capabilities)[source]#

Captures the context within which a document link request has been made.

doc#

The document within which the document link request was made.

property tooltip_support: bool#

Indicates if the client supports tooltips.

Testing#

Utility functions to help with testing Language Server features.

async esbonio.lsp.testing.completion_request(client, test_uri, text, character=None)[source]#

Make a completion request to a language server.

Intended for use within test cases, this function simulates the opening of a document, inserting some text, triggering a completion request and closing it again.

The file referenced by test_uri does not have to exist.

The text to be inserted is specified through the text parameter. By default it’s assumed that the text parameter consists of a single line of text, in fact this function will error if that is not the case.

If your request requires additional context (such as directive option completions) it can be included but it must be delimited with a \f character. For example, to represent the following scenario:

.. image:: filename.png
   :align: center
   :
    ^

where ^ represents the position from which we trigger the completion request. We would set text to the following .. image:: filename.png\n   :align: center\n\f   :

Parameters:
  • test – The client used to make the request.

  • test_uri (str) – The uri the completion request should be made within.

  • text (str) – The text that provides the context for the completion request.

  • character (int | None) – The character index at which to make the completion request from. If None, it will default to the end of the inserted text.

esbonio.lsp.testing.directive_argument_patterns(name, partial='')[source]#

Return a number of example directive argument patterns.

These correspond to test cases where directive argument suggestions should be generated.

Parameters:
  • name (str) – The name of the directive to generate suggestions for.

  • partial (str) – The partial argument that the user has already entered.

async esbonio.lsp.testing.hover_request(client, test_uri, text, line, character)[source]#

Make a hover request to a language server.

Intended for use within test cases, this function simulates the opening of a document containing some text, triggering a hover request and closing it again.

The file referenced by test_uri does not have to exist.

Parameters:
  • test – The client used to make the request.

  • test_uri (str) – The uri the completion request should be made within.

  • text (str) – The text that provides the context for the hover request.

  • line (int) – The line number to make the hover request from

  • character (int) – The column number to make the hover request from

esbonio.lsp.testing.intersphinx_target_patterns(name, project)[source]#

Return a number of example intersphinx target patterns.

These correspond to cases where target completions may be generated

Parameters:
  • name (str) – The name of the role to generate examples for

  • project (str) – The name of the project to generate examples for

esbonio.lsp.testing.make_completion_context(pattern, text, *, character=-1, prefer_insert=False)[source]#

Helper for making test completion context instances.

Parameters:
  • pattern (Pattern) – The regular expression pattern that corresponds to the completion request.

  • text (str) – The text that “triggered” the completion request

  • character (int) – The character column at which the request is being made. If -1 (the default), it will be assumed that the request is being made at the end of text.

  • prefer_insert (bool) – Flag to indicate if the preferred_insert_behavior option should be set to insert

esbonio.lsp.testing.make_esbonio_client(*args, **kwargs)[source]#

Construct a pytest-lsp client that is aware of esbonio specific messages

esbonio.lsp.testing.range_from_str(spec)[source]#

Create a range from the given string a:b-x:y

esbonio.lsp.testing.role_patterns(partial='')[source]#

Return a number of example role patterns.

These correspond to when role suggestions should be generated.

Parameters:

partial (str) – The partial role name that the user has already entered

esbonio.lsp.testing.role_target_patterns(name, partial='', include_modifiers=True)[source]#

Return a number of example role target patterns.

These correspond to test cases where role target suggestions should be generated.

Parameters:
  • name (str) – The name of the role to generate suggestions for.

  • partial (str) – The partial target that the user as already entered.

  • include_modifiers (bool) – A flag to indicate if additional modifiers like ! and ~ should be included in the generated patterns.

esbonio.lsp.testing.sphinx_version(eq=None, lt=None, lte=None, gt=None, gte=None)[source]#

Helper function for determining which version of Sphinx we are testing with.

Note

Currently this function only considers the major version number.

Parameters:
  • eq (int | None) – When set, this function returns True if Sphinx’s version is exactly what’s given.

  • gt (int | None) – When set, this function returns True if Sphinx’s version is strictly greater than what’s given

  • gte (int | None) – When set, this function returns True if Sphinx’s version is greater than or equal to what’s given

  • lt (int | None) – When set, this function returns True if Sphinx’s version is strictly less than what’s given

  • lte (int | None) – When set, this function returns True if Sphinx’s version is less than or equal to what’s given