Debian Codegraph @

doc/development/tutorials/adding_domain.rst

raw
1 .. _tutorial-adding-domain:
2
3 Adding a reference domain
4 =========================
5
6 The objective of this tutorial is to illustrate roles, directives and domains.
7 Once complete, we will be able to use this extension to describe a recipe and
8 reference that recipe from elsewhere in our documentation.
9
10 .. note::
11
12 This tutorial is based on a guide first published on `opensource.com`_ and
13 is provided here with the original author's permission.
14
15 .. _opensource.com: https://opensource.com/article/18/11/building-custom-workflows-sphinx
16
17
18 Overview
19 --------
20
21 We want the extension to add the following to Sphinx:
22
23 * A ``recipe`` :term:`directive`, containing some content describing the recipe
24 steps, along with a ``:contains:`` option highlighting the main ingredients
25 of the recipe.
26
27 * A ``ref`` :term:`role`, which provides a cross-reference to the recipe
28 itself.
29
30 * A ``recipe`` :term:`domain`, which allows us to tie together the above role
31 and domain, along with things like indices.
32
33 For that, we will need to add the following elements to Sphinx:
34
35 * A new directive called ``recipe``
36
37 * New indexes to allow us to reference ingredient and recipes
38
39 * A new domain called ``recipe``, which will contain the ``recipe`` directive
40 and ``ref`` role
41
42
43 Prerequisites
44 -------------
45
46 We need the same setup as in
47 :ref:`the previous extensions <tutorial-extend-build>`.
48 This time,
49 we will be putting out extension in a file called :file:`recipe.py`.
50
51 Here is an example of the folder structure you might obtain:
52
53 .. code-block:: text
54
55 └── source
56    ├── _ext
57 │   └── recipe.py
58    ├── conf.py
59    └── index.rst
60
61
62 Writing the extension
63 ---------------------
64
65 Open :file:`recipe.py` and paste the following code in it, all of which we will
66 explain in detail shortly:
67
68 .. literalinclude:: examples/recipe.py
69 :language: python
70 :linenos:
71
72 Let's look at each piece of this extension step-by-step to explain what's going
73 on.
74
75 .. rubric:: The directive class
76
77 The first thing to examine is the ``RecipeDirective`` directive:
78
79 .. literalinclude:: examples/recipe.py
80 :language: python
81 :linenos:
82 :pyobject: RecipeDirective
83
84 Unlike :ref:`tutorial-extending-syntax` and :ref:`tutorial-extend-build`,
85 this directive doesn't derive from
86 :class:`docutils.parsers.rst.Directive` and doesn't define a ``run`` method.
87 Instead, it derives from :class:`sphinx.directives.ObjectDescription` and
88 defines ``handle_signature`` and ``add_target_and_index`` methods. This is
89 because ``ObjectDescription`` is a special-purpose directive that's intended
90 for describing things like classes, functions, or, in our case, recipes. More
91 specifically, ``handle_signature`` implements parsing the signature of the
92 directive and passes on the object's name and type to its superclass, while
93 ``add_target_and_index`` adds a target (to link to) and an entry to the index
94 for this node.
95
96 We also see that this directive defines ``has_content``, ``required_arguments``
97 and ``option_spec``. Unlike the ``TodoDirective`` directive added in the
98 :ref:`previous tutorial <tutorial-extend-build>`,
99 this directive takes a single argument,
100 the recipe name, and an option, ``contains``,
101 in addition to the nested reStructuredText in the body.
102
103 .. rubric:: The index classes
104
105 .. currentmodule:: sphinx.domains
106
107 .. todo:: Add brief overview of indices
108
109 .. literalinclude:: examples/recipe.py
110 :language: python
111 :linenos:
112 :pyobject: IngredientIndex
113
114 .. literalinclude:: examples/recipe.py
115 :language: python
116 :linenos:
117 :pyobject: RecipeIndex
118
119 Both ``IngredientIndex`` and ``RecipeIndex`` are derived from :class:`Index`.
120 They implement custom logic to generate a tuple of values that define the
121 index. Note that ``RecipeIndex`` is a simple index that has only one entry.
122 Extending it to cover more object types is not yet part of the code.
123
124 Both indices use the method :meth:`Index.generate` to do their work. This
125 method combines the information from our domain, sorts it, and returns it in a
126 list structure that will be accepted by Sphinx. This might look complicated but
127 all it really is is a list of tuples like ``('tomato', 'TomatoSoup', 'test',
128 'rec-TomatoSoup',...)``. Refer to the :doc:`domain API guide
129 </extdev/domainapi>` for more information on this API.
130
131 These index pages can be referenced with the :rst:role:`ref` role by combining
132 the domain name and the index ``name`` value. For example, ``RecipeIndex`` can be
133 referenced with ``:ref:`recipe-recipe``` and ``IngredientIndex`` can be referenced
134 with ``:ref:`recipe-ingredient```.
135
136 .. rubric:: The domain
137
138 A Sphinx domain is a specialized container that ties together roles,
139 directives, and indices, among other things. Let's look at the domain we're
140 creating here.
141
142 .. literalinclude:: examples/recipe.py
143 :language: python
144 :linenos:
145 :pyobject: RecipeDomain
146
147 There are some interesting things to note about this ``recipe`` domain and domains
148 in general. Firstly, we actually register our directives, roles and indices
149 here, via the ``directives``, ``roles`` and ``indices`` attributes, rather than
150 via calls later on in ``setup``. We can also note that we aren't actually
151 defining a custom role and are instead reusing the
152 :class:`sphinx.roles.XRefRole` role and defining the
153 :class:`sphinx.domains.Domain.resolve_xref` method. This method takes two
154 arguments, ``typ`` and ``target``, which refer to the cross-reference type and
155 its target name. We'll use ``target`` to resolve our destination from our
156 domain's ``recipes`` because we currently have only one type of node.
157
158 Moving on, we can see that we've defined ``initial_data``. The values defined in
159 ``initial_data`` will be copied to ``env.domaindata[domain_name]`` as the
160 initial data of the domain, and domain instances can access it via
161 ``self.data``. We see that we have defined two items in ``initial_data``:
162 ``recipes`` and ``recipe_ingredients``. Each contains a list of all objects
163 defined (i.e. all recipes) and a hash that maps a canonical ingredient name to
164 the list of objects. The way we name objects is common across our extension and
165 is defined in the ``get_full_qualified_name`` method. For each object created,
166 the canonical name is ``recipe.<recipename>``, where ``<recipename>`` is the
167 name the documentation writer gives the object (a recipe). This enables the
168 extension to use different object types that share the same name. Having a
169 canonical name and central place for our objects is a huge advantage. Both our
170 indices and our cross-referencing code use this feature.
171
172 .. rubric:: The ``setup`` function
173
174 .. currentmodule:: sphinx.application
175
176 :ref:`As always <tutorial-extend-build>`,
177 the ``setup`` function is a requirement and is used to
178 hook the various parts of our extension into Sphinx. Let's look at the
179 ``setup`` function for this extension.
180
181 .. literalinclude:: examples/recipe.py
182 :language: python
183 :linenos:
184 :pyobject: setup
185
186 This looks a little different to what we're used to seeing. There are no calls
187 to :meth:`~Sphinx.add_directive` or even :meth:`~Sphinx.add_role`. Instead, we
188 have a single call to :meth:`~Sphinx.add_domain` followed by some
189 initialization of the :doc:`standard domain </usage/domains/standard>`.
190 This is because we had already registered our directives,
191 roles and indexes as part of the directive itself.
192
193
194 Using the extension
195 -------------------
196
197 You can now use the extension throughout your project. For example:
198
199 .. code-block:: rst
200 :caption: index.rst
201
202 Joe's Recipes
203 =============
204
205 Below are a collection of my favourite recipes. I highly recommend the
206 :recipe:ref:`TomatoSoup` recipe in particular!
207
208 .. toctree::
209
210 tomato-soup
211
212 .. code-block:: rst
213 :caption: tomato-soup.rst
214
215 The recipe contains `tomato` and `cilantro`.
216
217 .. recipe:recipe:: TomatoSoup
218 :contains: tomato, cilantro, salt, pepper
219
220 This recipe is a tasty tomato soup, combine all ingredients
221 and cook.
222
223 The important things to note are the use of the ``:recipe:ref:`` role to
224 cross-reference the recipe actually defined elsewhere (using the
225 ``:recipe:recipe:`` directive).
226
227
228 Further reading
229 ---------------
230
231 For more information, refer to the `docutils`_ documentation and
232 :doc:`/extdev/index`.
233
234 If you wish to share your extension across multiple projects or with others,
235 check out the :ref:`third-party-extensions` section.
236
237 .. _docutils: https://docutils.sourceforge.io/docs/