Utilities

Sphinx provides utility classes and functions to develop extensions.

Base classes for components

These base classes are useful to allow your extensions to obtain Sphinx components (e.g. Config, BuildEnvironment and so on) easily.

Note

The subclasses of them might not work with bare docutils because they are strongly coupled with Sphinx.

class sphinx.transforms.SphinxTransform(document, startnode=None)[source]

A base class of Transforms.

Compared with docutils.transforms.Transform, this class improves accessibility to Sphinx APIs.

property app: Sphinx

Reference to the Sphinx object.

property config: Config

Reference to the Config object.

property env: BuildEnvironment

Reference to the BuildEnvironment object.

class sphinx.transforms.post_transforms.SphinxPostTransform(document, startnode=None)[source]

A base class of post-transforms.

Post transforms are invoked to modify the document to restructure it for outputting. They resolve references, convert images, do special transformation for each output formats and so on. This class helps to implement these post transforms.

apply(**kwargs: Any) None[source]

Override to apply the transform to the document tree.

is_supported() bool[source]

Check this transform working for current builder.

run(**kwargs: Any) None[source]

Main method of post transforms.

Subclasses should override this method instead of apply().

class sphinx.util.docutils.SphinxDirective(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)[source]

A base class for Sphinx directives.

This class provides helper methods for Sphinx directives.

Added in version 1.8.

Note

The subclasses of this class might not work with docutils. This class is strongly coupled with Sphinx.

get_location() str[source]

Get current location info for logging.

Added in version 4.2.

get_source_info() tuple[str, int][source]

Get source and line number.

Added in version 3.0.

parse_content_to_nodes(allow_section_headings: bool = False) list[Node][source]

Parse the directive’s content into nodes.

Parameters:

allow_section_headings – Are titles (sections) allowed in the directive’s content? Note that this option bypasses Docutils’ usual checks on doctree structure, and misuse of this option can lead to an incoherent doctree. In Docutils, section nodes should only be children of Structural nodes, which includes document, section, and sidebar nodes.

Added in version 7.4.

parse_inline(text: str, *, lineno: int = -1) tuple[list[Node], list[system_message]][source]

Parse text as inline elements.

Parameters:
  • text – The text to parse, which should be a single line or paragraph. This cannot contain any structural elements (headings, transitions, directives, etc).

  • lineno – The line number where the interpreted text begins.

Returns:

A list of nodes (text and inline elements) and a list of system_messages.

Added in version 7.4.

parse_text_to_nodes(text: str = '', /, *, offset: int = -1, allow_section_headings: bool = False) list[Node][source]

Parse text into nodes.

Parameters:
  • text – Text, in string form. StringList is also accepted.

  • allow_section_headings – Are titles (sections) allowed in text? Note that this option bypasses Docutils’ usual checks on doctree structure, and misuse of this option can lead to an incoherent doctree. In Docutils, section nodes should only be children of Structural nodes, which includes document, section, and sidebar nodes.

  • offset – The offset of the content.

Added in version 7.4.

set_source_info(node: Node) None[source]

Set source and line number to the node.

Added in version 2.1.

property config: Config

Reference to the Config object.

Added in version 1.8.

property env: BuildEnvironment

Reference to the BuildEnvironment object.

Added in version 1.8.

class sphinx.util.docutils.SphinxRole[source]

A base class for Sphinx roles.

This class provides helper methods for Sphinx roles.

Added in version 2.0.

Note

The subclasses of this class might not work with docutils. This class is strongly coupled with Sphinx.

get_location() str[source]

Get current location info for logging.

Added in version 4.2.

property config: Config

Reference to the Config object.

Added in version 2.0.

content: Sequence[str]

A list of strings, the directive content for customisation (from the “role” directive).

property env: BuildEnvironment

Reference to the BuildEnvironment object.

Added in version 2.0.

inliner: Inliner

The docutils.parsers.rst.states.Inliner object.

lineno: int

The line number where the interpreted text begins.

name: str

The role name actually used in the document.

options: dict[str, Any]

A dictionary of directive options for customisation (from the “role” directive).

rawtext: str

