应用接口

每个Sphinx扩展都是一个Python模块,其中至少有一个:func:`setup`函数。此函数在初始化时使用一个参数调用,即表示Sphinx进程的应用程序对象。

class sphinx.application.Sphinx[源代码]

此应用程序对象具有下面描述的公共接口。

插件设置

这些方法通常在扩展的“setup()”函数中调用。

可以在:mod:`sphinx.ext`包装。

Sphinx.setup_extension(extname: str) None[源代码]

导入并设置Sphinx插件模块。

加载由模块*name*指定的扩展名。如果您的扩展需要其他扩展提供的功能,请使用此选项。如果提示了两次,则无需操作。

static Sphinx.require_sphinx(version: tuple[int, int] | str) None[源代码]

检查sphinx版”if”请求。

Compare version with the version of the running Sphinx, and abort the build when it is too old.

参数:

version – The required version in the form of major.minor or (major, minor).

Added in version 1.0.

在 7.1 版本发生变更: Type of version now allows (major, minor) form.

Sphinx.connect(event: str, callback: Callable, priority: int = 500) int[源代码]

发出*event*时要调用的寄存器*callback*。

有关可用核心事件和回调函数参数的详细信息,请参阅:ref:events

参数:
  • event – The name of target event

  • callback – Callback function for the event

  • priority – The priority of the callback. The callbacks will be invoked in order of priority (ascending).

返回:

A listener ID. It can be used for disconnect().

在 3.0 版本发生变更: 支持*优先级*

Sphinx.disconnect(listener_id: int) None[源代码]

按*listener_id*取消注册回调。

参数:

listener_id – A listener_id that connect() returns

Sphinx.add_builder(builder: type[Builder], override: bool = False) None[源代码]

注册一个新的建造者。

参数:
  • builder – A builder class

  • override – If true, install the builder forcedly even if another builder is already installed as the same name

在 1.8 版本发生变更: 添加*覆盖*关键字。

Sphinx.add_config_value(name: str, default: Any, rebuild: Literal['', 'env', 'epub', 'gettext', 'html', 'applehelp', 'devhelp'], types: type | Collection[type] | ENUM = ()) None[源代码]

注册配置值。

This is necessary for Sphinx to recognize new values and set default values accordingly.

参数:
  • name – The name of the configuration value. It is recommended to be prefixed with the extension name (ex. html_logo, epub_title)

  • default – The default value of the configuration.

  • rebuild

    The condition of rebuild. It must be one of those values:

    • ``“env”`如果设置中的更改仅在文档被解析时生效—这意味着必须重新构建整个环境。

    • ``“html”``如果更改设置需要完全重新生成html文档。

    • ``’’``如果设置中的更改不需要任何特殊的重建。

  • types – The type of configuration value. A list of types can be specified. For example, [str] is used to describe a configuration that takes string value.

在 0.4 版本发生变更: 如果*default*值是可调用的,则将使用config对象作为其参数来调用它,以获取默认值。这可以用来实现默认值依赖于其他值的配置值。

在 0.6 版本发生变更: 将*rebuild*从一个简单的布尔值(相当于’’’’’或’’env’``’)更改为字符串。但是,布尔值仍然被接受并在内部转换。

Sphinx.add_event(name: str) None[源代码]

注册一个名为*name*的事件。

这是需要有能力发射它。

参数:

name – The name of the event

Sphinx.set_translator(name: str, translator_class: type[nodes.NodeVisitor], override: bool = False) None[源代码]

注册或重写Docutils转换器类。

This is used to register a custom output translator or to replace a builtin translator. This allows extensions to use a custom translator and define custom nodes for the translator (see add_node()).

参数:
  • name – The name of the builder for the translator

  • translator_class – A translator class

  • override – If true, install the translator forcedly even if another translator is already installed as the same name

Added in version 1.3.

在 1.8 版本发生变更: 添加*覆盖*关键字。

Sphinx.add_node(node: type[Element], override: bool = False, **kwargs: tuple[Callable, Callable | None]) None[源代码]

注册Docutils节点类。

这对于Docutils内部构件是必需的。将来还可以使用它来验证已解析文档中的节点。

参数:
  • node – A node class

  • kwargs – Visitor functions for each builder (see below)

  • override – If true, install the node forcedly even if another node is already installed as the same name

Sphinx HTML、LaTeX、text和手册页编写器的节点访问者函数可以作为关键字参数给定:关键字应该是一个或多个“HTML”、“LaTeX”、“text”、“man”、“texinfo”或任何其他受支持的翻译器,值为“2元组”(visit,depart)``方法。``如果“visit”函数引发:exc:`docutils.nodes.SkipNode. 例子:

