使用角色和指令扩展语法

概述

reStructuredText和MyST的语法都可以通过创建新的 directives (用于块级元素)和 roles (用于内联元素)来扩展。

在本教程中,我们将扩展 Sphinx 以添加:

  • 一个 hello 角色,它将简单地输出文本 Hello {text}!

  • 一个 hello 指令,它将简单地输出文本 Hello {text}!,作为一个段落。

对于此扩展,您需要对 Python 有一些基本了解,我们还将介绍 docutils API 的一些方面。

设置工程

您可用现有 Sphinx 工程或使用 sphinx-quickstart 创建新工程。

通过此操作,我们将在 source 文件夹中将扩展添加到工程中:

  1. source 目录创建 _ext 文件夹

  2. _ext 文件夹创建一个Python文件 helloworld.py

这是您将获得的文件夹结构的示例:

└── source
    ├── _ext
    │   └── helloworld.py
    ├── conf.py
    ├── index.rst

编写扩展

打开 helloworld.py 并将下列代码粘进去:

 1from __future__ import annotations
 2
 3from docutils import nodes
 4
 5from sphinx.application import Sphinx
 6from sphinx.util.docutils import SphinxDirective, SphinxRole
 7from sphinx.util.typing import ExtensionMetadata
 8
 9
10class HelloRole(SphinxRole):
11    """A role to say hello!"""
12
13    def run(self) -> tuple[list[nodes.Node], list[nodes.system_message]]:
14        node = nodes.inline(text=f'Hello {self.text}!')
15        return [node], []
16
17
18class HelloDirective(SphinxDirective):
19    """A directive to say hello!"""
20
21    required_arguments = 1
22
23    def run(self) -> list[nodes.Node]:
24        paragraph_node = nodes.paragraph(text=f'hello {self.arguments[0]}!')
25        return [paragraph_node]
26
27
28def setup(app: Sphinx) -> ExtensionMetadata:
29    app.add_role('hello', HelloRole())
30    app.add_directive('hello', HelloDirective)
31
32    return {
33        'version': '0.1',
34        'parallel_read_safe': True,
35        'parallel_write_safe': True,
36    }

在此示例中发生了一些重要的事情:

角色类

我们的新角色是在 HelloRole 类中声明的。

1class HelloRole(SphinxRole):
2    """A role to say hello!"""
3
4    def run(self) -> tuple[list[nodes.Node], list[nodes.system_message]]:
5        node = nodes.inline(text=f'Hello {self.text}!')
6        return [node], []

此类扩展了 SphinxRole 类。该类包含一个 run 方法,这是对每个角色的要求。它包含角色的主要逻辑,并返回一个包含以下内容的元组:

  • 一个内联级 docutils 节点列表,由 Sphinx 处理。

  • 一个(可选的)系统消息节点列表

指令类

我们的新指令是在 HelloDirective 类中声明的。

1class HelloDirective(SphinxDirective):
2    """A directive to say hello!"""
3
4    required_arguments = 1
5
6    def run(self) -> list[nodes.Node]:
7        paragraph_node = nodes.paragraph(text=f'hello {self.arguments[0]}!')
8        return [paragraph_node]

此类扩展了 SphinxDirective 类。该类包含一个 run 方法,这对是每个指令的要求。它包含指令的主要逻辑,并返回一个由 Sphinx 处理的块级 docutils 节点列表。它还包含一个 required_arguments 属性,该属性告诉 Sphinx 指令需要多少参数。

什么是 docutils 节点?

当 Sphinx 解析文档时,它会创建一个“抽象语法树”(AST)节点,以结构化的方式表示文档的内容,这通常独立于任何一种输入(rST、MyST 等)或输出(HTML、LaTeX 等)格式。它是一个树,因为每个节点可以有子节点,依此类推:

<document>
   <paragraph>
      <text>
         Hello world!

docutils 包提供了许多 built-in nodes,用于表示不同类型的内容,例如文本、段落、引用、表格等。

每种节点类型通常只接受特定的一组直接子节点,例如 document 节点应仅包含“块级”节点,例如 paragraphsectiontable 等,而 paragraph 节点应仅包含“内联级”节点,例如 textemphasisstrong 等。

参见

docutils文档 creating directives,以及 creating roles

setup()函数

此函数是必需的。 我们使用它将我们的新指令插入 Sphinx。

def setup(app: Sphinx) -> ExtensionMetadata:
    app.add_role('hello', HelloRole())
    app.add_directive('hello', HelloDirective)

    return {
        'version': '0.1',
        'parallel_read_safe': True,
        'parallel_write_safe': True,
    }

您可以做的最简单的事情是调用 Sphinx.add_role()Sphinx.add_directive() 方法,这就是我们在这里所做的。对于这个特定的调用,第一个参数是 reStructuredText 文件中使用的角色/指令本身的名称。在这种情况下,我们将使用 hello。例如:

Some intro text here...

.. hello:: world

Some text with a :hello:`world` role.

我们还返回了 extension metadata,它指示扩展的版本,以及可以安全地将扩展用于并行读取和写入的事实。

使用扩展

该扩展名必须在您的 conf.py 文件中声明,以使 Sphinx 意识到这一点。 这里需要两个步骤:

  1. 使用sys.path.append将 _ext 目录新增到 Python path 中。 这应该放在文件的顶部。

  2. 更新或创建 extensions 列表,并将扩展名添加到列表中

例如:

import sys
from pathlib import Path

sys.path.append(str(Path('_ext').resolve()))

extensions = ['helloworld']

小技巧

因为我们没有将扩展安装为 Python package,所以我们需要修改 Python path,Sphinx 才能找到我们的扩展名。这就是为什么我们需要调用 sys.path.append

现在,您可以在文件中使用扩展名。 例如:

Some intro text here...

.. hello:: world

Some text with a :hello:`world` role.

上面的示例将生成:

Some intro text here...

Hello world!

Some text with a hello world! role.

延伸阅读

这是创建新角色和指令的扩展的基本原理。

有关更高级的示例,请参阅 对构建过程进行扩展

如果您希望在多个项目或与其他人共享您的扩展,请查看 第三方插件 部分。