6
.. module:: sphinx.application
7
:synopsis: Application class and extensibility interface.
10
Each Sphinx extension is a Python module with at least a :func:`setup` function.
11
This function is called at initialization time with one argument, the
12
application object representing the Sphinx process.
16
This application object has the public API described in the following.
21
These methods are usually called in an extension's ``setup()`` function.
23
Examples of using the Sphinx extension API can be seen in the :mod:`sphinx.ext`
26
.. method:: Sphinx.setup_extension(name)
28
Load the extension given by the module *name*. Use this if your extension
29
needs the features provided by another extension.
31
.. method:: Sphinx.add_builder(builder)
33
Register a new builder. *builder* must be a class that inherits from
34
:class:`~sphinx.builders.Builder`.
36
.. method:: Sphinx.add_config_value(name, default, rebuild)
38
Register a configuration value. This is necessary for Sphinx to recognize
39
new values and set default values accordingly. The *name* should be prefixed
40
with the extension name, to avoid clashes. The *default* value can be any
41
Python object. The string value *rebuild* must be one of those values:
43
* ``'env'`` if a change in the setting only takes effect when a document is
44
parsed -- this means that the whole environment must be rebuilt.
45
* ``'html'`` if a change in the setting needs a full rebuild of HTML
47
* ``''`` if a change in the setting will not need any special rebuild.
49
.. versionchanged:: 0.4
50
If the *default* value is a callable, it will be called with the config
51
object as its argument in order to get the default value. This can be
52
used to implement config values whose default depends on other values.
54
.. versionchanged:: 0.6
55
Changed *rebuild* from a simple boolean (equivalent to ``''`` or
56
``'env'``) to a string. However, booleans are still accepted and
59
.. method:: Sphinx.add_domain(domain)
61
Make the given *domain* (which must be a class; more precisely, a subclass of
62
:class:`~sphinx.domains.Domain`) known to Sphinx.
66
.. method:: Sphinx.override_domain(domain)
68
Make the given *domain* class known to Sphinx, assuming that there is already
69
a domain with its ``.name``. The new domain must be a subclass of the
74
.. method:: Sphinx.add_index_to_domain(domain, index)
76
Add a custom *index* class to the domain named *domain*. *index* must be a
77
subclass of :class:`~sphinx.domains.Index`.
81
.. method:: Sphinx.add_event(name)
83
Register an event called *name*. This is needed to be able to emit it.
85
.. method:: Sphinx.set_translator(name, translator_class)
87
Register or override a Docutils translator class. This is used to register
88
a custom output translator or to replace a builtin translator.
89
This allows extensions to use custom translator and define custom
90
nodes for the translator (see :meth:`add_node`).
92
This is a API version of :confval:`html_translator_class` for all other
93
builders. Note that if :confval:`html_translator_class` is specified and
94
this API is called for html related builders, API overriding takes
99
.. method:: Sphinx.add_node(node, **kwds)
101
Register a Docutils node class. This is necessary for Docutils internals.
102
It may also be used in the future to validate nodes in the parsed documents.
104
Node visitor functions for the Sphinx HTML, LaTeX, text and manpage writers
105
can be given as keyword arguments: the keyword should be one or more of
106
``'html'``, ``'latex'``, ``'text'``, ``'man'``, ``'texinfo'`` or any other
107
supported translators, the value a 2-tuple of ``(visit, depart)`` methods.
108
``depart`` can be ``None`` if the ``visit`` function raises
109
:exc:`docutils.nodes.SkipNode`. Example:
111
.. code-block:: python
113
class math(docutils.nodes.Element): pass
115
def visit_math_html(self, node):
116
self.body.append(self.starttag(node, 'math'))
117
def depart_math_html(self, node):
118
self.body.append('</math>')
120
app.add_node(math, html=(visit_math_html, depart_math_html))
122
Obviously, translators for which you don't specify visitor methods will choke
123
on the node when encountered in a document to translate.
125
.. versionchanged:: 0.5
126
Added the support for keyword arguments giving visit functions.
128
.. method:: Sphinx.add_directive(name, func, content, arguments, **options)
129
Sphinx.add_directive(name, directiveclass)
131
Register a Docutils directive. *name* must be the prospective directive
132
name. There are two possible ways to write a directive:
134
* In the docutils 0.4 style, *obj* is the directive function. *content*,
135
*arguments* and *options* are set as attributes on the function and
136
determine whether the directive has content, arguments and options,
137
respectively. **This style is deprecated.**
139
* In the docutils 0.5 style, *directiveclass* is the directive class. It
140
must already have attributes named *has_content*, *required_arguments*,
141
*optional_arguments*, *final_argument_whitespace* and *option_spec* that
142
correspond to the options for the function way. See `the Docutils docs
143
<http://docutils.sourceforge.net/docs/howto/rst-directives.html>`_ for
146
The directive class must inherit from the class
147
``docutils.parsers.rst.Directive``.
149
For example, the (already existing) :rst:dir:`literalinclude` directive would
152
.. code-block:: python
154
from docutils.parsers.rst import directives
155
add_directive('literalinclude', literalinclude_directive,
156
content = 0, arguments = (1, 0, 0),
157
linenos = directives.flag,
158
language = direcitves.unchanged,
159
encoding = directives.encoding)
161
.. versionchanged:: 0.6
162
Docutils 0.5-style directive classes are now supported.
164
.. method:: Sphinx.add_directive_to_domain(domain, name, func, content, arguments, **options)
165
Sphinx.add_directive_to_domain(domain, name, directiveclass)
167
Like :meth:`add_directive`, but the directive is added to the domain named
170
.. versionadded:: 1.0
172
.. method:: Sphinx.add_role(name, role)
174
Register a Docutils role. *name* must be the role name that occurs in the
175
source, *role* the role function (see the `Docutils documentation
176
<http://docutils.sourceforge.net/docs/howto/rst-roles.html>`_ on details).
178
.. method:: Sphinx.add_role_to_domain(domain, name, role)
180
Like :meth:`add_role`, but the role is added to the domain named *domain*.
182
.. versionadded:: 1.0
184
.. method:: Sphinx.add_generic_role(name, nodeclass)
186
Register a Docutils role that does nothing but wrap its contents in the
187
node given by *nodeclass*.
189
.. versionadded:: 0.6
191
.. method:: Sphinx.add_object_type(directivename, rolename, indextemplate='', parse_node=None, \
192
ref_nodeclass=None, objname='', doc_field_types=[])
194
This method is a very convenient way to add a new :term:`object` type that
195
can be cross-referenced. It will do this:
197
* Create a new directive (called *directivename*) for documenting an object.
198
It will automatically add index entries if *indextemplate* is nonempty; if
199
given, it must contain exactly one instance of ``%s``. See the example
200
below for how the template will be interpreted.
201
* Create a new role (called *rolename*) to cross-reference to these
203
* If you provide *parse_node*, it must be a function that takes a string and
204
a docutils node, and it must populate the node with children parsed from
205
the string. It must then return the name of the item to be used in
206
cross-referencing and index entries. See the :file:`conf.py` file in the
207
source for this documentation for an example.
208
* The *objname* (if not given, will default to *directivename*) names the
209
type of object. It is used when listing objects, e.g. in search results.
211
For example, if you have this call in a custom Sphinx extension::
213
app.add_object_type('directive', 'dir', 'pair: %s; directive')
215
you can use this markup in your documents::
217
.. rst:directive:: function
223
See also the :rst:dir:`function` directive.
225
For the directive, an index entry will be generated as if you had prepended ::
227
.. index:: pair: function; directive
229
The reference node will be of class ``literal`` (so it will be rendered in a
230
proportional font, as appropriate for code) unless you give the
231
*ref_nodeclass* argument, which must be a docutils node class. Most useful
232
are ``docutils.nodes.emphasis`` or ``docutils.nodes.strong`` -- you can also
233
use ``docutils.nodes.generated`` if you want no further text decoration. If
234
the text should be treated as literal (e.g. no smart quote replacement), but
235
not have typewriter styling, use ``sphinx.addnodes.literal_emphasis`` or
236
``sphinx.addnodes.literal_strong``.
238
For the role content, you have the same syntactical possibilities as for
239
standard Sphinx roles (see :ref:`xref-syntax`).
241
This method is also available under the deprecated alias
242
``add_description_unit``.
244
.. method:: Sphinx.add_crossref_type(directivename, rolename, indextemplate='', ref_nodeclass=None, objname='')
246
This method is very similar to :meth:`add_object_type` except that the
247
directive it generates must be empty, and will produce no output.
249
That means that you can add semantic targets to your sources, and refer to
250
them using custom roles instead of generic ones (like :rst:role:`ref`).
253
app.add_crossref_type('topic', 'topic', 'single: %s', docutils.nodes.emphasis)
257
.. topic:: application API
264
See also :topic:`this section <application API>`.
266
(Of course, the element following the ``topic`` directive needn't be a
269
.. method:: Sphinx.add_transform(transform)
271
Add the standard docutils :class:`Transform` subclass *transform* to the list
272
of transforms that are applied after Sphinx parses a reST document.
274
.. method:: Sphinx.add_javascript(filename)
276
Add *filename* to the list of JavaScript files that the default HTML template
277
will include. The filename must be relative to the HTML static path, see
278
:confval:`the docs for the config value <html_static_path>`. A full URI with
279
scheme, like ``http://example.org/foo.js``, is also supported.
281
.. versionadded:: 0.5
283
.. method:: Sphinx.add_stylesheet(filename)
285
Add *filename* to the list of CSS files that the default HTML template will
286
include. Like for :meth:`add_javascript`, the filename must be relative to
287
the HTML static path, or a full URI with scheme.
289
.. versionadded:: 1.0
291
.. method:: Sphinx.add_latex_package(packagename, options=None)
293
Add *packagename* to the list of packages that LaTeX source code will include.
294
If you provide *options*, it will be taken to `\usepackage` declaration.
296
.. code-block:: python
298
app.add_latex_package('mypackage') # => \usepackage{mypackage}
299
app.add_latex_package('mypackage', 'foo,bar') # => \usepackage[foo,bar]{mypackage}
301
.. versionadded:: 1.3
303
.. method:: Sphinx.add_lexer(alias, lexer)
305
Use *lexer*, which must be an instance of a Pygments lexer class, to
306
highlight code blocks with the given language *alias*.
308
.. versionadded:: 0.6
310
.. method:: Sphinx.add_autodocumenter(cls)
312
Add *cls* as a new documenter class for the :mod:`sphinx.ext.autodoc`
313
extension. It must be a subclass of :class:`sphinx.ext.autodoc.Documenter`.
314
This allows to auto-document new types of objects. See the source of the
315
autodoc module for examples on how to subclass :class:`Documenter`.
317
.. XXX add real docs for Documenter and subclassing
319
.. versionadded:: 0.6
321
.. method:: Sphinx.add_autodoc_attrgetter(type, getter)
323
Add *getter*, which must be a function with an interface compatible to the
324
:func:`getattr` builtin, as the autodoc attribute getter for objects that are
325
instances of *type*. All cases where autodoc needs to get an attribute of a
326
type are then handled by this function instead of :func:`getattr`.
328
.. versionadded:: 0.6
330
.. method:: Sphinx.add_search_language(cls)
332
Add *cls*, which must be a subclass of :class:`sphinx.search.SearchLanguage`,
333
as a support language for building the HTML full-text search index. The
334
class must have a *lang* attribute that indicates the language it should be
335
used for. See :confval:`html_search_language`.
337
.. versionadded:: 1.1
339
.. method:: Sphinx.require_sphinx(version)
341
Compare *version* (which must be a ``major.minor`` version string,
342
e.g. ``'1.1'``) with the version of the running Sphinx, and abort the build
345
.. versionadded:: 1.0
347
.. method:: Sphinx.connect(event, callback)
349
Register *callback* to be called when *event* is emitted. For details on
350
available core events and the arguments of callback functions, please see
353
The method returns a "listener ID" that can be used as an argument to
356
.. method:: Sphinx.disconnect(listener_id)
358
Unregister callback *listener_id*.
361
.. exception:: ExtensionError
363
All these methods raise this exception if something went wrong with the
370
.. method:: Sphinx.emit(event, *arguments)
372
Emit *event* and pass *arguments* to the callback functions. Return the
373
return values of all callbacks as a list. Do not emit core Sphinx events
376
.. method:: Sphinx.emit_firstresult(event, *arguments)
378
Emit *event* and pass *arguments* to the callback functions. Return the
379
result of the first callback that doesn't return ``None``.
381
.. versionadded:: 0.5
384
Producing messages / logging
385
----------------------------
387
The application object also provides support for emitting leveled messages.
391
There is no "error" call: in Sphinx, errors are defined as things that stop
392
the build; just raise an exception (:exc:`sphinx.errors.SphinxError` or a
393
custom subclass) to do that.
395
.. automethod:: Sphinx.warn
397
.. automethod:: Sphinx.info
399
.. automethod:: Sphinx.verbose
401
.. automethod:: Sphinx.debug
403
.. automethod:: Sphinx.debug2
411
These events are known to the core. The arguments shown are given to the
412
registered event handlers. Use :meth:`.connect` in an extension's ``setup``
413
function (note that ``conf.py`` can also have a ``setup`` function) to connect
414
handlers to the events. Example:
416
.. code-block:: python
418
def source_read_handler(app, docname, source):
419
print('do something here...')
422
app.connect('source-read', source_read_handler)
425
.. event:: builder-inited (app)
427
Emitted when the builder object has been created. It is available as
430
.. event:: env-get-outdated (app, env, added, changed, removed)
432
Emitted when the environment determines which source files have changed and
433
should be re-read. *added*, *changed* and *removed* are sets of docnames
434
that the environment has determined. You can return a list of docnames to
435
re-read in addition to these.
437
.. versionadded:: 1.1
439
.. event:: env-purge-doc (app, env, docname)
441
Emitted when all traces of a source file should be cleaned from the
442
environment, that is, if the source file is removed or before it is freshly
443
read. This is for extensions that keep their own caches in attributes of the
446
For example, there is a cache of all modules on the environment. When a
447
source file has been changed, the cache's entries for the file are cleared,
448
since the module declarations could have been removed from the file.
450
.. versionadded:: 0.5
452
.. event:: env-before-read-docs (app, env, docnames)
454
Emitted after the environment has determined the list of all added and
455
changed files and just before it reads them. It allows extension authors to
456
reorder the list of docnames (*inplace*) before processing, or add more
457
docnames that Sphinx did not consider changed (but never add any docnames
458
that are not in ``env.found_docs``).
460
You can also remove document names; do this with caution since it will make
461
Sphinx treat changed files as unchanged.
463
.. versionadded:: 1.3
465
.. event:: source-read (app, docname, source)
467
Emitted when a source file has been read. The *source* argument is a list
468
whose single element is the contents of the source file. You can process the
469
contents and replace this item to implement source-level transformations.
471
For example, if you want to use ``$`` signs to delimit inline math, like in
472
LaTeX, you can use a regular expression to replace ``$...$`` by
475
.. versionadded:: 0.5
477
.. event:: doctree-read (app, doctree)
479
Emitted when a doctree has been parsed and read by the environment, and is
480
about to be pickled. The *doctree* can be modified in-place.
482
.. event:: missing-reference (app, env, node, contnode)
484
Emitted when a cross-reference to a Python module or object cannot be
485
resolved. If the event handler can resolve the reference, it should return a
486
new docutils node to be inserted in the document tree in place of the node
487
*node*. Usually this node is a :class:`reference` node containing *contnode*
490
:param env: The build environment (``app.builder.env``).
491
:param node: The :class:`pending_xref` node to be resolved. Its attributes
492
``reftype``, ``reftarget``, ``modname`` and ``classname`` attributes
493
determine the type and target of the reference.
494
:param contnode: The node that carries the text and formatting inside the
495
future reference and should be a child of the returned reference node.
497
.. versionadded:: 0.5
499
.. event:: doctree-resolved (app, doctree, docname)
501
Emitted when a doctree has been "resolved" by the environment, that is, all
502
references have been resolved and TOCs have been inserted. The *doctree* can
503
be modified in place.
505
Here is the place to replace custom nodes that don't have visitor methods in
506
the writers, so that they don't cause errors when the writers encounter them.
508
.. event:: env-merge-info (env, docnames, other)
510
This event is only emitted when parallel reading of documents is enabled. It
511
is emitted once for every subprocess that has read some documents.
513
You must handle this event in an extension that stores data in the
514
environment in a custom location. Otherwise the environment in the main
515
process will not be aware of the information stored in the subprocess.
517
*other* is the environment object from the subprocess, *env* is the
518
environment from the main process. *docnames* is a set of document names
519
that have been read in the subprocess.
521
For a sample of how to deal with this event, look at the standard
522
``sphinx.ext.todo`` extension. The implementation is often similar to that
523
of :event:`env-purge-doc`, only that information is not removed, but added to
524
the main environment from the other environment.
526
.. versionadded:: 1.3
528
.. event:: env-updated (app, env)
530
Emitted when the :meth:`update` method of the build environment has
531
completed, that is, the environment and all doctrees are now up-to-date.
533
You can return an iterable of docnames from the handler. These documents
534
will then be considered updated, and will be (re-)written during the writing
537
.. versionadded:: 0.5
539
.. versionchanged:: 1.3
540
The handlers' return value is now used.
542
.. event:: html-collect-pages (app)
544
Emitted when the HTML builder is starting to write non-document pages. You
545
can add pages to write by returning an iterable from this event consisting of
546
``(pagename, context, templatename)``.
548
.. versionadded:: 1.0
550
.. event:: html-page-context (app, pagename, templatename, context, doctree)
552
Emitted when the HTML builder has created a context dictionary to render a
553
template with -- this can be used to add custom elements to the context.
555
The *pagename* argument is the canonical name of the page being rendered,
556
that is, without ``.html`` suffix and using slashes as path separators. The
557
*templatename* is the name of the template to render, this will be
558
``'page.html'`` for all pages from reST documents.
560
The *context* argument is a dictionary of values that are given to the
561
template engine to render the page and can be modified to include custom
562
values. Keys must be strings.
564
The *doctree* argument will be a doctree when the page is created from a reST
565
documents; it will be ``None`` when the page is created from an HTML template
568
You can return a string from the handler, it will then replace
569
``'page.html'`` as the HTML template for this page.
571
.. versionadded:: 0.4
573
.. versionchanged:: 1.3
574
The return value can now specify a template name.
576
.. event:: build-finished (app, exception)
578
Emitted when a build has finished, before Sphinx exits, usually used for
579
cleanup. This event is emitted even when the build process raised an
580
exception, given as the *exception* argument. The exception is reraised in
581
the application after the event handlers have run. If the build process
582
raised no exception, *exception* will be ``None``. This allows to customize
583
cleanup actions depending on the exception status.
585
.. versionadded:: 0.5
588
Checking the Sphinx version
589
---------------------------
591
.. currentmodule:: sphinx
593
Use this to adapt your extension to API changes in Sphinx.
595
.. data:: version_info
597
A tuple of five elements; for Sphinx version 1.2.1 beta 3 this would be
598
``(1, 2, 1, 'beta', 3)``.
600
.. versionadded:: 1.2
601
Before version 1.2, check the string ``sphinx.__version__``.
607
.. module:: sphinx.config
611
The config object makes the values of all config values available as
614
It is available as the ``config`` attribute on the application and
615
environment objects. For example, to get the value of :confval:`language`,
616
use either ``app.config.language`` or ``env.config.language``.
624
.. currentmodule:: sphinx.application
626
.. autoclass:: TemplateBridge
635
.. module:: sphinx.errors
637
.. exception:: SphinxError
639
This is the base class for "nice" exceptions. When such an exception is
640
raised, Sphinx will abort the build and present the exception category and
643
Extensions are encouraged to derive from this exception for their custom
646
Exceptions *not* derived from :exc:`SphinxError` are treated as unexpected
647
and shown to the user with a part of the traceback (and the full traceback
648
saved in a temporary file).
650
.. attribute:: category
652
Description of the exception "category", used in converting the exception
653
to a string ("category: message"). Should be set accordingly in
656
.. exception:: ConfigError
658
Used for erroneous values or nonsensical combinations of configuration
661
.. exception:: ExtensionError
663
Used for errors in setting up extensions.
665
.. exception:: ThemeError
667
Used for errors to do with themes.
669
.. exception:: VersionRequirementError
671
Raised when the docs require a higher Sphinx version than the current one.