class math(docutils.nodes.Element): pass

def visit_math_html(self, node):
    self.body.append(self.starttag(node, 'math'))
def depart_math_html(self, node):
    self.body.append('</math>')

app.add_node(math, html=(visit_math_html, depart_math_html))

显然,当在要翻译的文档中遇到未指定访问者方法的转换器时,会在节点上卡住。

在 0.5 版本发生变更: 增加了对提供访问函数的关键字参数的支持。

Sphinx.add_enumerable_node(node: type[Element], figtype: str, title_getter: TitleGetter | None = None, override: bool = False, **kwargs: tuple[Callable, Callable]) None[源代码]

将Docutils节点类注册为numfig目标。

Sphinx会自动为节点编号。然后用户可以使用:rst:角色:numref

参数:
  • node – A node class

  • figtype – The type of enumerable nodes. Each figtype has individual numbering sequences. As system figtypes, figure, table and code-block are defined. It is possible to add custom nodes to these default figtypes. It is also possible to define new custom figtype if a new figtype is given.

  • title_getter – A getter function to obtain the title of node. It takes an instance of the enumerable node, and it must return its title as string. The title is used to the default title of references for ref. By default, Sphinx searches docutils.nodes.caption or docutils.nodes.title from the node as a title.

  • kwargs – Visitor functions for each builder (same as add_node())

  • override – If true, install the node forcedly even if another node is already installed as the same name

Added in version 1.4.

Sphinx.add_directive(name: str, cls: type[Directive], override: bool = False) None[源代码]

注册Docutils指令。

参数:
  • name – The name of the directive

  • cls – A directive class

  • override – If false, do not install it if another directive is already installed as the same name If true, unconditionally install the directive.

For example, a custom directive named my-directive would be added like this:

from docutils.parsers.rst import Directive, directives

class MyDirective(Directive):
    has_content = True
    required_arguments = 1
    optional_arguments = 0
    final_argument_whitespace = True
    option_spec = {
        'class': directives.class_option,
        'name': directives.unchanged,
    }

    def run(self):
        ...

def setup(app):
    app.add_directive('my-directive', MyDirective)

For more details, see the Docutils docs .

在 0.6 版本发生变更: 现在支持Docutils 0.5样式的指令类。

自 1.8 版本弃用: 不推荐使用Docutils 0.4样式(基于函数)指令支持。

在 1.8 版本发生变更: 添加*覆盖*关键字。

Sphinx.add_role(name: str, role: Any, override: bool = False) None[源代码]

注册Docutils角色。

参数:
  • name – The name of role

  • role – A role function

  • override – If false, do not install it if another role is already installed as the same name If true, unconditionally install the role.

For more details about role functions, see the Docutils docs .

在 1.8 版本发生变更: 添加*覆盖*关键字。

Sphinx.add_generic_role(name: str, nodeclass: Any, override: bool = False) None[源代码]

注册通用Docutils角色。

注册一个Docutils角色,该角色只在*nodeclass*给定的节点中包装其内容。

参数:

override – If false, do not install it if another role is already installed as the same name If true, unconditionally install the role.

Added in version 0.6.

在 1.8 版本发生变更: 添加*覆盖*关键字。

Sphinx.add_domain(domain: type[Domain], override: bool = False) None[源代码]

注册域。

参数:
  • domain – A domain class

  • override – If false, do not install it if another domain is already installed as the same name If true, unconditionally install the domain.

Added in version 1.0.

在 1.8 版本发生变更: 添加*覆盖*关键字。

Sphinx.add_directive_to_domain(domain: str, name: str, cls: type[Directive], override: bool = False) None[源代码]

在域中注册Docutils指令。

例如:meth:addu directive,但该指令被添加到名为*domain*的域中。

参数:
  • domain – The name of target domain

  • name – A name of directive

  • cls – A directive class

  • override – If false, do not install it if another directive is already installed as the same name If true, unconditionally install the directive.