A string containing the entire interpreted text input.

text: str

The interpreted text content.

class sphinx.util.docutils.ReferenceRole[source]

A base class for reference roles.

The reference roles can accept link title <target> style as a text for the role. The parsed result; link title and target will be stored to self.title and self.target.

Added in version 2.0.

disabled: bool

A boolean indicates the reference is disabled.

has_explicit_title: bool

A boolean indicates the role has explicit title or not.

target: str

The link target for the interpreted text.

title: str

The link title for the interpreted text.

class sphinx.transforms.post_transforms.images.ImageConverter(document, startnode=None)[source]

A base class for image converters.

An image converter is kind of Docutils transform module. It is used to convert image files which are not supported by a builder to the appropriate format for that builder.

For example, LaTeX builder supports PDF, PNG and JPEG as image formats. However it does not support SVG images. For such case, using image converters allows to embed these unsupported images into the document. One of the image converters; sphinx.ext.imgconverter can convert a SVG image to PNG format using Imagemagick internally.

There are three steps to make your custom image converter:

  1. Make a subclass of ImageConverter class

  2. Override conversion_rules, is_available() and convert()

  3. Register your image converter to Sphinx using Sphinx.add_post_transform()

convert(_from: str, _to: str) bool[source]

Convert an image file to the expected format.

_from is a path of the source image file, and _to is a path of the destination file.

is_available() bool[source]

Return the image converter is available or not.

available: bool | None = None

The converter is available or not. Will be filled at the first call of the build. The result is shared in the same process.

conversion_rules: list[tuple[str, str]] = []

A conversion rules the image converter supports. It is represented as a list of pair of source image format (mimetype) and destination one:

conversion_rules = [
    ('image/svg+xml', 'image/png'),
    ('image/gif', 'image/png'),
    ('application/pdf', 'image/png'),
]
default_priority = 200

Numerical priority of this transform, 0 through 999 (override).

Utility components

class sphinx.events.EventManager(app: Sphinx)[source]

Event manager for Sphinx.

add(name: str) None[source]

Register a custom Sphinx event.

