事件回调 API

将回调函数连接到事件是扩展 Sphinx 的一种简单方法,通过在构建过程中的各个点挂钩来实现.

在扩展的 setup 函数中使用 Sphinx.connect(),或者在你的项目 conf.py 中的 setup 函数中,连接函数到事件:

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

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

参见

扩展可以通过使用 Sphinx.add_event() 添加自己的事件,并通过 Sphinx.emit()Sphinx.emit_firstresult() 调用它们.

核心事件概览

以下是构建过程中发生的核心事件的概述.

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
         - event.include-read(app, relative_path, parent_docname, content)
           is called for each include directive
      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)

if environment is written to disk:
   12. event.env-check-consistency(app, env)

13. event.write-started(app, builder)
    - This is called after ``app.parallel_ok`` has been set,
      which must not be altered by any event handler.

# 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:
   14. apply post-transforms (by priority): docutils.document -> docutils.document
   15. 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)

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

这里还有一个事件流程图,在Sphinx构建过程的上下文中:

// A flow graph of the Sphinx build process, highlighting event callbacks

digraph events {
    graph [
        rankdir=TB
    ];
    node [
        shape=rect
        style=rounded
    ];
    "Sphinx" [
        shape=record
        label = "<init> Sphinx.__init__() | <build> Sphinx.build()"
    ];

    // During initialization
    "config-inited"[style=filled fillcolor="#D5FFFF" color=blue penwidth=2];
    "Sphinx":init -> "config-inited";
    "builder-inited"[style=filled fillcolor="#D5FFFF" color=blue penwidth=2];
    "Sphinx":init -> "builder-inited";

    // During build
    "Builder" [label = "Builder.build()"]
    "Sphinx":build -> "Builder";
    "Builder.build" [
        shape=record
        label = "
            <before_read> before read |
            <read> read |
            <after_read> after read |
            <write> write |
            <finalize> finalize"
    ];
    "Builder" -> "Builder.build";

    "env-get-outdated"[style=filled fillcolor="#D5FFFF" color=blue penwidth=2];
    "Builder.build":before_read -> "env-get-outdated";
    remove_each_doc [shape="ellipse", label="for removed"];
    "Builder.build":before_read -> "remove_each_doc";
    "env-purge-doc"[style=filled fillcolor="#D5FFFF" color=blue penwidth=2];
    "remove_each_doc" -> "env-purge-doc";
    "env-before-read-docs"[style=filled fillcolor="#D5FFFF" color=blue penwidth=2];
    "Builder.build":before_read -> "env-before-read-docs";

    // during read phase
    "Builder.read" [label = "Builder.read()"]
    "Builder.build":read -> "Builder.read";
    read_each_doc [shape="ellipse", label="for added | changed"];
    "Builder.read" -> "read_each_doc";
    merge_each_process [
    shape="ellipse", label="for each process\n(parallel only)"
    ];
    "Builder.read" -> merge_each_process;
    "env-updated"[style=filled fillcolor="#D5FFFF" color=blue penwidth=2];
    "Builder.read" -> "env-updated"

    // during read phase, for each document/process
    "env-purge-doc"[style=filled fillcolor="#D5FFFF" color=blue penwidth=2];
    "read_each_doc" -> "env-purge-doc";
    "source-read"[style=filled fillcolor="#D5FFFF" color=blue penwidth=2];
    "read_each_doc" -> "source-read";
    "Include" [label="Include\ndirective"]
    "read_each_doc" -> "Include";
    "include-read"[style=filled fillcolor="#D5FFFF" color=blue penwidth=2];
    "Include" -> "include-read";
    "ObjectDescription" [label="ObjectDescription\ndirective"]
    "read_each_doc" -> "ObjectDescription";
    "object-description-transform"[style=filled fillcolor="#D5FFFF" color=blue penwidth=2];
    "ObjectDescription" -> "object-description-transform";
    "doctree-read"[style=filled fillcolor="#D5FFFF" color=blue penwidth=2];
    "read_each_doc" -> "doctree-read";
    "env-merge-info"[style=filled fillcolor="#D5FFFF" color=blue penwidth=2];
    "merge_each_process" -> "env-merge-info";

    // after read phase
    "env-get-updated"[style=filled fillcolor="#D5FFFF" color=blue penwidth=2];
    "Builder.build":after_read -> "env-get-updated";
    if_read_changes [shape="diamond", label="if changed\ndocuments"];
    "Builder.build":after_read -> if_read_changes;
    if_read_changes -> "cache the\nBuild.Environment";
    "env-check-consistency"[style=filled fillcolor="#D5FFFF" color=blue penwidth=2];
    if_read_changes -> "env-check-consistency";

    // during write phase
    "write-started"[style=filled fillcolor="#D5FFFF" color=blue penwidth=2];
    "Builder.build":write -> "write-started";
    "Builder.write" [label = "Builder.write()"]
    "Builder.build":write -> "Builder.write";
    write_each_doc [shape="ellipse", label="for updated"];
    "Builder.write" -> write_each_doc;
    "ReferenceResolver" [
    label="ReferenceResolver\nPost-transform"
    ]
    write_each_doc -> "ReferenceResolver";
    "missing-reference"[style=filled fillcolor="#D5FFFF" color=blue penwidth=2];
    ReferenceResolver -> "missing-reference";
    "warn-missing-reference"[style=filled fillcolor="#D5FFFF" color=blue penwidth=2];
    ReferenceResolver -> "warn-missing-reference";
    "HyperlinkCollector" [
    label="HyperlinkCollector\nPost-transform"
    ]
    write_each_doc -> "HyperlinkCollector";
    "linkcheck-process-uri"[style=filled fillcolor="#D5FFFF" color=blue penwidth=2];
    HyperlinkCollector -> "linkcheck-process-uri";
    "doctree-resolved"[style=filled fillcolor="#D5FFFF" color=blue penwidth=2];
    write_each_doc -> "doctree-resolved";
    "html-page-context"[style=filled fillcolor="#D5FFFF" color=blue penwidth=2];
    write_each_doc -> "html-page-context";

    // html only
    "html-collect-pages"[style=filled fillcolor="#D5FFFF" color=blue penwidth=2];
    "Builder.build":finalize -> "html-collect-pages";

    // finalize build
    "build-finished"[style=filled fillcolor="#D5FFFF" color=blue penwidth=2];
    "Builder.build":finalize -> "build-finished";

    // constrain layout ordering
    {rank=same "config-inited" "builder-inited"};
    {rank=same; "env-get-outdated" "env-before-read-docs" "env-get-updated"};
    {rank=same; "env-purge-doc" "source-read" "doctree-read", "merge_each_process"};
    {rank=same; "env-updated" "env-check-consistency"};
    {rank=same; "env-merge-info" "write-started" "Builder.write"};
    {rank=max; "build-finished"};
}