Added in version 1.0.

在 1.8 版本发生变更: 添加*覆盖*关键字。

Sphinx.add_role_to_domain(domain: str, name: str, role: RoleFunction | XRefRole, override: bool = False) None[源代码]

在域中注册Docutils角色。

Like:meth:addu role,但是角色被添加到名为*domain*的域中。

参数:
  • domain – The name of the target domain

  • name – The name of the role

  • role – The role function

  • override – If false, do not install it if another role is already installed as the same name If true, unconditionally install the role.

Added in version 1.0.

在 1.8 版本发生变更: 添加*覆盖*关键字。

Sphinx.add_index_to_domain(domain: str, index: type[Index], override: bool = False) None[源代码]

注册域的自定义索引。

Add a custom index class to the domain named domain.

参数:
  • domain – The name of the target domain

  • index – The index class

  • override – If false, do not install it if another index is already installed as the same name If true, unconditionally install the index.

Added in version 1.0.

在 1.8 版本发生变更: 添加*覆盖*关键字。

Sphinx.add_object_type(directivename: str, rolename: str, indextemplate: str = '', parse_node: Callable | None = None, ref_nodeclass: type[TextElement] | None = None, objname: str = '', doc_field_types: Sequence = (), override: bool = False) None[源代码]

注册一个新的对象类型。

这方法是添加一个新的:term:`object`类型的非常方便的方法,可以交叉引用。它将这样做:

  • 创建一个新的指令(称为*directivename*),用于记录对象。如果*indextemplate*非空,它将自动添加索引项;如果给定,则它必须正好包含一个````实例。有关如何解释模板,请参见下面的示例。

  • 创建一个新角色(称为*rolename*),以交叉引用这些对象描述。

  • 如果提供*parse_node*,它必须是一个接受字符串和docutils节点的函数,并且必须使用从字符串解析的子节点填充节点。然后它必须返回要在交叉引用和索引项中使用的项的名称。请参见:文件:`配置文件`文件在源文件中的示例。

  • objname*(如果未给定,将默认为*directivename)命名对象的类型。在列出对象时使用,例如在搜索结果中。

例如,如果在自定义Sphinx插件中有此调用:

app.add_object_type('directive', 'dir', 'pair: %s; directive')

您可以在文档中使用此标记:

.. rst:directive:: function

   Document a function.

<...>

See also the :rst:dir:`function` directive.

对于该指令,将生成一个索引项,就像您预先添加了:

.. index:: pair: function; directive

引用节点将是“literal”类(因此它将以适合代码的比例字体呈现),除非提供*ref_nodeclass*参数,该参数必须是docutils节点类。最有用的是``docutils.nodes.emphasis``或者``docutils.nodes.strong``–您也可以使用``docutils.nodes.generated``如果你不想进一步的文字装饰。如果文本应视为文字(例如,没有智能引号替换),但没有打字机样式,则使用``sphinx.addnodes.literal_强调``或者``sphinx.addnodes.literal_强``.

对于角色内容,您具有与标准Sphinx角色相同的语法可能性(请参见:ref:xref syntax)。

If override is True, the given object_type is forcedly installed even if an object_type having the same name is already installed.

在 1.8 版本发生变更: 添加*覆盖*关键字。

Sphinx.add_crossref_type(directivename: str, rolename: str, indextemplate: str = '', ref_nodeclass: type[TextElement] | None = None, objname: str = '', override: bool = False) None[源代码]

注册新的交叉引用对象类型。

This method is very similar to add_object_type() except that the directive it generates must be empty, and will produce no output.

这意味着您可以将语义目标添加到源代码中,并使用自定义角色而不是通用角色来引用它们(例如:rst:角色:ref)。示例调用:

app.add_crossref_type('topic', 'topic', 'single: %s',
                      docutils.nodes.emphasis)

用法示例:

.. topic:: application API

The application API
-------------------

Some random text here.

See also :topic:`this section <application API>`.

(当然,``topic``指令后面的元素不必是节。)

参数:

override – If false, do not install it if another cross-reference type is already installed as the same name If true, unconditionally install the cross-reference type.

在 1.8 版本发生变更: 添加*覆盖*关键字。

Sphinx.add_transform(transform: type[Transform]) None[源代码]

