添加参考域

本教程的目标是说明角色、指令和领域。完成后,我们将能够使用此扩展来描述手册并从文档中的其他地方引用该手册。

备注

本教程基于最早发布于 opensource.com 并且是在获得原作者许可的情况下提供的。

概述

我们希望扩展将以下内容添加到Sphinx:

  • A recipe directive ,包含一些描述手册步骤的内容,以及 :contains: 选项突出显示手册的主要成分。

  • A ref role ,它提供了手册本身的交叉引用。

  • A recipe domain ,这使我们能够将上述角色和领域以及索引等内容联系在一起。

为此,我们需要将以下元素添加到Sphinx:

  • 一项新指令称为 recipe

  • 新索引使我们能够参考成分和手册

  • 一个名为 recipe ,其中将包含 recipe 指令和 ref 作用

先决条件

我们需要与中相同的设置 the previous extensions .这次,我们将在一个名为 recipe.py .

以下是您可能获得的文件夹结构的示例:

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

编写扩展

开放 recipe.py 并将以下代码粘贴在其中,所有这些我们将很快详细解释:

  1from collections import defaultdict
  2
  3from docutils.parsers.rst import directives
  4
  5from sphinx import addnodes
  6from sphinx.application import Sphinx
  7from sphinx.directives import ObjectDescription
  8from sphinx.domains import Domain, Index
  9from sphinx.roles import XRefRole
 10from sphinx.util.nodes import make_refnode
 11from sphinx.util.typing import ExtensionMetadata
 12
 13
 14class RecipeDirective(ObjectDescription):
 15    """A custom directive that describes a recipe."""
 16
 17    has_content = True
 18    required_arguments = 1
 19    option_spec = {
 20        'contains': directives.unchanged_required,
 21    }
 22
 23    def handle_signature(self, sig, signode):
 24        signode += addnodes.desc_name(text=sig)
 25        return sig
 26
 27    def add_target_and_index(self, name_cls, sig, signode):
 28        signode['ids'].append('recipe' + '-' + sig)
 29        if 'contains' in self.options:
 30            ingredients = [x.strip() for x in self.options.get('contains').split(',')]
 31
 32            recipes = self.env.get_domain('recipe')
 33            recipes.add_recipe(sig, ingredients)
 34
 35
 36class IngredientIndex(Index):
 37    """A custom index that creates an ingredient matrix."""
 38
 39    name = 'ingredient'
 40    localname = 'Ingredient Index'
 41    shortname = 'Ingredient'
 42
 43    def generate(self, docnames=None):
 44        content = defaultdict(list)
 45
 46        recipes = {
 47            name: (dispname, typ, docname, anchor)
 48            for name, dispname, typ, docname, anchor, _ in self.domain.get_objects()
 49        }
 50        recipe_ingredients = self.domain.data['recipe_ingredients']
 51        ingredient_recipes = defaultdict(list)
 52
 53        # flip from recipe_ingredients to ingredient_recipes
 54        for recipe_name, ingredients in recipe_ingredients.items():
 55            for ingredient in ingredients:
 56                ingredient_recipes[ingredient].append(recipe_name)
 57
 58        # convert the mapping of ingredient to recipes to produce the expected
 59        # output, shown below, using the ingredient name as a key to group
 60        #
 61        # name, subtype, docname, anchor, extra, qualifier, description
 62        for ingredient, recipe_names in ingredient_recipes.items():
 63            for recipe_name in recipe_names:
 64                dispname, typ, docname, anchor = recipes[recipe_name]
 65                content[ingredient].append((
 66                    dispname,
 67                    0,
 68                    docname,
 69                    anchor,
 70                    docname,
 71                    '',
 72                    typ,
 73                ))
 74
 75        # convert the dict to the sorted list of tuples expected
 76        content = sorted(content.items())
 77
 78        return content, True
 79
 80
 81class RecipeIndex(Index):
 82    """A custom index that creates an recipe matrix."""
 83
 84    name = 'recipe'
 85    localname = 'Recipe Index'
 86    shortname = 'Recipe'
 87
 88    def generate(self, docnames=None):
 89        content = defaultdict(list)
 90
 91        # sort the list of recipes in alphabetical order
 92        recipes = self.domain.get_objects()
 93        recipes = sorted(recipes, key=lambda recipe: recipe[0])
 94
 95        # generate the expected output, shown below, from the above using the
 96        # first letter of the recipe as a key to group thing
 97        #
 98        # name, subtype, docname, anchor, extra, qualifier, description
 99        for _name, dispname, typ, docname, anchor, _priority in recipes:
