Sphinx

# Domain API

class sphinx.domains.Domain(env: BuildEnvironment)

  A Domain is meant to be a group of “object” description directives for objects of a similar nature, and corresponding roles to create references to them. Examples would be Python modules, classes, functions etc., elements of a templating language, Sphinx roles and directives, etc.

  Each domain has a separate storage for information about existing objects and how to reference them in self.data, which must be a dictionary. It also must implement several functions that expose the object information in a uniform way to parts of Sphinx that allow the user to reference or search for objects in a domain-agnostic way.

  About self.data: since all object and cross-referencing information is stored on a BuildEnvironment instance, the domain.data object is also stored in the env.domaindata dict under the key domain.name. Before the build process starts, every active domain is instantiated and given the environment object; the domaindata dict must then either be nonexistent or a dictionary whose ‘version’ key is equal to the domain class’ `data_version` attribute. Otherwise, OSError is raised and the pickled environment is discarded.

  add_object_type(name: str, objtype: ObjType) → None

    Add an object type.

  check_consistency() → None

    Do consistency checks (experimental).

  clear_doc(docname: str) → None

    Remove traces of a document in the domain-specific inventories.

  directive(name: str) → type[Directive] | None

    Return a directive adapter class that always gives the registered directive its full name (‘domain:name’) as `self.name`.

  get_enumerable_node_type(node: Node) → str | None

    Get type of enumerable nodes (experimental).

  get_full_qualified_name(node: Element) → str | None

    Return full qualified name for given node.

  get_objects() → Iterable[tuple[str, str, str, str, str, int]]

    Return an iterable of “object descriptions”.

    Object descriptions are tuples with six items:

    `name`

      Fully qualified name.

    `dispname`

      Name to display when searching/linking.

    `type`

      Object type, a key in `self.object_types`.

    `docname`

      The document where it is to be found.

    `anchor`

      The anchor name for the object.

    `priority`

      How “important” the object is (determines placement in search results). One of:

      `1`

        Default priority (placed before full-text matches).

      `0`

        Object is important (placed before default-priority objects).

      `2`

        Object is unimportant (placed after full-text matches).

      `-1`

        Object should not show up in search at all.

  get_type_name(type: ObjType, primary: bool = False) → str

    Return full name for given ObjType.

  merge_domaindata(docnames: Set[str], otherdata: dict[str, Any]) → None

    Merge in data regarding docnames from a different domaindata inventory (coming from a subprocess in parallel builds).

  process_doc(env: BuildEnvironment, docname: str, document: nodes.document) → None

    Process a document after it is read by the environment.

  process_field_xref(pnode: pending_xref) → None

    Process a pending xref created in a doc field. For example, attach information about the current scope.

  resolve_any_xref(env: BuildEnvironment, fromdocname: str, builder: Builder, target: str, node: pending_xref, contnode: Element) → list[tuple[str, nodes.reference]]

    Resolve the pending_xref node with the given target.

    The reference comes from an “any” or similar role, which means that we don’t know the type. Otherwise, the arguments are the same as for `resolve_xref()`.

    The method must return a list (potentially empty) of tuples `('domain:role', newnode)`, where `'domain:role'` is the name of a role that could have created the same reference, e.g. `'py:func'`. `newnode` is what `resolve_xref()` would return.

    Added in version 1.3.

  resolve_xref(env: BuildEnvironment, fromdocname: str, builder: Builder, typ: str, target: str, node: pending_xref, contnode: Element) → nodes.reference | None

    Resolve the pending_xref node with the given typ and target.

    This method should return a new node, to replace the xref node, containing the contnode which is the markup content of the cross-reference.

    If no resolution can be found, None can be returned; the xref node will then given to the `missing-reference` event, and if that yields no resolution, replaced by contnode.

    The method can also raise `sphinx.environment.NoUri` to suppress the `missing-reference` event being emitted.

  role(name: str) → RoleFunction | None

    Return a role adapter function that always gives the registered role its full name (‘domain:name’) as the first argument.

  setup() → None

    Set up domain object.

  dangling_warnings: dict[str, str] = {}

    role name -> a warning message if reference is missing

  data: dict[str, Any]

    data value

  data_version = 0

    data version, bump this when the format of self.data changes

  directives: dict[str, type[Directive]] = {}

    directive name -> directive class

  enumerable_nodes: dict[type[Node], tuple[str, TitleGetter | None]] = {}

    node_class -> (enum_node_type, title_getter)

  indices: list[type[Index]] = []

    a list of Index subclasses

  initial_data: dict[str, Any] = {}

    data value for a fresh environment

  label = ''

    domain label: longer, more descriptive (used in messages)

  name = ''

    domain name: should be short, but unique

  object_types: dict[str, ObjType] = {}

    type (usually directive) name -> ObjType instance

  roles: dict[str, RoleFunction | XRefRole] = {}

    role name -> role callable

class sphinx.domains.ObjType(lname: str, /, *roles: Any, **attrs: Any)

  An ObjType is the description for a type of object that a domain can document. In the object_types attribute of Domain subclasses, object type names are mapped to instances of this class.

  Constructor arguments:

  - lname: localized name of the type (do not include domain name)

  - roles: all the roles that can refer to an object of this type

  - attrs: object attributes – currently only “searchprio” is known, which defines the object’s priority in the full-text search index, see `Domain.get_objects()`.