注册要在解析后应用的Docutils转换。

Add the standard docutils Transform subclass transform to the list of transforms that are applied after Sphinx parses a reST document.

参数:

transform – A transform class

Sphinx变换的优先级范围类别

优先级

sphinx的主要目标

0-99

用docutils修复无效节点。翻译博士论文。

100-299

准备

300-399

早期的

400-699

主要的

700-799

后置处理。修改文本和引用的截止日期。

800-899

收集引用和引用节点。域处理。

900-999

完成并清理。

refs: Transform Priority Range Categories

Sphinx.add_post_transform(transform: type[Transform]) None[源代码]

在编写之前注册要应用的Docutils转换。

Add the standard docutils Transform subclass transform to the list of transforms that are applied before Sphinx writes a document.

参数:

transform – A transform class

Sphinx.add_js_file(filename: str | None, priority: int = 500, loading_method: str | None = None, **kwargs: Any) None[源代码]

注册一个JavaScript文件以包含在HTML输出中。

参数:
  • filename – The name of a JavaScript file that the default HTML template will include. It must be relative to the HTML static path, or a full URI with scheme, or None . The None value is used to create an inline <script> tag. See the description of kwargs below.

  • priority – Files are included in ascending order of priority. If multiple JavaScript files have the same priority, those files will be included in order of registration. See list of “priority range for JavaScript files” below.

  • loading_method – The loading method for the JavaScript file. Either 'async' or 'defer' are allowed.

  • kwargs – Extra keyword arguments are included as attributes of the <script> tag. If the special keyword argument body is given, its value will be added as the content of the <script> tag.

例如:

app.add_js_file('example.js')
# => <script src="_static/example.js"></script>

app.add_js_file('example.js', loading_method="async")
# => <script src="_static/example.js" async="async"></script>

app.add_js_file(None, body="var myVariable = 'foo';")
# => <script>var myVariable = 'foo';</script>
priority range for JavaScript files

优先级

sphinx的主要目标

200

default priority for built-in JavaScript files

500

default priority for extensions

800

default priority for html_js_files

A JavaScript file can be added to the specific HTML page when an extension calls this method on html-page-context event.

Added in version 0.5.

在 1.8 版本发生变更: 重命名自``app.add_javascript应用程序()``. 它允许关键字参数作为脚本标记的属性。

在 3.5 版本发生变更: Take priority argument. Allow to add a JavaScript file to the specific page.

在 4.4 版本发生变更: Take loading_method argument. Allow to change the loading method of the JavaScript file.

Sphinx.add_css_file(filename: str, priority: int = 500, **kwargs: Any) None[源代码]

注册要包含在HTML输出中的样式表。

参数:
  • filename – The name of a CSS file that the default HTML template will include. It must be relative to the HTML static path, or a full URI with scheme.

  • priority – Files are included in ascending order of priority. If multiple CSS files have the same priority, those files will be included in order of registration. See list of “priority range for CSS files” below.

  • kwargs – Extra keyword arguments are included as attributes of the <link> tag.

例如:

app.add_css_file('custom.css')
# => <link rel="stylesheet" href="_static/custom.css" type="text/css" />

app.add_css_file('print.css', media='print')
# => <link rel="stylesheet" href="_static/print.css"
#          type="text/css" media="print" />

app.add_css_file('fancy.css', rel='alternate stylesheet', title='fancy')
# => <link rel="alternate stylesheet" href="_static/fancy.css"
#          type="text/css" title="fancy" />
priority range for CSS files

优先级

sphinx的主要目标

200

default priority for built-in CSS files

500

default priority for extensions

800

default priority for html_css_files

A CSS file can be added to the specific HTML page when an extension calls this method on html-page-context event.

Added in version 1.0.

在 1.6 版本发生变更: Optional alternate and/or title attributes can be supplied with the arguments alternate (a Boolean) and title (a string). The default is no title and alternate = False. For more information, refer to the documentation.

在 1.8 版本发生变更: 重命名自``app.add_样式表()``. 它允许关键字参数作为链接标记的属性。

在 3.5 版本发生变更: Take priority argument. Allow to add a CSS file to the specific page.

Sphinx.add_latex_package(packagename: str, options: str | None = None, after_hyperref: bool = False) None[源代码]