Sphinx 核心事件流程

核心事件详情

以下是这些事件的更详细列表.

config-inited(app, config)
参数:

当配置对象已被初始化时发出.

Added in version 1.8.

builder-inited(app)
参数:

appSphinx

当构建器对象已被创建时发出(可用作 app.builder).

env-get-outdated(app, env, added, changed, removed)
参数:
返回:

Sequence[str] 要重新读取的附加文档名称

当环境确定哪些源文件已更改并应重新读取时发出.*added*、changedremoved 是环境确定的一组文档名称.您可以返回要重新读取的文档名称列表.

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未考虑更改的更多文档名称(但绝不要添加任何不在 found_docs 中的文档名称).

你也可以移除文档名称;请谨慎操作,因为这会使Sphinx将更改的文件视为未更改.

Added in version 1.3.

source-read(app, docname, content)
参数:
  • appSphinx

  • docnamestr

  • contentlist[str] 包含一个元素,表示包含文件的内容.

当一个源文件被读取时发出.

你可以处理 content 并替换此项以实现源级别的转换.

例如,如果你想使用 $ 符号来分隔行内数学公式,就像在 LaTeX 中那样,你可以使用正则表达式将 $...$ 替换为 :math:`...`.

Added in version 0.5.

include-read(app, relative_path, parent_docname, content)
参数:
  • appSphinx

  • relative_pathPath 表示相对于 源目录 的包含文件.

  • parent_docname – 文档名称的 str 包含 include 指令.

  • contentlist[str] 包含一个元素,表示包含文件的内容.

当一个文件通过 include 指令读取时发出.

你可以处理 content 并替换此项以转换包含的内容,如使用 source-read 事件.

Added in version 7.2.5.

参见

The include 指令和 source-read 事件.

object-description-transform(app, domain, objtype, contentnode)
参数:

当一个对象描述指令运行时发出.*domain* 和 objtype 参数是表示对象描述的字符串.*contentnode* 是对象的内容.它可以在原地修改.

Added in version 2.4.

doctree-read(app, doctree)
参数:
  • appSphinx

  • doctreedocutils.nodes.document

当一个 doctree 已经被环境解析和读取,并且即将被序列化时发出.``doctree`` 可以就地修改.

missing-reference(app, env, node, contnode)
参数:
  • appSphinx

  • envBuildEnvironment

  • nodepending_xref 节点待解析.其 reftypereftargetmodnameclassname 属性决定了引用的类型和目标.

  • contnode – 该节点携带未来引用中的文本和格式,并且应该是返回的引用节点的子节点.

