添加参考域¶
本教程的目标是说明角色、指令和领域.一旦完成,我们将能够使用该扩展来描述一个食谱,并在文档的其他地方引用该食谱.
备注
本教程基于在 opensource.com 上首次发布的指南,现经过原作者许可在此提供.
概述¶
我们希望扩展为 Sphinx 添加以下内容:
一个
recipe
指令 ,包含了一些描述食谱步骤的内容,以及一个:contains:
选项,突出显示食谱的主要成分.A
ref
role ,提供了对该食谱本身的交叉引用.一个
recipe
domain ,它允许我们将以上角色和域结合在一起,以及诸如索引之类的东西.
为此,我们需要将以下元素添加到Sphinx:
一个新的指令叫做
recipe
新的索引以便我们引用成分和食谱
一个新的域叫做
recipe
,将包含recipe
指令和ref
角色
前提条件¶
我们需要与 前面的扩展 相同的设置.这一次,我们将把扩展放在一个名为 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_signature
和 add_target_and_index
方法.这是因为 ObjectDescription
是一种特殊用途的指令,旨在描述类、函数或在我们案例中的食谱.更具体地说, handle_signature
实现了解析指令的签名,并将对象的名称和类型传递给它的超类,而 add_target_and_index
为此节点添加一个目标(用于链接)和一个索引项.
我们还看到该指令定义了 has_content
, required_arguments
和 option_spec
.与在 previous tutorial 中添加的 TodoDirective
指令不同,该指令接受一个参数,即配方名称,以及一个选项 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
两个 IngredientIndex
和 RecipeIndex
都是从 Index
派生的.它们实现了自定义逻辑以生成一个值元组来定义索引.请注意, RecipeIndex
是一个简单的索引,仅具有一个条目.目前尚未扩展为涵盖更多对象类型.
这两个索引都使用 Index.generate()
方法来完成它们的工作.该方法结合了我们领域的信息,对其进行排序,并以 Sphinx 所接受的列表结构返回.这看起来可能很复杂,但它实际上只是一个元组的列表,如 ('tomato', 'TomatoSoup', 'test', 'rec-TomatoSoup',...)
.有关此 API 的更多信息,请参阅 domain API guide .
这些索引页面可以通过结合域名和索引 name
值,使用 ref
角色进行引用.例如, 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
、 roles
和 indices
属性,而不是在 setup
中稍后的调用.我们还可以注意到,我们并没有定义一个自定义角色,而是重复使用了 sphinx.roles.XRefRole
角色,并定义了 sphinx.domains.Domain.resolve_xref
方法.该方法接受两个参数, typ
和 target
,分别指代交叉引用类型及其目标名称.我们将使用 target
来从我们领域的 recipes
中解析目的地,因为我们目前只有一种类型的节点.
接下来,我们可以看到我们已经定义了 initial_data
.在 initial_data
中定义的值将被复制到 env.domaindata[domain_name]
作为域的初始数据,域实例可以通过 self.data
访问它.我们看到在 initial_data
中定义了两个项目: recipes
和 recipe_ingredients
.每个项目包含了所有定义对象(即所有食谱)的列表和一个哈希表,用于将标准成分名称映射到对象列表.我们为对象命名的方式在我们的扩展中是通用的,并在 get_full_qualified_name
方法中定义.对于每个创建的对象,标准名称为 recipe.<recipename>
,其中 <recipename>
是文档编写者给该对象(一个食谱)指定的名称.这使得扩展可以使用不同类型但共享相同名称的对象.拥有一个标准名称和对象的集中管理是一个巨大的优势.我们的索引和交叉引用代码都使用了这一特性.
The setup
function
一如既往 , setup
函数是一个必要条件,用于将我们扩展的各个部分挂钩到 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()
的单一调用,后面是对 标准域 的一些初始化.这是因为我们已将我们的指令、角色和索引作为指令本身的一部分进行注册.
使用扩展¶
您现在可以在整个项目中使用该扩展.例如:
Joe's Recipes
=============
Below are a collection of my favourite recipes. I highly recommend the
:recipe:ref:`TomatoSoup` recipe in particular!
.. toctree::
tomato-soup
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 文档和 Sphinx API .
如果您希望在多个项目之间或与其他人共享您的扩展,请查看 第三方扩展 部分.