注册包,以包含在LaTeX源代码中。

Add packagename to the list of packages that LaTeX source code will include. If you provide options, it will be taken to the usepackage declaration. If you set after_hyperref truthy, the package will be loaded after hyperref package.

app.add_latex_package('mypackage')
# => \usepackage{mypackage}
app.add_latex_package('mypackage', 'foo,bar')
# => \usepackage[foo,bar]{mypackage}

Added in version 1.3.

Added in version 3.1: *在_hyperref*选项之后。

Sphinx.add_lexer(alias: str, lexer: type[Lexer]) None[源代码]

为源代码注册一个新的分析程序。

使用*lexer*突出显示具有给定语言*alias*的代码块。

Added in version 0.6.

在 2.1 版本发生变更: Take a lexer class as an argument.

在 4.0 版本发生变更: Removed support for lexer instances as an argument.

Sphinx.add_autodocumenter(cls: Any, override: bool = False) None[源代码]

为自动文档插件注册一个新的documenter类。

Add cls as a new documenter class for the sphinx.ext.autodoc extension. It must be a subclass of sphinx.ext.autodoc.Documenter. This allows auto-documenting new types of objects. See the source of the autodoc module for examples on how to subclass Documenter.

If override is True, the given cls is forcedly installed even if a documenter having the same name is already installed.

参见 为IntEnum开发autodoc 插件

Added in version 0.6.

在 2.2 版本发生变更: 添加*覆盖*关键字。

Sphinx.add_autodoc_attrgetter(typ: type, getter: Callable[[Any, str, Any], Any]) None[源代码]

为自动文档插件注册一个类似“getattr”的新函数。

添加*getter*,它必须是一个接口与:func:getattr`内置函数兼容的函数,作为*typ*实例的对象的autodoc属性getter。自动文档需要获取某个类型属性的所有情况都由该函数处理,而不是:func:`getattr

Added in version 0.6.

Sphinx.add_search_language(cls: Any) None[源代码]

为HTML搜索索引注册一种新语言。

添加*cls*,它必须是:class:sphinx搜索语言,作为生成HTML全文搜索索引的支持语言。该类必须具有一个*lang*属性,该属性指示该类应用于的语言。请参阅:confval:html_search_language

Added in version 1.1.

Sphinx.add_source_suffix(suffix: str, filetype: str, override: bool = False) None[源代码]

注册源文件的后缀。

Same as source_suffix. The users can override this using the config setting.

参数:

override – If false, do not install it the same suffix is already installed. If true, unconditionally install the suffix.

Added in version 1.8.

Sphinx.add_source_parser(parser: type[Parser], override: bool = False) None[源代码]

注册解析器类。

参数:

override – If false, do not install it if another parser is already installed for the same suffix. If true, unconditionally install the parser.

Added in version 1.4.

在 1.8 版本发生变更: *后缀*参数已弃用。它只接受*parser*参数。使用:meth:`add_source_suffix`API来注册后缀。

在 1.8 版本发生变更: 添加*覆盖*关键字。

Sphinx.add_env_collector(collector: type[EnvironmentCollector]) None[源代码]

注册环境收集器类。

请参阅:ref:collector api

Added in version 1.6.

Sphinx.add_html_theme(name: str, theme_path: str) None[源代码]

注册HTML主题。

The name is a name of theme, and theme_path is a full path to the theme (refs: 将主题作为Python包分发).

Added in version 1.6.

Sphinx.add_html_math_renderer(name: str, inline_renderers: tuple[Callable, Callable | None] | None = None, block_renderers: tuple[Callable, Callable | None] | None = None) None[源代码]

注册HTML渲染器。

*name*是数学渲染器的名称。*inline_renderers*和*block_renderers*都用作HTML编写器的访问者函数:前者用于inline math节点(节点.math),后者用于块数学节点(nodes.math_块). 关于访问者函数,请参见:meth:`addu node`以获取详细信息。

Added in version 1.8.

Sphinx.add_message_catalog(catalog: str, locale_dir: str) None[源代码]

注册邮件目录。

参数:
  • catalog – The name of the catalog

  • locale_dir – The base path of the message catalog

For more details, see sphinx.locale.get_translation().

Added in version 1.8.

Sphinx.is_parallel_allowed(typ: str) bool[源代码]