100            content[dispname[0].lower()].append((
101                dispname,
102                0,
103                docname,
104                anchor,
105                docname,
106                '',
107                typ,
108            ))
109
110        # convert the dict to the sorted list of tuples expected
111        content = sorted(content.items())
112
113        return content, True
114
115
116class RecipeDomain(Domain):
117    name = 'recipe'
118    label = 'Recipe Sample'
119    roles = {
120        'ref': XRefRole(),
121    }
122    directives = {
123        'recipe': RecipeDirective,
124    }
125    indices = {
126        RecipeIndex,
127        IngredientIndex,
128    }
129    initial_data = {
130        'recipes': [],  # object list
131        'recipe_ingredients': {},  # name -> object
132    }
133    data_version = 0
134
135    def get_full_qualified_name(self, node):
136        return f'recipe.{node.arguments[0]}'
137
138    def get_objects(self):
139        yield from self.data['recipes']
140
141    def resolve_xref(self, env, fromdocname, builder, typ, target, node, contnode):
142        match = [
143            (docname, anchor)
144            for name, sig, typ, docname, anchor, prio in self.get_objects()
145            if sig == target
146        ]
147
148        if len(match) > 0:
149            todocname = match[0][0]
150            targ = match[0][1]
151
152            return make_refnode(builder, fromdocname, todocname, targ, contnode, targ)
153        else:
154            print('Awww, found nothing')
155            return None
156
157    def add_recipe(self, signature, ingredients):
158        """Add a new recipe to the domain."""
159        name = f'recipe.{signature}'
160        anchor = f'recipe-{signature}'
161
162        self.data['recipe_ingredients'][name] = ingredients
163        # name, dispname, type, docname, anchor, priority
164        self.data['recipes'].append((
165            name,
166            signature,
167            'Recipe',
168            self.env.docname,
169            anchor,
170            0,
171        ))
172
173
174def setup(app: Sphinx) -> ExtensionMetadata:
175    app.add_domain(RecipeDomain)
176
177    return {
178        'version': '0.1',
179        'parallel_read_safe': True,
180        'parallel_write_safe': True,
181    }

让我们一步一步地看看这个扩展的每个部分,以解释正在发生的事情。

指令类

首先要检查的是 RecipeDirective 指令:

 1class RecipeDirective(ObjectDescription):
 2    """A custom directive that describes a recipe."""
 3
 4    has_content = True
 5    required_arguments = 1
 6    option_spec = {
 7        'contains': directives.unchanged_required,
 8    }
 9
10    def handle_signature(self, sig, signode):
11        signode += addnodes.desc_name(text=sig)
12        return sig
13
14    def add_target_and_index(self, name_cls, sig, signode):
15        signode['ids'].append('recipe' + '-' + sig)
16        if 'contains' in self.options:
17            ingredients = [x.strip() for x in self.options.get('contains').split(',')]
18
19            recipes = self.env.get_domain('recipe')
20            recipes.add_recipe(sig, ingredients)

不像 使用角色和指令扩展语法扩展构建过程 ,此指令并非源自 docutils.parsers.rst.Directive 并且没有定义 run 法相反,它源于 sphinx.directives.ObjectDescription 并且限定 handle_signatureadd_target_and_index 方法.这是因为 ObjectDescription 是一个特殊用途指令,旨在描述类、函数或(在我们的例子中)手册等内容。更具体地说, handle_signature 实现解析指令的签名并将对象的名称和类型传递到其超类,同时 add_target_and_index 为此节点添加目标(要链接到)和索引项。

