Debian Codegraph @

doc/extdev/index.rst

raw
1 .. _dev-extensions:
2
3 Sphinx API
4 ==========
5
6 Since many projects will need special features in their documentation, Sphinx
7 is designed to be extensible on several levels.
8
9 Here are a few things you can do in an extension:
10
11 * Add new :term:`builder`\s to support new output formats or actions on the
12 parsed documents.
13 * Register custom reStructuredText roles and directives, extending the markup
14 using the :doc:`markupapi`.
15 * Add custom code to so-called "hook points" at strategic places throughout the
16 build process, allowing you to register a hook and run specialized code.
17 For example, see the :ref:`events`.
18
19 An extension is simply a Python module with a ``setup()`` function. A user
20 activates the extension by placing the extension's module name
21 (or a sub-module) in their :confval:`extensions` configuration value.
22
23 When :program:`sphinx-build` is executed, Sphinx will attempt to import each
24 module that is listed, and execute ``yourmodule.setup(app)``. This
25 function is used to prepare the extension (e.g., by executing Python code),
26 linking resources that Sphinx uses in the build process (like CSS or HTML
27 files), and notifying Sphinx of everything the extension offers (such
28 as directive or role definitions). The ``app`` argument is an instance of
29 :class:`.Sphinx` and gives you control over most aspects of the Sphinx build.
30
31 .. note::
32
33 The configuration file itself can be treated as an extension if it
34 contains a ``setup()`` function. All other extensions to load must be
35 listed in the :confval:`extensions` configuration value.
36
37 The rest of this page describes some high-level aspects of developing
38 extensions and various parts of Sphinx's behavior that you can control.
39 For some examples of how extensions can be built and used to control different
40 parts of Sphinx, see the :ref:`extension-tutorials-index`.
41
42 .. _important-objects:
43
44 Important objects
45 -----------------
46
47 There are several key objects whose API you will use while writing an
48 extension. These are:
49
50 **Application**
51 The application object (usually called ``app``) is an instance of
52 :class:`.Sphinx`.
53 It controls most high-level functionality, such as loading config,
54 initialising the environment, and the setup of extensions.
55
56 **Environment**
57 The build environment object (usually called ``env``) is an instance of
58 :class:`.BuildEnvironment`. It is responsible for parsing the source
59 documents, stores all metadata about the document collection and is
60 serialized to disk after each build.
61
62 Its API provides methods to do with access to metadata, resolving references,
63 etc. It can also be used by extensions to cache information that should
64 persist for incremental rebuilds.
65
66 If you have the application or builder object, the environment is available
67 as ``app.env`` or ``builder.env``.
68 In :class:`.SphinxDirective`, :class:`.SphinxRole`, or :class:`.SphinxTransform`
69 subclasses, the environment is available as ``self.env``.
70
71 **Builder**
72 The builder object (usually called ``builder``) is an instance of a specific
73 subclass of :class:`.Builder`. Each builder class knows how to convert the
74 parsed documents into an output format, or otherwise process them (e.g. check
75 external links).
76
77 If you have the application object, the builder is available as
78 ``app.builder``.
79
80 **Config**
81 The config object (usually called ``config``) provides the values of
82 configuration values set in :file:`conf.py` as attributes. It is an instance
83 of :class:`.Config`.
84
85 The config is available as ``env.config``, ``builder.config``, or ``app.config``.
86 In :class:`.SphinxDirective`, :class:`.SphinxRole`, or :class:`.SphinxTransform`
87 subclasses, the environment is available as ``self.config``.
88
89 **Events**
90 The event manager object (usually called ``events``) manages and dispatches
91 Sphinx's events system.
92 It is an instance of :class:`.EventManager`.
93
94 The event manager is available as ``env.events``, ``builder.events``,
95 or ``app.events``.
96
97 To see an example of use of these objects, refer to
98 :ref:`the tutorials <extension-tutorials-index>`.
99
100 .. _build-phases:
101
102 Build phases
103 ------------
104
105 One thing that is vital in order to understand extension mechanisms is the way
106 in which a Sphinx project is built: this works in several phases.
107
108 .. graphviz:: /_static/diagrams/sphinx_build_phases.dot
109 :caption: Build phases
110
111 **Phase 0: Initialization**
112
113 In this phase, almost nothing of interest to us happens. The source
114 directory is searched for source files, and extensions are initialized.
115 Should a stored build environment exist, it is loaded, otherwise a new one is
116 created.
117
118 **Phase 1: Reading**
119
120 In Phase 1, all source files (and on subsequent builds, those that are new or
121 changed) are read and parsed. This is the phase where directives and roles
122 are encountered by docutils, and the corresponding code is executed. The
123 output of this phase is a *doctree* for each source file; that is a tree of
124 docutils nodes. For document elements that aren't fully known until all
125 existing files are read, temporary nodes are created.
126
127 There are nodes provided by docutils, which are documented `in the docutils
128 documentation <https://docutils.sourceforge.io/docs/ref/doctree.html>`__.
129 Additional nodes are provided by Sphinx and :ref:`documented here <nodes>`.
130
131 During reading, the build environment is updated with all meta- and cross
132 reference data of the read documents, such as labels, the names of headings,
133 described Python objects and index entries. This will later be used to
134 replace the temporary nodes.
135
136 The parsed doctrees are stored on the disk, because it is not possible to
137 hold all of them in memory.
138
139 **Phase 2: Consistency checks**
140
141 Some checking is done to ensure no surprises in the built documents.
142
143 **Phase 3: Resolving**
144
145 Now that the metadata and cross-reference data of all existing documents is
146 known, all temporary nodes are replaced by nodes that can be converted into
147 output using components called transforms. For example, links are created
148 for object references that exist, and simple literal nodes are created for
149 those that don't.
150
151 **Phase 4: Writing**
152
153 This phase converts the resolved doctrees to the desired output format, such
154 as HTML or LaTeX. This happens via a so-called docutils writer that visits
155 the individual nodes of each doctree and produces some output in the process.
156
157 .. note::
158
159 Some builders deviate from this general build plan, for example, the builder
160 that checks external links does not need anything more than the parsed
161 doctrees and therefore does not have phases 2--4.
162
163 To see an example of application, refer to :ref:`tutorial-extend-build`.
164
165 .. _ext-metadata:
166
167 Extension metadata
168 ------------------
169
170 .. versionadded:: 1.3
171
172 The ``setup()`` function should return a dictionary.
173 This is treated by Sphinx as metadata of the extension.
174 Metadata keys currently recognized are:
175
176 ``'version'``
177 A string that identifies the extension version.
178 It is used for extension version requirement checking
179 (see :confval:`needs_extensions`) and informational purposes.
180 If no version string is returned, ``'unknown version'`` is used by default.
181
182 ``'env_version'``
183 A non-zero positive integer integer that records
184 the version of data stored in the environment by the extension.
185
186 .. attention::
187 If ``'env_version'`` is not set, the extension **must not**
188 store any data or state directly on the environment object (``env``).
189
190 This key must be defined if the extension uses the ``env`` object to store data.
191 The version number must be incremented whenever the type, structure, or meaning
192 of the stored data change, to ensure Sphinx does not try and load invalid data
193 from a cached environment.
194
195 .. versionadded:: 1.8
196
197 ``'parallel_read_safe'``
198 A boolean that specifies if parallel reading of source files
199 can be used when the extension is loaded.
200 It defaults to ``False``, meaning that you have to explicitly specify
201 your extension to be safe for parallel reading after checking that it is.
202
203 .. important::
204
205 When *parallel-read-safe* is ``True``,
206 the extension must satisfy the following conditions:
207
208 * The core logic of the extension is parallelly executable during
209 the reading phase.
210 * It has event handlers for :event:`env-merge-info` and
211 :event:`env-purge-doc` events if it stores data to the build
212 environment object (``env``) during the reading phase.
213
214 ``'parallel_write_safe'``
215 A boolean that specifies if parallel writing of output files
216 can be used when the extension is loaded.
217 Since extensions usually don't negatively influence the process,
218 this defaults to ``True``.
219
220 .. important::
221
222 When *parallel-write-safe* is ``True``,
223 the extension must satisfy the following conditions:
224
225 * The core logic of the extension is parallelly executable during
226 the writing phase.
227
228
229 APIs used for writing extensions
230 --------------------------------
231
232 These sections provide a more complete description of the tools at your
233 disposal when developing Sphinx extensions. Some are core to Sphinx
234 (such as the :doc:`appapi`) while others trigger specific behavior
235 (such as the :doc:`i18n`)
236
237 .. toctree::
238 :maxdepth: 2
239
240 appapi
241 event_callbacks
242 projectapi
243 envapi
244 builderapi
245 eventapi
246 collectorapi
247 markupapi
248 domainapi
249 parserapi
250 nodes
251 logging
252 i18n
253 utils
254 testing
255 deprecated