返回:

要在文档树中插入的新节点以替代当前节点,或者 None 让其他处理程序尝试.

当无法解析对对象的交叉引用时发出.如果事件处理程序可以解析引用,它应返回一个新的 docutils 节点,以替换文档树中的节点 node.通常这个节点是一个包含 contnode 作为子节点的 reference 节点.如果处理程序无法解析交叉引用,它可以返回 None 让其他处理程序尝试,或者引发 NoUri 以阻止其他处理程序尝试并抑制关于此交叉引用未解析的警告.

Added in version 0.5.

warn-missing-reference(app, domain, node)
参数:
返回:

如果发出了警告,则为 True ,否则为 None

当一个对象的交叉引用无法解析,即使在 missing-reference 之后,也会发出此事件.如果事件处理程序可以为缺失的引用发出警告,它应返回 True.配置变量 nitpick_ignorenitpick_ignore_regex 防止为相应的节点发出此事件.

Added in version 3.4.

doctree-resolved(app, doctree, docname)
参数:
  • appSphinx

  • doctreedocutils.nodes.document

  • docnamestr

当一个 doctree 已经被环境”解析”时发出,即所有引用已被解析并且目录已被插入.*doctree* 可以就地修改.

这里是替换自定义节点的地方,这些自定义节点在写入器中没有访问者方法,这样当写入器遇到它们时不会导致错误.

env-merge-info(app, env, docnames, other)
参数:

只有在启用文档并行读取时才会发出此事件.每个读取了一些文档的子进程都会发出一次.

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

other 是从子进程的环境对象,*env* 是主进程的环境.*docnames* 是在子进程中读取的文档名称集合.

Added in version 1.3.

env-updated(app, env)
参数:
返回:

str 的可迭代对象

在读取所有文档后发出,此时环境和所有doctrees都已更新.

你可以在处理程序中返回一个文档名称的可迭代对象.这些文档将被视为已更新,并将在写入阶段被(重新)写入.

Added in version 0.5.

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

env-get-updated(app, env)
参数:
返回:

str 的可迭代对象

当环境确定哪些源文件已更改并应重新读取时发出.您可以返回一个要重新读取的文档名称的可迭代对象.

env-check-consistency(app, env)
参数:

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

Added in version 1.6.

write-started(app, builder)
参数:

在构建器开始解析和写入文档之前发出.

Added in version 7.4.

build-finished(app, exception)
参数:
  • appSphinx

  • exceptionExceptionNone

当一个构建完成时发出,在Sphinx退出之前,通常用于清理.即使构建过程引发异常,也会发出此事件,异常作为 exception 参数给出.事件处理程序运行后,异常会在应用程序中重新引发.如果构建过程没有引发异常,*exception* 将是 None.这允许根据异常状态自定义清理操作.

Added in version 0.5.

特定生成器事件

这些事件是由特定的构建器发出的.

html-collect-pages(app)
参数:

appSphinx

返回:

(pagename, context, templatename) 的可迭代对象,其中 pagenametemplatename 是字符串,*context* 是 dict[str, Any].

当HTML构建器开始编写非文档页面时发出.

你可以通过从这个事件返回一个可迭代对象来添加页面进行编写.

Added in version 1.0.

html-page-context(app, pagename, templatename, context, doctree)
参数:
  • appSphinx

  • pagenamestr

  • templatenamestr

  • contextdict[str, Any]

  • doctreedocutils.nodes.documentNone

返回:

strNone

当HTML构建器创建了一个上下文字典以渲染模板时发出 – 这可以用于向上下文中添加自定义元素.

pagename 参数是被渲染页面的规范名称,即不带 .html 后缀,并使用斜杠作为路径分隔符.*templatename* 是用于渲染的模板的名称,对于所有来自 reStructuredText 文档的页面,这将是 'page.html'.

context 参数是一个提供给模板引擎渲染页面的值的字典,可以被修改以包含自定义值.

doctree 参数在页面由 reStructuredText 文档创建时将是一个 doctree;当页面仅由 HTML 模板创建时,它将是 None.

你可以在处理程序中返回一个字符串,它将替换 'page.html' 作为此页面的HTML模板.

小技巧

你可以通过 Sphinx.add_js_file() 和 :meth:`.Sphinx.add_css_file`(自 v3.5.0 起)为特定页面安装 JS/CSS 文件.

Added in version 0.4.

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

linkcheck-process-uri(app, uri)
参数:
  • appSphinx

  • uri – 收集的 URI 的 str

返回:

strNone

当 linkcheck 构建器从文档中收集超链接时发出.

事件处理程序可以通过返回一个字符串来修改URI.

Added in version 4.1.