Check whether parallel processing is allowed or not.

参数:

typ – A type of processing; 'read' or 'write'.

exception sphinx.application.ExtensionError

如果插件接口出现问题,所有这些方法都会引发此异常。

发射事件

class sphinx.application.Sphinx[源代码]
emit(event: str, *args: Any, allowed_exceptions: tuple[type[Exception], ...] = ()) list[源代码]

发出*事件*并将*参数*传递给回调函数。

以列表形式返回所有回调的返回值。不要在扩展中发出核心sphinx事件!

参数:
  • event – The name of event that will be emitted

  • args – The arguments for the event

  • allowed_exceptions – The list of exceptions that are allowed in the callbacks

在 3.1 版本发生变更: 添加了*allowed_exceptions*来指定路径穿越异常

emit_firstresult(event: str, *args: Any, allowed_exceptions: tuple[type[Exception], ...] = ()) Any[源代码]

发出*事件*并将*参数*传递给回调函数。

返回第一个不返回“None”的回调的结果。

参数:
  • event – The name of event that will be emitted

  • args – The arguments for the event

  • allowed_exceptions – The list of exceptions that are allowed in the callbacks

Added in version 0.5.

在 3.1 版本发生变更: 添加了*allowed_exceptions*来指定路径穿越异常

Sphinx运行时信息

应用程序对象还提供运行时信息作为属性。

Sphinx.project

目标项目。参见:类:.项目

Sphinx.srcdir

源目录

Sphinx.confdir

目录包含``配置文件``.

Sphinx.doctreedir

用于存储文档树的目录。

Sphinx.outdir

用于存储生成文档的目录。

Sphinx核心事件