class sphinx.domains.Index(domain: Domain)

  An Index is the description for a domain-specific index. To add an index to a domain, subclass Index, overriding the three name attributes:

  - name is an identifier used for generating file names. It is also used for a hyperlink target for the index. Therefore, users can refer the index page using `ref` role and a string which is combined domain name and `name` attribute (ex. `:ref:`py-modindex``).

  - localname is the section title for the index.

  - shortname is a short name for the index, for use in the relation bar in HTML output. Can be empty to disable entries in the relation bar.

  and providing a `generate()` method. Then, add the index class to your domain’s indices list. Extensions can add indices to existing domains using `add_index_to_domain()`.

  Changed in version 3.0: Index pages can be referred by domain name and index name via `ref` role.

  abstractmethod generate(docnames: Iterable[str] | None = None) → tuple[list[tuple[str, list[IndexEntry]]], bool]

    Get entries for the index.

    If `docnames` is given, restrict to entries referring to these docnames.

    The return value is a tuple of `(content, collapse)`:

    `collapse`

      A boolean that determines if sub-entries should start collapsed (for output formats that support collapsing sub-entries).

    `content`:

      A sequence of `(letter, entries)` tuples, where `letter` is the “heading” for the given `entries`, usually the starting letter, and `entries` is a sequence of single entries. Each entry is an `IndexEntry`.

class sphinx.domains.IndexEntry(name: str, subtype: int, docname: str, anchor: str, extra: str, qualifier: str, descr: str)

  An index entry.

  Note

  The qualifier and description are not rendered for some output formats, such as LaTeX.

  name: str

    The name of the index entry to be displayed.

  subtype: int

    The sub-entry related type. One of:

    `0`

      A normal entry.

    `1`

      An entry with sub-entries.

    `2`

      A sub-entry.

  docname: str

    docname where the entry is located.

  anchor: str

    Anchor for the entry within docname

  extra: str

    Extra info for the entry.

  qualifier: str

    Qualifier for the description.

  descr: str

    Description for the entry.

class sphinx.directives.ObjectDescription(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)

  Directive to describe a class, function or similar object.

  Not used directly, but subclassed (in domain-specific directives) to add custom behaviour.

  _object_hierarchy_parts(sig_node: desc_signature) → tuple[str, ...]

    Returns a tuple of strings, one entry for each part of the object’s hierarchy (e.g. `('module', 'submodule', 'Class', 'method')`). The returned tuple is used to properly nest children within parents in the table of contents, and can also be used within the `_toc_entry_name()` method.

    This method must not be used outwith table of contents generation.

  _toc_entry_name(sig_node: desc_signature) → str

    Returns the text of the table of contents entry for the object.

    This function is called once, in `run()`, to set the name for the table of contents entry (a special attribute `_toc_name` is set on the object node, later used in `environment.collectors.toctree.TocTreeCollector.process_doc().build_toc()` when the table of contents entries are collected).

    To support table of contents entries for their objects, domains must override this method, also respecting the configuration setting `toc_object_entries_show_parents`. Domains must also override `_object_hierarchy_parts()`, with one (string) entry for each part of the object’s hierarchy. The result of this method is set on the signature node, and can be accessed as `sig_node['_toc_parts']` for use within this method. The resulting tuple is also used to properly nest children within parents in the table of contents.

    An example implementations of this method is within the python domain (`PyObject._toc_entry_name()`). The python domain sets the `_toc_parts` attribute within the `handle_signature()` method.

  add_target_and_index(name: ObjDescT, sig: str, signode: desc_signature) → None

    Add cross-reference IDs and entries to self.indexnode, if applicable.

    name is whatever `handle_signature()` returned.

  after_content() → None

    Called after parsing content.

    Used to reset information about the current directive context on the build environment.

  before_content() → None

    Called before parsing content.

    Used to set information about the current directive context on the build environment.

  get_signatures() → list[str]

    Retrieve the signatures to document from the directive arguments.

    By default, signatures are given as arguments, one per line.

  handle_signature(sig: str, signode: desc_signature) → ObjDescT

    Parse the signature sig.

    The individual nodes are then appended to signode. If ValueError is raised, parsing is aborted and the whole sig is put into a single desc_name node.

    The return value should be a value that identifies the object. It is passed to `add_target_and_index()` unchanged, and otherwise only used to skip duplicates.

  run() → list[Node]

    Main directive entry function, called by docutils upon encountering the directive.

    This directive is meant to be quite easily subclassable, so it delegates to several additional methods. What it does:

    - find out if called as a domain-specific directive, set self.domain

    - create a desc node to fit all description inside

    - parse standard options, currently no-index

    - create an index node if needed as self.indexnode

    - parse all given signatures (as returned by self.get_signatures()) using self.handle_signature(), which should either return a name or raise ValueError

    - add index entries using self.add_target_and_index()

    - parse the content and handle doc fields in it

  transform_content(content_node: desc_content) → None

    Can be used to manipulate the content.

    Called after creating the content through nested parsing, but before the `object-description-transform` event is emitted, and before the info-fields are transformed.

  final_argument_whitespace = True

    May the final argument contain whitespace?

  has_content = True

    May the directive have content?

  option_spec: ClassVar[OptionSpec] = {'no-contents-entry': <function flag>, 'no-index': <function flag>, 'no-index-entry': <function flag>, 'no-typesetting': <function flag>, 'nocontentsentry': <function flag>, 'noindex': <function flag>, 'noindexentry': <function flag>}

    Mapping of option names to validator functions.

  optional_arguments = 0

    Number of optional arguments after the required arguments.

  required_arguments = 1

    Number of required directive arguments.

## Python Domain

class sphinx.domains.python.PythonDomain(env: BuildEnvironment)

  Python language domain.

  objects
  modules
  note_object(name: str, objtype: str, node_id: str, aliased: bool = False, location: Any = None) → None

    Note a python object for cross reference.

    Added in version 2.1.

  note_module(name: str, node_id: str, synopsis: str, platform: str, deprecated: bool) → None

    Note a python module for cross reference.

    Added in version 2.1.