我们还看到该指令定义了 has_content , required_argumentsoption_spec .不像 TodoDirective 添加的指令 previous tutorial ,此指令接受一个参数、配方名称和一个选项, contains ,除了正文中嵌套的reStructuredtext之外。

索引类

待处理

添加指数的简要概述

 1class IngredientIndex(Index):
 2    """A custom index that creates an ingredient matrix."""
 3
 4    name = 'ingredient'
 5    localname = 'Ingredient Index'
 6    shortname = 'Ingredient'
 7
 8    def generate(self, docnames=None):
 9        content = defaultdict(list)
10
11        recipes = {
12            name: (dispname, typ, docname, anchor)
13            for name, dispname, typ, docname, anchor, _ in self.domain.get_objects()
14        }
15        recipe_ingredients = self.domain.data['recipe_ingredients']
16        ingredient_recipes = defaultdict(list)
17
18        # flip from recipe_ingredients to ingredient_recipes
19        for recipe_name, ingredients in recipe_ingredients.items():
20            for ingredient in ingredients:
21                ingredient_recipes[ingredient].append(recipe_name)
22
23        # convert the mapping of ingredient to recipes to produce the expected
24        # output, shown below, using the ingredient name as a key to group
25        #
26        # name, subtype, docname, anchor, extra, qualifier, description
27        for ingredient, recipe_names in ingredient_recipes.items():
28            for recipe_name in recipe_names:
29                dispname, typ, docname, anchor = recipes[recipe_name]
30                content[ingredient].append((
31                    dispname,
32                    0,
33                    docname,
34                    anchor,
35                    docname,
36                    '',
37                    typ,
38                ))
39
40        # convert the dict to the sorted list of tuples expected
41        content = sorted(content.items())
42
43        return content, True
 1class RecipeIndex(Index):
 2    """A custom index that creates an recipe matrix."""
 3
 4    name = 'recipe'
 5    localname = 'Recipe Index'
 6    shortname = 'Recipe'
 7
 8    def generate(self, docnames=None):
 9        content = defaultdict(list)
10
11        # sort the list of recipes in alphabetical order
12        recipes = self.domain.get_objects()
13        recipes = sorted(recipes, key=lambda recipe: recipe[0])
14
15        # generate the expected output, shown below, from the above using the
16        # first letter of the recipe as a key to group thing
17        #
18        # name, subtype, docname, anchor, extra, qualifier, description
19        for _name, dispname, typ, docname, anchor, _priority in recipes:
20            content[dispname[0].lower()].append((
21                dispname,
22                0,
23                docname,
24                anchor,
25                docname,
26                '',
27                typ,
28            ))
29
30        # convert the dict to the sorted list of tuples expected
31        content = sorted(content.items())
32
33        return content, True

IngredientIndexRecipeIndex 衍生自 Index .它们实现自定义逻辑来生成定义索引的值的多元组。注意 RecipeIndex 是一个只有一个条目的简单索引。扩展它以覆盖更多对象类型还不是代码的一部分。

两个指数都使用该方法 Index.generate() 去做他们的工作。该方法组合来自域的信息,对其进行排序,并以列表结构返回,该结构将被Sphinx接受。这可能看起来很复杂,但实际上只是一个像这样的二元组列表 ('tomato', 'TomatoSoup', 'test', 'rec-TomatoSoup',...) .参阅 domain API guide 有关此API的更多信息。

这些索引页面可以使用 ref 通过结合域名和索引来发挥作用 name 值例如, RecipeIndex 可以参考 :ref:`recipe-recipe 和 ``IngredientIndex` 可以参考 :ref:`recipe-ingredient `.

Sphinx域是一个专用容器,将角色、指令和索引等联系在一起。让我们看看我们在这里创建的域。

 1class RecipeDomain(Domain):
 2    name = 'recipe'
 3    label = 'Recipe Sample'
 4    roles = {
 5        'ref': XRefRole(),
 6    }
 7    directives = {
 8        'recipe': RecipeDirective,
 9    }