这些事件是众所周知的。显示的参数将提供给已注册的事件处理程序。用法:meth:`.Sphinx连接`在插件的“setup”函数中(注意``配置文件``也可以有一个“setup”函数来将处理程序连接到事件。例子:

def source_read_handler(app, docname, source):
    print('do something here...')

def setup(app):
    app.connect('source-read', source_read_handler)

Below is an overview of each event that happens during a build. In the list below, we include the event name, its callback parameters, and the input and output type for that event:

1. event.config-inited(app,config)
2. event.builder-inited(app)
3. event.env-get-outdated(app, env, added, changed, removed)
4. event.env-before-read-docs(app, env, docnames)

for docname in docnames:
   5. event.env-purge-doc(app, env, docname)

   if doc changed and not removed:
      6. source-read(app, docname, source)
      7. run source parsers: text -> docutils.document
         - parsers can be added with the app.add_source_parser() API
      8. apply transforms based on priority: docutils.document -> docutils.document
         - event.doctree-read(app, doctree) is called in the middle of transforms,
           transforms come before/after this event depending on their priority.

9. event.env-merge-info(app, env, docnames, other)
   - if running in parallel mode, this event will be emitted for each process

10. event.env-updated(app, env)
11. event.env-get-updated(app, env)
12. event.env-check-consistency(app, env)

# The updated-docs list can be builder dependent, but generally includes all new/changed documents,
# plus any output from `env-get-updated`, and then all "parent" documents in the ToC tree
# For builders that output a single page, they are first joined into a single doctree before post-transforms
# or the doctree-resolved event is emitted
for docname in updated-docs:
   13. apply post-transforms (by priority): docutils.document -> docutils.document
   14. event.doctree-resolved(app, doctree, docname)
       - In the event that any reference nodes fail to resolve, the following may emit:
       - event.missing-reference(env, node, contnode)
       - event.warn-missing-reference(domain, node)

15. Generate output files
16. event.build-finished(app, exception)

下面是这些事件的更详细的列表。

builder-inited(app)

创建生成器对象时发出。它可以作为``应用程序生成器``.

config-inited(app, config)

初始化配置对象时发出。

Added in version 1.8.

env-get-outdated(app, env, added, changed, removed)

当环境确定哪些源文件已更改并应重新读取时发出。added*changed*和*removed*是环境确定的文档名集合。除此之外,您还可以返回要重新读取的文档名列表。

Added in version 1.1.

env-purge-doc(app, env, docname)

当应该从环境中清除源文件的所有跟踪时(即,如果删除了源文件或在新读取源文件之前)发出。这是针对在环境属性中保留自己缓存的扩展。

例如,环境中有一个所有模块的缓存。当源文件发生更改时,该文件的缓存项将被清除,因为模块声明可能已从文件中删除。

Added in version 0.5.

env-before-read-docs(app, env, docnames)

在环境确定了所有添加和更改的文件的列表之后,在环境读取这些文件之前发出。它允许扩展作者在处理之前重新排序文档名(inplace),或者添加更多Sphinx认为没有更改的文档名(但绝不添加任何不在``环境发现文件``).

您还可以删除文档名;请谨慎操作,因为这会使Sphinx将更改后的文件视为未更改的文件。

Added in version 1.3.

source-read(app, docname, source)

读取源文件时发出。*source*参数是一个列表,其单个元素是源文件的内容。您可以处理内容并替换此项来实现源代码级转换。

例如,如果要使用“$`”符号来分隔内联数学,就像在LaTeX中一样,可以使用正则表达式将“$…$”替换为“:math:``”。

Added in version 0.5.

include-read(app, relative_path, parent_docname, content)

Emitted when a file has been read with the include directive. The relative_path argument is a Path object representing the relative path of the included file from the source directory. The parent_docname argument is the name of the document that contains the include directive. The source argument is a list whose single element is the contents of the included file. You can process the contents and replace this item to transform the included content, as with the source-read event.

Added in version 7.2.5.

参见

The include directive and the source-read event.

object-description-transform(app, domain, objtype, contentnode)

在运行对象描述指令时发出。*domain*和*objtype*参数是表示对象的对象描述的字符串。而*contentnode*是对象的内容。可以就地修改。

Added in version 2.4.

doctree-read(app, doctree)

当环境解析和读取文档树并将要进行处理时发出。*doctree*可以就地修改。

missing-reference(app, env, node, contnode)

Emitted when a cross-reference to an object cannot be resolved. If the event handler can resolve the reference, it should return a new docutils node to be inserted in the document tree in place of the node node. Usually this node is a reference node containing contnode as a child. If the handler can not resolve the cross-reference, it can either return None to let other handlers try, or raise NoUri to prevent other handlers in trying and suppress a warning about this cross-reference being unresolved.

参数:
  • env – 构建环境(app.builder.env).

  • node – The pending_xref node to be resolved. Its reftype, reftarget, modname and classname attributes determine the type and target of the reference.

  • contnode – 在将来引用中承载文本和格式的节点,它应该是返回的引用节点的子节点。

Added in version 0.5.

warn-missing-reference(app, domain, node)

Emitted when a cross-reference to an object cannot be resolved even after missing-reference. If the event handler can emit warnings for the missing reference, it should return True. The configuration variables nitpick_ignore and nitpick_ignore_regex prevent the event from being emitted for the corresponding nodes.

Added in version 3.4.

doctree-resolved(app, doctree, docname)

当环境已“解析”文档树时发出,也就是说,已解析所有引用并插入toc。*doctree*可以就地修改。

这里是替换编写器中没有用户方法的自定义节点的地方,这样当编写器遇到它们时,它们不会导致错误。

env-merge-info(app, env, docnames, other)

此事件仅在启用文档并行读取时发出。对于读取了一些文档的每个子进程,它都会发出一次。

必须在将数据存储在环境中的自定义位置的扩展中处理此事件。否则,主进程中的环境将不知道子进程中存储的信息。

*other*是子进程中的环境对象,*env*是主进程中的环境。*docnames*是在子流程中读取的一组文档名称。

Added in version 1.3.

env-updated(app, env)

Emitted after reading all documents, when the environment and all doctrees are now up-to-date.

您可以从处理程序返回可迭代的文档名。这些文件将被视为更新,并将在编写阶段(重新)编写。

Added in version 0.5.

在 1.3 版本发生变更: 现在使用处理程序的返回值。

env-check-consistency(app, env)

在一致性检查阶段发出。您可以检查整个文档的元数据的一致性。

Added in version 1.6: 作为一个**实验性**事件

html-collect-pages(app)

当HTML生成器开始编写非文档页面时发出。您可以通过从这个事件返回一个包含“(页名,环境,模板名)”的迭代器来添加要写入的页。

Added in version 1.0.

html-page-context(app, pagename, templatename, context, doctree)

当HTML生成器创建了用于呈现模板的上下文字典时发出——这可用于向上下文添加自定义元素。

*pagename*参数是所呈现页面的规范名称,即不带“.html”后缀并使用斜杠作为路径分隔符。*templatename*是要呈现的模板的名称,它将是“`”页面.html’``表示reST文档中的所有页面。

*context*参数是提供给模板引擎以呈现页面的值的字典,可以对其进行修改以包含自定义值。键必须是字符串。

从reST文档创建页面时,*doctree*参数将是文档树;仅从HTML模板创建页面时,*doctree*参数将为“None”。

您可以从处理程序返回一个字符串,然后它将替换“`”页面.html“`”作为此页的HTML模板。

备注

You can install JS/CSS files for the specific page via Sphinx.add_js_file() and Sphinx.add_css_file() since v3.5.0.

Added in version 0.4.

在 1.3 版本发生变更: 返回值现在可以指定模板名称。

linkcheck-process-uri(app, uri)

Emitted when the linkcheck builder collects hyperlinks from document. uri is a collected URI. The event handlers can modify the URI by returning a string.

Added in version 4.1.

build-finished(app, exception)

生成完成后,在Sphinx退出之前发出,通常用于清理。即使生成过程引发异常(以*exception*参数指定),也会发出此事件。事件处理程序运行后,将在应用程序中重新初始化异常。如果生成过程没有引发异常,*exception*将为“None”。这允许根据异常状态自定义清理操作。

Added in version 0.5.

检查Sphinx版本

使用此选项可使您的插件适应Sphinx中的接口更改。

sphinx.version_info = (7, 4, 0, 'beta', 0)

版本信息,以便更好地编程使用。

一个由五个元素组成的元组;对于Sphinx版本1.2.1 beta 3,这将是`(1,2,1,’beta’,3)``。第四个元素可以是:alpha`beta`rc``final``之一。``final``始终将0作为最后一个元素。

Added in version 1.2: 在版本1.2之前,请检查字符串“sphinx.uuuversion”。

配置对象

class sphinx.config.Config(config: dict[str, Any] | None = None, overrides: dict[str, Any] | None = None)[源代码]

配置文件抽象。

The Config object makes the values of all config options available as attributes.

It is exposed via the Sphinx.config and sphinx.environment.BuildEnvironment.config attributes. For example, to get the value of language, use either app.config.language or env.config.language.

模板桥

class sphinx.application.TemplateBridge[源代码]

这个类定义了“模板桥”的接口,也就是说,一个提供了模板名称和上下文的模板的类。

init(builder: Builder, theme: Theme | None = None, dirs: list[str] | None = None) None[源代码]

由生成器调用以初始化模板系统。

*builder*是builder对象;您可能需要查看``builder.config.templates_path``.

*主题*是a:类:`phinx.theming.Theme`对象或无;在后一种情况下,*dirs*可以是查找模板的固定目录列表。

newest_template_mtime() float[源代码]

由生成器调用以确定输出文件是否因模板更改而过期。返回已更改的最新模板文件的m时间。默认实现返回“0”。

render(template: str, context: dict) None[源代码]

由生成器调用,以呈现具有指定上下文(Python字典)的文件名形式给定的模板。

render_string(template: str, context: dict) str[源代码]

由生成器调用以呈现给定为字符串的模板,并具有指定的上下文(Python字典)。

例外

exception sphinx.errors.SphinxError[源代码]

Sphinx错误的基类。

这是“nice”异常的基类。当引发此类异常时,Sphinx将中止构建并向用户显示异常类别和消息。

鼓励插件从这个异常中派生出自定义错误。

异常*not*派生自:exc:`SphinxError`将被视为意外的,并将回溯的一部分(以及保存在临时文件中的完整回溯)显示给用户。

category

异常“category”的描述,用于将异常转换为字符串(“category:message”)。应该在子类中相应地设置。

exception sphinx.errors.ConfigError[源代码]

配置错误。

exception sphinx.errors.ExtensionError(message: str, orig_exc: Exception | None = None, modname: str | None = None)[源代码]

插件错误。

exception sphinx.errors.ThemeError[源代码]

主题错误。

exception sphinx.errors.VersionRequirementError[源代码]

不兼容的Sphinx版本错误。