| 1 |
.. _tutorial-extend-build: |
| 2 |
|
| 3 |
Extending the build process |
| 4 |
=========================== |
| 5 |
|
| 6 |
The objective of this tutorial is to create a more comprehensive extension than |
| 7 |
that created in :ref:`tutorial-extending-syntax`. |
| 8 |
Whereas that guide just covered writing |
| 9 |
a custom :term:`role` and :term:`directive`, |
| 10 |
this guide covers a more complex extension to the Sphinx build process; |
| 11 |
adding multiple directives, |
| 12 |
along with custom nodes, additional config values and custom event handlers. |
| 13 |
|
| 14 |
To this end, we will cover a ``todo`` extension |
| 15 |
that adds capabilities to include todo entries in the documentation, |
| 16 |
and to collect these in a central place. |
| 17 |
This is similar to the :mod:`sphinx.ext.todo` extension distributed with Sphinx. |
| 18 |
|
| 19 |
Overview |
| 20 |
-------- |
| 21 |
|
| 22 |
.. note:: |
| 23 |
To understand the design of this extension, refer to |
| 24 |
:ref:`important-objects` and :ref:`build-phases`. |
| 25 |
|
| 26 |
We want the extension to add the following to Sphinx: |
| 27 |
|
| 28 |
* A ``todo`` directive, containing some content that is marked with "TODO" and |
| 29 |
only shown in the output if a new config value is set. Todo entries should not |
| 30 |
be in the output by default. |
| 31 |
|
| 32 |
* A ``todolist`` directive that creates a list of all todo entries throughout |
| 33 |
the documentation. |
| 34 |
|
| 35 |
For that, we will need to add the following elements to Sphinx: |
| 36 |
|
| 37 |
* New directives, called ``todo`` and ``todolist``. |
| 38 |
|
| 39 |
* New document tree nodes to represent these directives, conventionally also |
| 40 |
called ``todo`` and ``todolist``. We wouldn't need new nodes if the new |
| 41 |
directives only produced some content representable by existing nodes. |
| 42 |
|
| 43 |
* A new config value ``todo_include_todos`` (config value names should start |
| 44 |
with the extension name, in order to stay unique) that controls whether todo |
| 45 |
entries make it into the output. |
| 46 |
|
| 47 |
* New event handlers: one for the :event:`doctree-resolved` event, to |
| 48 |
replace the todo and todolist nodes, one for :event:`env-merge-info` |
| 49 |
to merge intermediate results from parallel builds, and one for |
| 50 |
:event:`env-purge-doc` (the reason for that will be covered later). |
| 51 |
|
| 52 |
|
| 53 |
Prerequisites |
| 54 |
------------- |
| 55 |
|
| 56 |
As with :ref:`tutorial-extending-syntax`, |
| 57 |
we will not be distributing this plugin via PyPI so |
| 58 |
once again we need a Sphinx project to call this from. You can use an existing |
| 59 |
project or create a new one using :program:`sphinx-quickstart`. |
| 60 |
|
| 61 |
We assume you are using separate source (:file:`source`) and build |
| 62 |
(:file:`build`) folders. Your extension file could be in any folder of your |
| 63 |
project. In our case, let's do the following: |
| 64 |
|
| 65 |
#. Create an :file:`_ext` folder in :file:`source` |
| 66 |
#. Create a new Python file in the :file:`_ext` folder called :file:`todo.py` |
| 67 |
|
| 68 |
Here is an example of the folder structure you might obtain: |
| 69 |
|
| 70 |
.. code-block:: text |
| 71 |
|
| 72 |
└── source |
| 73 |
├── _ext |
| 74 |
│ └── todo.py |
| 75 |
├── _static |
| 76 |
├── conf.py |
| 77 |
├── somefolder |
| 78 |
├── index.rst |
| 79 |
├── somefile.rst |
| 80 |
└── someotherfile.rst |
| 81 |
|
| 82 |
|
| 83 |
Writing the extension |
| 84 |
--------------------- |
| 85 |
|
| 86 |
Open :file:`todo.py` and paste the following code in it, all of which we will |
| 87 |
explain in detail shortly: |
| 88 |
|
| 89 |
.. literalinclude:: examples/todo.py |
| 90 |
:language: python |
| 91 |
:linenos: |
| 92 |
|
| 93 |
This is far more extensive extension than the one detailed in |
| 94 |
:ref:`tutorial-extending-syntax`, |
| 95 |
however, we will will look at each piece step-by-step to explain what's |
| 96 |
happening. |
| 97 |
|
| 98 |
.. rubric:: The node classes |
| 99 |
|
| 100 |
Let's start with the node classes: |
| 101 |
|
| 102 |
.. literalinclude:: examples/todo.py |
| 103 |
:language: python |
| 104 |
:linenos: |
| 105 |
:lines: 8-21 |
| 106 |
|
| 107 |
Node classes usually don't have to do anything except inherit from the standard |
| 108 |
docutils classes defined in :mod:`docutils.nodes`. ``todo`` inherits from |
| 109 |
``Admonition`` because it should be handled like a note or warning, ``todolist`` |
| 110 |
is just a "general" node. |
| 111 |
|
| 112 |
.. note:: |
| 113 |
|
| 114 |
Many extensions will not have to create their own node classes and work fine |
| 115 |
with the nodes already provided by `docutils |
| 116 |
<https://docutils.sourceforge.io/docs/ref/doctree.html>`__ and :ref:`Sphinx |
| 117 |
<nodes>`. |
| 118 |
|
| 119 |
.. attention:: |
| 120 |
|
| 121 |
It is important to know that while you can extend Sphinx without |
| 122 |
leaving your ``conf.py``, if you declare an inherited node right |
| 123 |
there, you'll hit an unobvious :py:class:`~pickle.PickleError`. So if |
| 124 |
something goes wrong, please make sure that you put inherited nodes |
| 125 |
into a separate Python module. |
| 126 |
|
| 127 |
For more details, see: |
| 128 |
|
| 129 |
- https://github.com/sphinx-doc/sphinx/issues/6751 |
| 130 |
- https://github.com/sphinx-doc/sphinx/issues/1493 |
| 131 |
- https://github.com/sphinx-doc/sphinx/issues/1424 |
| 132 |
|
| 133 |
.. rubric:: The directive classes |
| 134 |
|
| 135 |
A directive class is a class deriving usually from |
| 136 |
:class:`docutils.parsers.rst.Directive`. The directive interface is also |
| 137 |
covered in detail in the `docutils documentation`_; the important thing is that |
| 138 |
the class should have attributes that configure the allowed markup, and a |
| 139 |
``run`` method that returns a list of nodes. |
| 140 |
|
| 141 |
Looking first at the ``TodolistDirective`` directive: |
| 142 |
|
| 143 |
.. literalinclude:: examples/todo.py |
| 144 |
:language: python |
| 145 |
:linenos: |
| 146 |
:pyobject: TodolistDirective |
| 147 |
|
| 148 |
It's very simple, creating and returning an instance of our ``todolist`` node |
| 149 |
class. The ``TodolistDirective`` directive itself has neither content nor |
| 150 |
arguments that need to be handled. That brings us to the ``TodoDirective`` |
| 151 |
directive: |
| 152 |
|
| 153 |
.. literalinclude:: examples/todo.py |
| 154 |
:language: python |
| 155 |
:linenos: |
| 156 |
:pyobject: TodoDirective |
| 157 |
|
| 158 |
Several important things are covered here. First, as you can see, we're now |
| 159 |
subclassing the :class:`~sphinx.util.docutils.SphinxDirective` helper class |
| 160 |
instead of the usual :class:`~docutils.parsers.rst.Directive` class. This |
| 161 |
gives us access to the :ref:`build environment instance <important-objects>` |
| 162 |
using the ``self.env`` property. Without this, we'd have to use the rather |
| 163 |
convoluted ``self.state.document.settings.env``. Then, to act as a link target |
| 164 |
(from ``TodolistDirective``), the ``TodoDirective`` directive needs to return a |
| 165 |
target node in addition to the ``todo`` node. The target ID (in HTML, this will |
| 166 |
be the anchor name) is generated by using ``env.new_serialno`` which returns a |
| 167 |
new unique integer on each call and therefore leads to unique target names. The |
| 168 |
target node is instantiated without any text (the first two arguments). |
| 169 |
|
| 170 |
On creating admonition node, the content body of the directive are parsed using |
| 171 |
``self.parse_content_to_nodes()``. |
| 172 |
Following this, the ``todo`` node is added to the environment. |
| 173 |
This is needed to be able to create a list of all todo entries throughout |
| 174 |
the documentation, in the place where the author puts a ``todolist`` directive. |
| 175 |
For this case, the environment attribute ``todo_all_todos`` is used |
| 176 |
(again, the name should be unique, so it is prefixed by the extension name). |
| 177 |
It does not exist when a new environment is created, so the directive must |
| 178 |
check and create it if necessary. |
| 179 |
Various information about the todo entry's location are stored along with |
| 180 |
a copy of the node. |
| 181 |
|
| 182 |
In the last line, the nodes that should be put into the doctree are returned: |
| 183 |
the target node and the admonition node. |
| 184 |
|
| 185 |
The node structure that the directive returns looks like this:: |
| 186 |
|
| 187 |
+--------------------+ |
| 188 |
| target node | |
| 189 |
+--------------------+ |
| 190 |
+--------------------+ |
| 191 |
| todo node | |
| 192 |
+--------------------+ |
| 193 |
\__+--------------------+ |
| 194 |
| admonition title | |
| 195 |
+--------------------+ |
| 196 |
| paragraph | |
| 197 |
+--------------------+ |
| 198 |
| ... | |
| 199 |
+--------------------+ |
| 200 |
|
| 201 |
.. rubric:: The event handlers |
| 202 |
|
| 203 |
Event handlers are one of Sphinx's most powerful features, providing a way to |
| 204 |
do hook into any part of the documentation process. There are many events |
| 205 |
provided by Sphinx itself, as detailed in :ref:`the API guide <events>`, and |
| 206 |
we're going to use a subset of them here. |
| 207 |
|
| 208 |
Let's look at the event handlers used in the above example. First, the one for |
| 209 |
the :event:`env-purge-doc` event: |
| 210 |
|
| 211 |
.. literalinclude:: examples/todo.py |
| 212 |
:language: python |
| 213 |
:linenos: |
| 214 |
:pyobject: purge_todos |
| 215 |
|
| 216 |
Since we store information from source files in the environment, which is |
| 217 |
persistent, it may become out of date when the source file changes. Therefore, |
| 218 |
before each source file is read, the environment's records of it are cleared, |
| 219 |
and the :event:`env-purge-doc` event gives extensions a chance to do the same. |
| 220 |
Here we clear out all todos whose docname matches the given one from the |
| 221 |
``todo_all_todos`` list. If there are todos left in the document, they will be |
| 222 |
added again during parsing. |
| 223 |
|
| 224 |
The next handler, for the :event:`env-merge-info` event, is used |
| 225 |
during parallel builds. As during parallel builds all threads have |
| 226 |
their own ``env``, there's multiple ``todo_all_todos`` lists that need |
| 227 |
to be merged: |
| 228 |
|
| 229 |
.. literalinclude:: examples/todo.py |
| 230 |
:language: python |
| 231 |
:linenos: |
| 232 |
:pyobject: merge_todos |
| 233 |
|
| 234 |
|
| 235 |
The other handler belongs to the :event:`doctree-resolved` event: |
| 236 |
|
| 237 |
.. literalinclude:: examples/todo.py |
| 238 |
:language: python |
| 239 |
:linenos: |
| 240 |
:pyobject: process_todo_nodes |
| 241 |
|
| 242 |
The :event:`doctree-resolved` event is emitted for each document that is |
| 243 |
about to be written at the end of :ref:`phase 3 (resolving) <build-phases>` |
| 244 |
and allows custom resolving to be done on that document. |
| 245 |
The handler we have written for this event is a bit more involved. |
| 246 |
If the ``todo_include_todos`` config value (which we'll describe shortly) is false, |
| 247 |
all ``todo`` and ``todolist`` nodes are removed from the documents. If not, |
| 248 |
``todo`` nodes just stay where and how they are. ``todolist`` nodes are |
| 249 |
replaced by a list of todo entries, complete with backlinks to the location |
| 250 |
where they come from. The list items are composed of the nodes from the |
| 251 |
``todo`` entry and docutils nodes created on the fly: a paragraph for each |
| 252 |
entry, containing text that gives the location, and a link (reference node |
| 253 |
containing an italic node) with the backreference. The reference URI is built |
| 254 |
by :meth:`sphinx.builders.Builder.get_relative_uri` which creates a suitable |
| 255 |
URI depending on the used builder, and appending the todo node's (the target's) |
| 256 |
ID as the anchor name. |
| 257 |
|
| 258 |
.. rubric:: The ``setup`` function |
| 259 |
|
| 260 |
.. currentmodule:: sphinx.application |
| 261 |
|
| 262 |
As noted :ref:`previously <tutorial-extending-syntax>`, |
| 263 |
the ``setup`` function is a requirement |
| 264 |
and is used to plug directives into Sphinx. However, we also use it to hook up |
| 265 |
the other parts of our extension. Let's look at our ``setup`` function: |
| 266 |
|
| 267 |
.. literalinclude:: examples/todo.py |
| 268 |
:language: python |
| 269 |
:linenos: |
| 270 |
:pyobject: setup |
| 271 |
|
| 272 |
The calls in this function refer to the classes and functions we added earlier. |
| 273 |
What the individual calls do is the following: |
| 274 |
|
| 275 |
* :meth:`~Sphinx.add_config_value` lets Sphinx know that it should recognize the |
| 276 |
new *config value* ``todo_include_todos``, whose default value is ``False`` |
| 277 |
(which also tells Sphinx that it is a boolean value). |
| 278 |
|
| 279 |
If the third argument was ``'html'``, HTML documents would be fully rebuilt |
| 280 |
if the config value changed its value. This is needed for config values that |
| 281 |
influence reading (build :ref:`phase 1 (reading) <build-phases>`). |
| 282 |
|
| 283 |
* :meth:`~Sphinx.add_node` adds a new *node class* to the build system. It also |
| 284 |
can specify visitor functions for each supported output format. These visitor |
| 285 |
functions are needed when the new nodes stay until :ref:`phase 4 (writing) |
| 286 |
<build-phases>`. Since the ``todolist`` node is always replaced in |
| 287 |
:ref:`phase 3 (resolving) <build-phases>`, it doesn't need any. |
| 288 |
|
| 289 |
* :meth:`~Sphinx.add_directive` adds a new *directive*, given by name and class. |
| 290 |
|
| 291 |
* Finally, :meth:`~Sphinx.connect` adds an *event handler* to the event whose |
| 292 |
name is given by the first argument. The event handler function is called |
| 293 |
with several arguments which are documented with the event. |
| 294 |
|
| 295 |
With this, our extension is complete. |
| 296 |
|
| 297 |
|
| 298 |
Using the extension |
| 299 |
------------------- |
| 300 |
|
| 301 |
As before, we need to enable the extension by declaring it in our |
| 302 |
:file:`conf.py` file. There are two steps necessary here: |
| 303 |
|
| 304 |
#. Add the :file:`_ext` directory to the `Python path`_ using |
| 305 |
``sys.path.append``. This should be placed at the top of the file. |
| 306 |
|
| 307 |
#. Update or create the :confval:`extensions` list and add the extension file |
| 308 |
name to the list |
| 309 |
|
| 310 |
In addition, we may wish to set the ``todo_include_todos`` config value. As |
| 311 |
noted above, this defaults to ``False`` but we can set it explicitly. |
| 312 |
|
| 313 |
For example: |
| 314 |
|
| 315 |
.. code-block:: python |
| 316 |
|
| 317 |
import sys |
| 318 |
from pathlib import Path |
| 319 |
|
| 320 |
sys.path.append(str(Path('_ext').resolve())) |
| 321 |
|
| 322 |
extensions = ['todo'] |
| 323 |
|
| 324 |
todo_include_todos = False |
| 325 |
|
| 326 |
You can now use the extension throughout your project. For example: |
| 327 |
|
| 328 |
.. code-block:: rst |
| 329 |
:caption: index.rst |
| 330 |
|
| 331 |
Hello, world |
| 332 |
============ |
| 333 |
|
| 334 |
.. toctree:: |
| 335 |
somefile.rst |
| 336 |
someotherfile.rst |
| 337 |
|
| 338 |
Hello world. Below is the list of TODOs. |
| 339 |
|
| 340 |
.. todolist:: |
| 341 |
|
| 342 |
.. code-block:: rst |
| 343 |
:caption: somefile.rst |
| 344 |
|
| 345 |
foo |
| 346 |
=== |
| 347 |
|
| 348 |
Some intro text here... |
| 349 |
|
| 350 |
.. todo:: Fix this |
| 351 |
|
| 352 |
.. code-block:: rst |
| 353 |
:caption: someotherfile.rst |
| 354 |
|
| 355 |
bar |
| 356 |
=== |
| 357 |
|
| 358 |
Some more text here... |
| 359 |
|
| 360 |
.. todo:: Fix that |
| 361 |
|
| 362 |
Because we have configured ``todo_include_todos`` to ``False``, we won't |
| 363 |
actually see anything rendered for the ``todo`` and ``todolist`` directives. |
| 364 |
However, if we toggle this to true, we will see the output described |
| 365 |
previously. |
| 366 |
|
| 367 |
|
| 368 |
Further reading |
| 369 |
--------------- |
| 370 |
|
| 371 |
For more information, refer to the `docutils`_ documentation and |
| 372 |
:doc:`/extdev/index`. |
| 373 |
|
| 374 |
If you wish to share your extension across multiple projects or with others, |
| 375 |
check out the :ref:`third-party-extensions` section. |
| 376 |
|
| 377 |
|
| 378 |
.. _docutils: https://docutils.sourceforge.io/docs/ |
| 379 |
.. _Python path: https://docs.python.org/3/using/cmdline.html#envvar-PYTHONPATH |
| 380 |
.. _docutils documentation: https://docutils.sourceforge.io/docs/ref/rst/directives.html |