10    indices = {
11        RecipeIndex,
12        IngredientIndex,
13    }
14    initial_data = {
15        'recipes': [],  # object list
16        'recipe_ingredients': {},  # name -> object
17    }
18    data_version = 0
19
20    def get_full_qualified_name(self, node):
21        return f'recipe.{node.arguments[0]}'
22
23    def get_objects(self):
24        yield from self.data['recipes']
25
26    def resolve_xref(self, env, fromdocname, builder, typ, target, node, contnode):
27        match = [
28            (docname, anchor)
29            for name, sig, typ, docname, anchor, prio in self.get_objects()
30            if sig == target
31        ]
32
33        if len(match) > 0:
34            todocname = match[0][0]
35            targ = match[0][1]
36
37            return make_refnode(builder, fromdocname, todocname, targ, contnode, targ)
38        else:
39            print('Awww, found nothing')
40            return None
41
42    def add_recipe(self, signature, ingredients):
43        """Add a new recipe to the domain."""
44        name = f'recipe.{signature}'
45        anchor = f'recipe-{signature}'
46
47        self.data['recipe_ingredients'][name] = ingredients
48        # name, dispname, type, docname, anchor, priority
49        self.data['recipes'].append((
50            name,
51            signature,
52            'Recipe',
53            self.env.docname,
54            anchor,
55            0,
56        ))

对此有一些有趣的事情需要注意 recipe 域和一般域。首先,我们实际上通过 directives , rolesindices 属性,而不是通过稍后的呼叫 setup .我们还可以注意到,我们实际上并没有定义自定义角色,而是重新使用 sphinx.roles.XRefRole 角色和定义 sphinx.domains.Domain.resolve_xref 法该方法需要两个参数, typtarget ,引用交叉引用类型及其目标名称。我们将使用 target 从我们的域中解析我们的目的地 recipes 因为我们目前只有一种类型的节点。

继续前进,我们可以看到我们已经定义了 initial_data .中所定义的值 initial_data 将被复制到 env.domaindata[domain_name] 作为域的初始数据,域实例可以通过 self.data .我们看到我们在中定义了两项 initial_data : recipesrecipe_ingredients .每个都包含定义的所有对象(即所有手册)的列表以及将规范成分名称映射到对象列表的哈希。命名对象的方式在我们的扩展中很常见,并且在 get_full_qualified_name 法对于创建的每个对象,规范名称为 recipe.<recipename> ,在哪里 <recipename> 是文档作者给对象的名称(配方)。这使扩展能够使用共享相同名称的不同对象类型。为我们的对象拥有规范的名称和中心位置是一个巨大的优势。我们的索引和交叉引用代码都使用此功能。

setup 功能

As alwayssetup 函数是一个必需项,用于将扩展的各个部分挂钩到Sphinx中。我们看一个 setup 此扩展的功能。

1def setup(app: Sphinx) -> ExtensionMetadata:
2    app.add_domain(RecipeDomain)
3
4    return {
5        'version': '0.1',
6        'parallel_read_safe': True,
7        'parallel_write_safe': True,
8    }

这看起来与我们习惯看到的有点不同。没有电话 add_directive() 或甚至 add_role() .相反,我们只有一个电话, add_domain() 然后对 standard domain .这是因为我们已经将指令、角色和索引注册为指令本身的一部分。

使用扩展

现在,您可以在整个项目中使用该扩展包。例如:

index.rst
Joe's Recipes
=============

Below are a collection of my favourite recipes. I highly recommend the
:recipe:ref:`TomatoSoup` recipe in particular!

.. toctree::

   tomato-soup
tomato-soup.rst
The recipe contains `tomato` and `cilantro`.

.. recipe:recipe:: TomatoSoup
   :contains: tomato, cilantro, salt, pepper

   This recipe is a tasty tomato soup, combine all ingredients
   and cook.

需要注意的重要事情是使用 :recipe:ref: 交叉引用其他地方实际定义的手册的角色(使用 :recipe:recipe: 指令)。

进一步阅读

有关更多信息,请参阅 docutils 文件和 SphinxAPI .

如果您希望跨多个项目或与其他人共享您的扩展,请查看 第三方扩展 科.