connect(name: Literal['config-inited'], callback: Callable[[Sphinx, Config], None], priority: int) int[source]
connect(name: Literal['builder-inited'], callback: Callable[[Sphinx], None], priority: int) int
connect(name: Literal['env-get-outdated'], callback: Callable[[Sphinx, BuildEnvironment, Set[str], Set[str], Set[str]], Sequence[str]], priority: int) int
connect(name: Literal['env-before-read-docs'], callback: Callable[[Sphinx, BuildEnvironment, list[str]], None], priority: int) int
connect(name: Literal['env-purge-doc'], callback: Callable[[Sphinx, BuildEnvironment, str], None], priority: int) int
connect(name: Literal['source-read'], callback: Callable[[Sphinx, str, list[str]], None], priority: int) int
connect(name: Literal['include-read'], callback: Callable[[Sphinx, Path, str, list[str]], None], priority: int) int
connect(name: Literal['doctree-read'], callback: Callable[[Sphinx, nodes.document], None], priority: int) int
connect(name: Literal['env-merge-info'], callback: Callable[[Sphinx, BuildEnvironment, list[str], BuildEnvironment], None], priority: int) int
connect(name: Literal['env-updated'], callback: Callable[[Sphinx, BuildEnvironment], str], priority: int) int
connect(name: Literal['env-get-updated'], callback: Callable[[Sphinx, BuildEnvironment], Iterable[str]], priority: int) int
connect(name: Literal['env-check-consistency'], callback: Callable[[Sphinx, BuildEnvironment], None], priority: int) int
connect(name: Literal['write-started'], callback: Callable[[Sphinx, Builder], None], priority: int) int
connect(name: Literal['doctree-resolved'], callback: Callable[[Sphinx, nodes.document, str], None], priority: int) int
connect(name: Literal['missing-reference'], callback: Callable[[Sphinx, BuildEnvironment, addnodes.pending_xref, nodes.TextElement], nodes.reference | None], priority: int) int
connect(name: Literal['warn-missing-reference'], callback: Callable[[Sphinx, Domain, addnodes.pending_xref], bool | None], priority: int) int
connect(name: Literal['build-finished'], callback: Callable[[Sphinx, Exception | None], None], priority: int) int
connect(name: Literal['html-collect-pages'], callback: Callable[[Sphinx], Iterable[tuple[str, dict[str, Any], str]]], priority: int) int
connect(name: Literal['html-page-context'], callback: Callable[[Sphinx, str, str, dict[str, Any], nodes.document], str | None], priority: int) int
connect(name: Literal['linkcheck-process-uri'], callback: Callable[[Sphinx, str], str | None], priority: int) int
connect(name: Literal['object-description-transform'], callback: Callable[[Sphinx, str, str, addnodes.desc_content], None], priority: int) int
connect(name: Literal['autodoc-process-docstring'], callback: _AutodocProcessDocstringListener, priority: int) int
connect(name: Literal['autodoc-before-process-signature'], callback: Callable[[Sphinx, Any, bool], None], priority: int) int
connect(name: Literal['autodoc-process-signature'], callback: Callable[[Sphinx, Literal['module', 'class', 'exception', 'function', 'method', 'attribute'], str, Any, dict[str, bool], str | None, str | None], tuple[str | None, str | None] | None], priority: int) int
connect(name: Literal['autodoc-process-bases'], callback: Callable[[Sphinx, str, Any, dict[str, bool], list[str]], None], priority: int) int
connect(name: Literal['autodoc-skip-member'], callback: Callable[[Sphinx, Literal['module', 'class', 'exception', 'function', 'method', 'attribute'], str, Any, bool, dict[str, bool]], bool], priority: int) int
connect(name: Literal['todo-defined'], callback: Callable[[Sphinx, todo_node], None], priority: int) int
connect(name: Literal['viewcode-find-source'], callback: Callable[[Sphinx, str], tuple[str, dict[str, tuple[Literal['class', 'def', 'other'], int, int]]]], priority: int) int
connect(name: Literal['viewcode-follow-imported'], callback: Callable[[Sphinx, str, str], str | None], priority: int) int
connect(name: str, callback: Callable[..., Any], priority: int) int

Connect a handler to specific event.

disconnect(listener_id: int) None[source]

Disconnect a handler.

emit(name: str, *args: Any, allowed_exceptions: tuple[type[Exception], ...] = ()) list[source]

Emit a Sphinx event.

emit_firstresult(name: str, *args: Any, allowed_exceptions: tuple[type[Exception], ...] = ()) Any[source]

Emit a Sphinx event and returns first result.

This returns the result of the first handler that doesn’t return None.

Utility functions

sphinx.util.parsing.nested_parse_to_nodes(state: RSTState, text: str | StringList, *, source: str = '<generated text>', offset: int = 0, allow_section_headings: bool = True, keep_title_context: bool = False) list[Node][source]

Parse text into nodes.

Parameters:
  • state – The state machine state. Must be a subclass of RSTState.

  • text – Text, in string form. StringList is also accepted.

  • source – The text’s source, used when creating a new StringList.

  • offset – The offset of the content.

  • allow_section_headings – Are titles (sections) allowed in text? Note that this option bypasses Docutils’ usual checks on doctree structure, and misuse of this option can lead to an incoherent doctree. In Docutils, section nodes should only be children of Structural nodes, which includes document, section, and sidebar nodes.

  • keep_title_context – If this is False (the default), then content is parsed as if it were an independent document, meaning that title decorations (e.g. underlines) do not need to match the surrounding document. This is useful when the parsed content comes from a completely different context, such as docstrings. If this is True, then title underlines must match those in the surrounding document, otherwise the behaviour is undefined.

Added in version 7.4.

Utility types

class sphinx.util.typing.ExtensionMetadata[source]

The metadata returned by an extension’s setup() function.

See Extension metadata.

env_version: int

An integer that identifies the version of env data added by the extension.

parallel_read_safe: bool

Indicate whether parallel reading of source files is supported by the extension.

parallel_write_safe: bool

Indicate whether parallel writing of output files is supported by the extension (default: True).

version: str

The extension version (default: 'unknown version').