Sphinx PDF
Sphinx PDF
Sphinx PDF
Release 3.0.0+/0fb832baa
Georg Brandl
1 Introduction 1
1.1 Conversion from other systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Use with other systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.4 Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2 Installing Sphinx 3
2.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.2 Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.3 macOS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.4 Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.5 Installation from PyPI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.6 Installation from source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
3 Getting Started 7
3.1 Setting up the documentation sources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.2 Defining document structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.3 Adding content . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.4 Running the build . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.5 Documenting objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.6 Basic configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.7 Autodoc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.8 Intersphinx . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3.9 More topics to be covered . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
4 reStructuredText 13
4.1 reStructuredText Primer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
4.2 Roles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
4.3 Directives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
4.4 Field Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
4.5 Domains . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
5 Markdown 69
5.1 Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
6 Configuration 71
6.1 Project information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
6.2 General configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
6.3 Options for internationalization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
6.4 Options for Math . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
6.5 Options for HTML output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
i
6.6 Options for Single HTML output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
6.7 Options for HTML help output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
6.8 Options for Apple Help output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
6.9 Options for epub output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
6.10 Options for LaTeX output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
6.11 Options for text output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
6.12 Options for manual page output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
6.13 Options for Texinfo output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
6.14 Options for QtHelp output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
6.15 Options for the linkcheck builder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
6.16 Options for the XML builder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
6.17 Options for the C++ domain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
7 Builders 109
7.1 Serialization builder details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
8 Extensions 117
8.1 Built-in extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
8.2 Third-party extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
9 HTML 159
9.1 Builders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
9.2 Themes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
10 Internationalization 167
10.1 Sphinx internationalization details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
10.2 Translating with sphinx-intl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
10.3 Using Transifex service for team translation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
10.4 Contributing to Sphinx reference translation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
15 Templating 203
15.1 Do I need to use Sphinx’s templates to produce HTML? . . . . . . . . . . . . . . . . . . . . . 203
15.2 Jinja/Sphinx Templating Primer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
15.3 Working with the builtin templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
ii
16.2 The latex_elements configuration setting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
16.3 ’sphinxsetup’ key . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
16.4 LaTeX macros and environments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
20 Glossary 293
iii
22.22 Release 1.7.1 (released Feb 23, 2018) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
22.23 Release 1.7.0 (released Feb 12, 2018) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328
22.24 Release 1.6.7 (released Feb 04, 2018) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332
22.25 Release 1.6.6 (released Jan 08, 2018) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
22.26 Release 1.6.5 (released Oct 23, 2017) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334
22.27 Release 1.6.4 (released Sep 26, 2017) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334
22.28 Release 1.6.3 (released Jul 02, 2017) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
22.29 Release 1.6.2 (released May 28, 2017) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
22.30 Release 1.6.1 (released May 16, 2017) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
22.31 Release 1.6 (unreleased) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342
22.32 Release 1.5.6 (released May 15, 2017) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342
22.33 Release 1.5.5 (released Apr 03, 2017) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342
22.34 Release 1.5.4 (released Apr 02, 2017) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
22.35 Release 1.5.3 (released Feb 26, 2017) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
22.36 Release 1.5.2 (released Jan 22, 2017) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344
22.37 Release 1.5.1 (released Dec 13, 2016) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345
22.38 Release 1.5 (released Dec 5, 2016) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
22.39 Release 1.4.9 (released Nov 23, 2016) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352
22.40 Release 1.4.8 (released Oct 1, 2016) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352
22.41 Release 1.4.7 (released Oct 1, 2016) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352
22.42 Release 1.4.6 (released Aug 20, 2016) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
22.43 Release 1.4.5 (released Jul 13, 2016) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
22.44 Release 1.4.4 (released Jun 12, 2016) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
22.45 Release 1.4.3 (released Jun 5, 2016) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
22.46 Release 1.4.2 (released May 29, 2016) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
22.47 Release 1.4.1 (released Apr 12, 2016) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
22.48 Release 1.4 (released Mar 28, 2016) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
22.49 Release 1.3.6 (released Feb 29, 2016) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
22.50 Release 1.3.5 (released Jan 24, 2016) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
22.51 Release 1.3.4 (released Jan 12, 2016) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
22.52 Release 1.3.3 (released Dec 2, 2015) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
22.53 Release 1.3.2 (released Nov 29, 2015) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
22.54 Release 1.3.1 (released Mar 17, 2015) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366
22.55 Release 1.3 (released Mar 10, 2015) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366
22.56 Release 1.3b3 (released Feb 24, 2015) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
22.57 Release 1.3b2 (released Dec 5, 2014) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
22.58 Release 1.3b1 (released Oct 10, 2014) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
22.59 Release 1.2.3 (released Sep 1, 2014) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
22.60 Release 1.2.2 (released Mar 2, 2014) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373
22.61 Release 1.2.1 (released Jan 19, 2014) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374
22.62 Release 1.2 (released Dec 10, 2013) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
22.63 Release 1.2 beta3 (released Oct 3, 2013) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
22.64 Release 1.2 beta2 (released Sep 17, 2013) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
22.65 Release 1.2 beta1 (released Mar 31, 2013) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378
22.66 Release 1.1.3 (Mar 10, 2012) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382
22.67 Release 1.1.2 (Nov 1, 2011) – 1.1.1 is a silly version number anyway! . . . . . . . . . . . . . . 383
22.68 Release 1.1.1 (Nov 1, 2011) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383
22.69 Release 1.1 (Oct 9, 2011) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383
22.70 Release 1.0.8 (Sep 23, 2011) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385
22.71 Release 1.0.7 (Jan 15, 2011) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386
22.72 Release 1.0.6 (Jan 04, 2011) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
22.73 Release 1.0.5 (Nov 12, 2010) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
22.74 Release 1.0.4 (Sep 17, 2010) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388
22.75 Release 1.0.3 (Aug 23, 2010) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388
iv
22.76 Release 1.0.2 (Aug 14, 2010) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388
22.77 Release 1.0.1 (Jul 27, 2010) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
22.78 Release 1.0 (Jul 23, 2010) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
22.79 Previous versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
Index 417
v
vi
CHAPTER
ONE
INTRODUCTION
This is the documentation for the Sphinx documentation builder. Sphinx is a tool that translates a set
of reStructuredText3 source files into various output formats, automatically producing cross-references,
indices, etc. That is, if you have a directory containing a bunch of reST-formatted documents (and possibly
subdirectories of docs in there as well), Sphinx can generate a nicely-organized arrangement of HTML files
(in some other directory) for easy browsing and navigation. But from the same source, it can also generate
a PDF file using LaTeX.
The focus is on hand-written documentation, rather than auto-generated API docs. Though there is
support for that kind of documentation as well (which is intended to be freely mixed with hand-written
content), if you need pure API docs have a look at Epydoc4 , which also understands reST.
For a great “introduction” to writing docs in general – the whys and hows, see also Write the docs5 ,
written by Eric Holscher.
This section is intended to collect helpful hints for those wanting to migrate to reStructuredText/Sphinx
from other documentation systems.
• Gerard Flanagan has written a script to convert pure HTML to reST; it can be found at the Python
Package Index6 .
• For converting the old Python docs to Sphinx, a converter was written which can be found at the
Python SVN repository7 . It contains generic code to convert Python-doc-style LaTeX markup to
Sphinx reST.
• Marcin Wojdyr has written a script to convert Docbook to reST with Sphinx markup; it is at GitHub8 .
• Christophe de Vienne wrote a tool to convert from Open/LibreOffice documents to Sphinx:
odt2sphinx9 .
• To convert different markups, Pandoc10 is a very helpful tool.
3 http://docutils.sourceforge.net/rst.html
4 http://epydoc.sourceforge.net/
5 http://www.writethedocs.org/guide/writing/beginners-guide-to-docs/
6 https://pypi.org/project/html2rest/
7 https://svn.python.org/projects/doctools/converter/
8 https://github.com/wojdyr/db2rst
9 https://pypi.org/project/odt2sphinx/
10 https://pandoc.org/
1
Sphinx Documentation, Release 3.0.0+/0fb832baa
1.3 Prerequisites
Sphinx needs at least Python 3.5 to run, as well as the docutils11 and Jinja212 libraries. Sphinx should
work with docutils version 0.12 or some (not broken) SVN trunk snapshot.
1.4 Usage
See Getting Started for an introduction. It also contains links to more advanced sections in this manual for
the topics it discusses.
11 http://docutils.sourceforge.net/
12 http://jinja.pocoo.org/
2 Chapter 1. Introduction
CHAPTER
TWO
INSTALLING SPHINX
• Overview
• Linux
• macOS
• Windows
• Installation from PyPI
• Installation from source
2.1 Overview
2.2 Linux
2.2.1 Debian/Ubuntu
3
Sphinx Documentation, Release 3.0.0+/0fb832baa
Most Linux distributions have Sphinx in their package repositories. Usually the package is called
python3-sphinx, python-sphinx or sphinx. Be aware that there are at least two other packages
with sphinx in their name: a speech recognition toolkit (CMU Sphinx) and a full-text search database
(Sphinx search).
2.3 macOS
Sphinx can be installed using Homebrew14 , MacPorts15 , or as part of a Python distribution such as Ana-
conda16 .
2.3.1 Homebrew
2.3.2 MacPorts
2.3.3 Anaconda
2.4 Windows
Most Windows users do not have Python installed by default, so we begin with the installation of Python
itself. If you are unsure, open the Command Prompt (Win-r and type cmd). Once the command prompt is
open, type python --version and press Enter. If Python is available, you will see the version of Python
14 https://brew.sh/
15 https://www.macports.org/
16 https://www.anaconda.com/download/#macos
17 https://formulae.brew.sh/formula/sphinx-doc
18 https://www.macports.org/ports.php?by=library&substr=py36-sphinx
printed to the screen. If you do not have Python installed, refer to the Hitchhikers Guide to Python’s19
Python on Windows installation guides. You must install Python 320 .
Once Python is installed, you can install Sphinx using pip. Refer to the pip installation instructions below
for more information.
Sphinx packages are published on the Python Package Index21 . The preferred tool for installing packages
from PyPI is pip. This tool is provided with all modern versions of Python.
On Linux or MacOS, you should open your terminal and run the following command.
On Windows, you should open Command Prompt (Win-r and type cmd) and run the same command.
After installation, type sphinx-build --version on the command prompt. If everything worked fine,
you will see the version number for the Sphinx package you just installed.
Installation from PyPI also allows you to install the latest development release. You will not generally
need (or want) to do this, but it can be useful if you see a possible bug in the latest stable release. To do
this, use the --pre flag.
You can install Sphinx directly from a clone of the Git repository22 . This can be done either by cloning the
repo and installing from the local clone, on simply installing directly via git.
You can also download a snapshot of the Git repo in either tar.gz23 or zip24 format. Once downloaded
and extracted, these can be installed with pip as above.
19 https://docs.python-guide.org/
20 https://docs.python-guide.org/starting/install3/win/
21 https://pypi.org/project/Sphinx/
22 https://github.com/sphinx-doc/sphinx
23 https://github.com/sphinx-doc/sphinx/archive/master.tar.gz
24 https://github.com/sphinx-doc/sphinx/archive/master.zip
THREE
GETTING STARTED
Once Sphinx is installed, you can proceed with setting up your first Sphinx project. To ease the process
of getting started, Sphinx provides a tool, sphinx-quickstart, which will generate a documentation
source directory and populate it with some defaults. We’re going to use the sphinx-quickstart tool
here, though its use is by no means necessary.
The root directory of a Sphinx collection of reStructuredText document sources is called the source directory.
This directory also contains the Sphinx configuration file conf.py, where you can configure all aspects
of how Sphinx reads your sources and builds your documentation.26
Sphinx comes with a script called sphinx-quickstart that sets up a source directory and creates a
default conf.py with the most useful configuration values from a few questions it asks you. To use this,
run:
$ sphinx-quickstart
Answer each question asked. Be sure to say “yes” to the autodoc extension, as we will use this later.
There is also an automatic “API documentation” generator called sphinx-apidoc; see sphinx-apidoc for
details.
Let’s assume you’ve run sphinx-quickstart. It created a source directory with conf.py and a master
document, index.rst (if you accepted the defaults). The main function of the master document is to serve
as a welcome page, and to contain the root of the “table of contents tree” (or toctree). This is one of the
main things that Sphinx adds to reStructuredText, a way to connect multiple files to a single hierarchy of
documents.
reStructuredText directives
toctree is a reStructuredText directive, a very versatile piece of markup. Directives can have arguments,
options and content.
Arguments are given directly after the double colon following the directive’s name. Each directive
decides whether it can have arguments, and how many.
26 This is the usual layout. However, conf.py can also live in another directory, the configuration directory. Refer to the sphinx-build
7
Sphinx Documentation, Release 3.0.0+/0fb832baa
Options are given after the arguments, in form of a “field list”. The maxdepth is such an option for the
toctree directive.
Content follows the options or arguments after a blank line. Each directive decides whether to allow
content, and what to do with it.
A common gotcha with directives is that the first line of the content must be indented to the same
level as the options are.
.. toctree::
:maxdepth: 2
.. toctree::
:maxdepth: 2
usage/installation
usage/quickstart
...
This is exactly how the toctree for this documentation looks. The documents to include are given as
document names, which in short means that you leave off the file name extension and use forward slashes
(/) as directory separators.
You can now create the files you listed in the toctree and add content, and their section titles will be
inserted (up to the maxdepth level) at the place where the toctree directive is placed. Also, Sphinx
now knows about the order and hierarchy of your documents. (They may contain toctree directives
themselves, which means you can create deeply nested hierarchies if necessary.)
In Sphinx source files, you can use most features of standard reStructuredText. There are also several
features added by Sphinx. For example, you can add cross-file references in a portable way (which works
for all output types) using the ref role.
For an example, if you are viewing the HTML version, you can look at the source for this document – use
the “Show Source” link in the sidebar.
Todo: Update the below link when we add new guides on these.
See reStructuredText for a more in-depth introduction to reStructuredText, including markup added
by Sphinx.
Now that you have added some files and content, let’s make a first build of the docs. A build is started
with the sphinx-build program:
where sourcedir is the source directory, and builddir is the directory in which you want to place the built
documentation. The -b option selects a builder; in this example Sphinx will build HTML files.
Refer to the sphinx-build man page for all options that sphinx-build supports.
However, sphinx-quickstart script creates a Makefile and a make.bat which make life even easier
for you. These can be executed by running make with the name of the builder. For example.
$ make html
This will build HTML docs in the build directory you chose. Execute make without an argument to see
which targets are available.
One of Sphinx’s main objectives is easy documentation of objects (in a very general sense) in any domain. A
domain is a collection of object types that belong together, complete with markup to create and reference
descriptions of these objects.
The most prominent domain is the Python domain. For example, to document Python’s built-in function
enumerate(), you would add this to one of your source files.
...
does the same job if you keep the default setting for the default domain.
There are several more directives for documenting other types of Python objects, for example py:class
or py:method. There is also a cross-referencing role for each of these object types. This markup will
create a link to the documentation of enumerate().
See Domains for all the available domains and their directives/roles.
Earlier we mentioned that the conf.py file controls how Sphinx processes your documents. In that file,
which is executed as a Python source file, you assign configuration values. For advanced users: since it is
executed by Sphinx, you can do non-trivial tasks in it, like extending sys.path or importing a module
to find out the version you are documenting.
The config values that you probably want to change are already put into the conf.py by
sphinx-quickstart and initially commented out (with standard Python syntax: a # comments the
rest of the line). To change the default value, remove the hash sign and modify the value. To customize a
config value that is not automatically added by sphinx-quickstart, just add an additional assignment.
Keep in mind that the file uses Python syntax for strings, numbers, lists and so on. The file is saved in
UTF-8 by default, as indicated by the encoding declaration in the first line. If you use non-ASCII characters
in any string value, you need to use Python Unicode strings (like project = u'Exposé').
3.7 Autodoc
When documenting Python code, it is common to put a lot of documentation in the source files, in
documentation strings. Sphinx supports the inclusion of docstrings from your modules with an extension
(an extension is a Python module that provides additional features for Sphinx projects) called autodoc.
In order to use autodoc, you need to activate it in conf.py by putting the string 'sphinx.ext.autodoc'
into the list assigned to the extensions config value. Then, you have a few additional directives at your
disposal.
For example, to document the function io.open(), reading its signature and docstring from the source
file, you’d write this:
.. autofunction:: io.open
You can also document whole classes or even modules automatically, using member options for the auto
directives, like
.. automodule:: io
:members:
autodoc needs to import your modules in order to extract the docstrings. Therefore, you must add the
appropriate path to sys.path in your conf.py.
Warning: autodoc imports the modules to be documented. If any modules have side effects on
import, these will be executed by autodoc when sphinx-build is run.
If you document scripts (as opposed to library modules), make sure their main routine is protected by
a if __name__ == '__main__' condition.
3.8 Intersphinx
Many Sphinx documents including the Python documentation25 are published on the Internet. When
you want to make links to such documents from your documentation, you can do it with sphinx.ext.
intersphinx.
In order to use intersphinx, you need to activate it in conf.py by putting the string 'sphinx.ext.
intersphinx' into the extensions list and set up the intersphinx_mapping config value.
For example, to link to io.open() in the Python library manual, you need to setup your
intersphinx_mapping like:
And now, you can write a cross-reference like :py:func:`io.open`. Any cross-reference that has no
matching target in the current documentation set, will be looked up in the documentation sets configured
in intersphinx_mapping (this needs access to the URL in order to download the list of valid targets).
Intersphinx also works for some other domain’s roles including :ref:, however it doesn’t work for :doc:
as that is non-domain role.
25 https://docs.python.org/3
3.8. Intersphinx 11
Sphinx Documentation, Release 3.0.0+/0fb832baa
• Other extensions:
• Static files
• Selecting a theme
• Setuptools integration
• Templating
• Using extensions
• Writing extensions
FOUR
RESTRUCTUREDTEXT
reStructuredText (reST) is the default plaintext markup language used by both Docutils and Sphinx. Do-
cutils provides the basic reStructuredText syntax, while Sphinx extends this to support additional func-
tionality.
The below guides go through the most important aspects of reST. For the authoritative reStructuredText
reference, refer to the docutils documentation27 .
reStructuredText is the default plaintext markup language used by Sphinx. This section is a brief introduc-
tion to reStructuredText (reST) concepts and syntax, intended to provide authors with enough information
to author documents productively. Since reST was designed to be a simple, unobtrusive markup language,
this will not take too long.
See also:
The authoritative reStructuredText User Documentation28 . The “ref” links in this document link to the
description of the individual constructs in the reST reference.
4.1.1 Paragraphs
The paragraph (ref29 ) is the most basic block in a reST document. Paragraphs are simply chunks of text
separated by one or more blank lines. As in Python, indentation is significant in reST, so all lines of the
same paragraph must be left-aligned to the same level of indentation.
13
Sphinx Documentation, Release 3.0.0+/0fb832baa
List markup (ref30 ) is natural: just place an asterisk at the start of a paragraph and indent properly. The
same goes for numbered lists; they can also be autonumbered using a # sign:
Nested lists are possible, but be aware that they must be separated from the parent list items by blank
lines:
* this is
* a list
next term
Description.
Note that the term cannot have more than one line of text.
Quoted paragraphs (ref32 ) are created by just indenting them more than the surrounding paragraphs.
Line blocks (ref33 ) are a way of preserving line breaks:
30 http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#bullet-lists
31 http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#definition-lists
32 http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#block-quotes
33 http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#line-blocks
14 Chapter 4. reStructuredText
Sphinx Documentation, Release 3.0.0+/0fb832baa
Literal code blocks (ref38 ) are introduced by ending a paragraph with the special marker ::. The literal
block must be indented (and, like all paragraphs, separated from the surrounding ones by blank lines):
Doctest blocks (ref39 ) are interactive Python sessions cut-and-pasted into docstrings. They do not require
the literal blocks syntax. The doctest block must end with a blank line and should not end with with an
unused prompt:
>>> 1 + 1
2
34 http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#field-lists
35 http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#option-lists
36 http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#quoted-literal-blocks
37 http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#doctest-blocks
38 http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#literal-blocks
39 http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#doctest-blocks
4.1.6 Tables
For grid tables (ref40 ), you have to “paint” the cell grid yourself. They look like this:
+------------------------+------------+----------+----------+
| Header row, column 1 | Header 2 | Header 3 | Header 4 |
| (header rows optional) | | | |
+========================+============+==========+==========+
| body row 1, column 1 | column 2 | column 3 | column 4 |
+------------------------+------------+----------+----------+
| body row 2 | ... | ... | |
+------------------------+------------+----------+----------+
Simple tables (ref41 ) are easier to write, but limited: they must contain more than one row, and the first
column cells cannot contain multiple lines. They look like this:
Two more syntaxes are supported: CSV tables and List tables. They use an explicit markup block. Refer to
Tables for more information.
4.1.7 Hyperlinks
External links
Use `Link text <https://domain.invalid/>`_ for inline web links. If the link text should be the
web address, you don’t need special markup at all, the parser finds links and mail addresses in ordinary
text.
Important: There must be a space between the link text and the opening < for the URL.
You can also separate the link and the target definition (ref42 ), like this:
.. _a link: https://domain.invalid/
Internal links
Internal linking is done via a special reST role provided by Sphinx, see the section on specific markup,
Cross-referencing arbitrary locations.
40 http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#grid-tables
41 http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#simple-tables
42 http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#hyperlink-targets
16 Chapter 4. reStructuredText
Sphinx Documentation, Release 3.0.0+/0fb832baa
4.1.8 Sections
Section headers (ref43 ) are created by underlining (and optionally overlining) the section title with a punc-
tuation character, at least as long as the text:
=================
This is a heading
=================
Normally, there are no heading levels assigned to certain characters as the structure is determined from
the succession of headings. However, this convention is used in Python’s Style Guide for documenting44
which you may follow:
• # with overline, for parts
• * with overline, for chapters
• =, for sections
• -, for subsections
• ^, for subsubsections
• ", for paragraphs
Of course, you are free to use your own marker characters (see the reST documentation), and use a deeper
nesting level, but keep in mind that most target formats (HTML, LaTeX) have a limited supported nesting
depth.
Sphinx extends standard docutils behavior and intercepts field lists specified at the beginning of docu-
ments. Refer to Field Lists for more information.
4.1.10 Roles
A role or “custom interpreted text role” (ref46 ) is an inline piece of explicit markup. It signifies that
that the enclosed text should be interpreted in a specific way. Sphinx uses this to provide semantic
43 http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#sections
44 https://docs.python.org/devguide/documenting.html#style-guide
45 http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#field-lists
46 http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#roles
markup and cross-referencing of identifiers, as described in the appropriate section. The general syntax is
:rolename:`content`.
Docutils supports the following roles:
• emphasis47 – equivalent of *emphasis*
• strong48 – equivalent of **strong**
• literal49 – equivalent of ``literal``
• subscript50 – subscript text
• superscript51 – superscript text
• title-reference52 – for titles of books, periodicals, and other materials
Refer to Roles for roles added by Sphinx.
“Explicit markup” (ref53 ) is used in reST for most constructs that need special handling, such as footnotes,
specially-highlighted paragraphs, comments, and generic directives.
An explicit markup block begins with a line starting with .. followed by whitespace and is terminated
by the next paragraph at the same level of indentation. (There needs to be a blank line between explicit
markup and normal paragraphs. This may all sound a bit complicated, but it is intuitive enough when
you write it.)
4.1.12 Directives
A directive (ref54 ) is a generic block of explicit markup. Along with roles, it is one of the extension
mechanisms of reST, and Sphinx makes heavy use of it.
Docutils supports the following directives:
• Admonitions: attention55 , caution56 , danger57 , error58 , hint59 , important60 , note61 , tip62 , warning63
and the generic admonition64 . (Most themes style only “note” and “warning” specially.)
• Images:
– image65 (see also Images below)
47 http://docutils.sourceforge.net/docs/ref/rst/roles.html#emphasis
48 http://docutils.sourceforge.net/docs/ref/rst/roles.html#strong
49 http://docutils.sourceforge.net/docs/ref/rst/roles.html#literal
50 http://docutils.sourceforge.net/docs/ref/rst/roles.html#subscript
51 http://docutils.sourceforge.net/docs/ref/rst/roles.html#superscript
52 http://docutils.sourceforge.net/docs/ref/rst/roles.html#title-reference
53 http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#explicit-markup-blocks
54 http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#directives
55 http://docutils.sourceforge.net/docs/ref/rst/directives.html#attention
56 http://docutils.sourceforge.net/docs/ref/rst/directives.html#caution
57 http://docutils.sourceforge.net/docs/ref/rst/directives.html#danger
58 http://docutils.sourceforge.net/docs/ref/rst/directives.html#error
59 http://docutils.sourceforge.net/docs/ref/rst/directives.html#hint
60 http://docutils.sourceforge.net/docs/ref/rst/directives.html#important
61 http://docutils.sourceforge.net/docs/ref/rst/directives.html#note
62 http://docutils.sourceforge.net/docs/ref/rst/directives.html#tip
63 http://docutils.sourceforge.net/docs/ref/rst/directives.html#warning
64 http://docutils.sourceforge.net/docs/ref/rst/directives.html#admonitions
65 http://docutils.sourceforge.net/docs/ref/rst/directives.html#image
18 Chapter 4. reStructuredText
Sphinx Documentation, Release 3.0.0+/0fb832baa
rst-class.
83 http://docutils.sourceforge.net/docs/ref/rst/directives.html#meta
84 http://docutils.sourceforge.net/docs/ref/rst/directives.html#metadata-document-title
85 http://docutils.sourceforge.net/docs/ref/rst/directives.html#default-role
86 http://docutils.sourceforge.net/docs/ref/rst/directives.html#role
Since these are only per-file, better use Sphinx’s facilities for setting the default_role.
.. function:: foo(x)
foo(y, z)
:module: some.module.name
function is the directive name. It is given two arguments here, the remainder of the first line and the
second line, as well as one option module (as you can see, options are given in the lines immediately
following the arguments and indicated by the colons). Options must be indented to the same level as the
directive content.
The directive content follows after a blank line and is indented relative to the directive start.
4.1.13 Images
.. image:: gnu.png
(options)
When used within Sphinx, the file name given (here gnu.png) must either be relative to the source file,
or absolute which means that they are relative to the top source directory. For example, the file sketch/
spam.rst could refer to the image images/spam.png as ../images/spam.png or /images/spam.
png.
Sphinx will automatically copy image files over to a subdirectory of the output directory on building (e.g.
the _static directory for HTML output.)
Interpretation of image size options (width and height) is as follows: if the size has no unit or the unit
is pixels, the given size will only be respected for output channels that support pixels. Other units (like
pt for points) will be used for HTML and LaTeX output (the latter replaces pt by bp as this is the TeX
unit such that 72bp=1in).
Sphinx extends the standard docutils behavior by allowing an asterisk for the extension:
.. image:: gnu.*
Sphinx then searches for all images matching the provided pattern and determines their type. Each builder
then chooses the best image out of these candidates. For instance, if the file name gnu.* was given and
two files gnu.pdf and gnu.png existed in the source tree, the LaTeX builder would choose the former,
while the HTML builder would prefer the latter. Supported image types and choosing priority are defined
at Builders.
87 http://docutils.sourceforge.net/docs/ref/rst/directives.html#sectnum
88 http://docutils.sourceforge.net/docs/ref/rst/directives.html#header
89 http://docutils.sourceforge.net/docs/ref/rst/directives.html#footer
90 http://docutils.sourceforge.net/docs/ref/rst/directives.html#image
20 Chapter 4. reStructuredText
Sphinx Documentation, Release 3.0.0+/0fb832baa
4.1.14 Footnotes
For footnotes (ref91 ), use [#name]_ to mark the footnote location, and add the footnote body at the
bottom of the document after a “Footnotes” rubric heading, like so:
.. rubric:: Footnotes
You can also explicitly number the footnotes ([1]_) or use auto-numbered footnotes without names
([#]_).
4.1.15 Citations
Standard reST citations (ref92 ) are supported, with the additional feature that they are “global”, i.e. all
citations can be referenced from all files. Use them like so:
Citation usage is similar to footnote usage, but with a label that is not numeric or begins with #.
4.1.16 Substitutions
reST supports “substitutions” (ref93 ), which are pieces of text and/or markup referred to in the text by
|name|. They are defined like footnotes with explicit markup blocks, like this:
or this:
directive. (Be sure to give the include file a file name extension differing from that of other source files, to
avoid Sphinx finding it as a standalone document.)
Sphinx defines some default substitutions, see Substitutions.
4.1.17 Comments
Every explicit markup block which isn’t a valid markup construct (like the footnotes above) is regarded
as a comment (ref95 ). For example:
.. This is a comment.
You can indent text after a comment start to form multiline comments:
..
This whole indented block
is a comment.
Since the easiest way to include special characters like em dashes or copyright signs in reST is to directly
write them as Unicode characters, one has to specify an encoding. Sphinx assumes source files to be
encoded in UTF-8 by default; you can change this with the source_encoding config value.
4.1.19 Gotchas
There are some problems one commonly runs into while authoring reST documents:
• Separation of inline markup: As said above, inline markup spans must be separated from the
surrounding text by non-word characters, you have to use a backslash-escaped space to get around
that. See the reference96 for the details.
• No nested inline markup: Something like *see :func:`foo`* is not possible.
4.2 Roles
Sphinx uses interpreted text roles to insert semantic markup into documents. They are written as
:rolename:`content`.
Note: The default role (`content`) has no special meaning by default. You are free to use it for anything
you like, e.g. variable names; use the default_role config value to set it to a known role – the any role
to find anything or the py:obj role to find Python objects are very useful for this.
22 Chapter 4. reStructuredText
Sphinx Documentation, Release 3.0.0+/0fb832baa
Cross-references are generated by many semantic interpreted text roles. Basically, you only need to write
:role:`target`, and a link will be created to the item named target of the type indicated by role. The
link’s text will be the same as target.
There are some additional facilities, however, that make cross-referencing roles more versatile:
• You may supply an explicit title and reference target, like in reST direct hyperlinks: :role:`title
<target>` will refer to target, but the link text will be title.
• If you prefix the content with !, no reference/hyperlink will be created.
• If you prefix the content with ~, the link text will only be the last component of the target. For
example, :py:meth:`~Queue.Queue.get` will refer to Queue.Queue.get but only display get
as the link text. This does not work with all cross-reference roles, but is domain specific.
In HTML output, the link’s title attribute (that is e.g. shown as a tool-tip on mouse-hover) will
always be the full target name.
Cross-referencing anything
:any:
New in version 1.3.
This convenience role tries to do its best to find a valid target for its reference text.
• First, it tries standard cross-reference targets that would be referenced by doc, ref or option.
Custom objects added to the standard domain by extensions (see Sphinx.
add_object_type()) are also searched.
• Then, it looks for objects (targets) in all loaded domains. It is up to the domains how specific
a match must be. For example, in the Python domain a reference of :any:`Builder` would
match the sphinx.builders.Builder class.
If none or multiple targets are found, a warning will be emitted. In the case of multiple targets, you
can change “any” to a specific role.
This role is a good candidate for setting default_role. If you do, you can write cross-references
without a lot of markup overhead. For example, in this Python function documentation
.. function:: install()
there could be references to a glossary term (usually :term:`handler`), a Python module (usually
:py:mod:`signal` or :mod:`signal`) and a section (usually :ref:`about-signals`).
The any role also works together with the intersphinx extension: when no local cross-reference
is found, all object types of intersphinx inventories are also searched.
Cross-referencing objects
4.2. Roles 23
Sphinx Documentation, Release 3.0.0+/0fb832baa
• JavaScript
• ReST
:ref:
To support cross-referencing to arbitrary locations in any document, the standard reST labels are
used. For this to work label names must be unique throughout the entire documentation. There are
two ways in which you can refer to labels:
• If you place a label directly before a section title, you can reference to it with
:ref:`label-name`. For example:
.. _my-reference-label:
Section to cross-reference
--------------------------
The :ref: role would then generate a link to the section, with the link title being “Section to
cross-reference”. This works just as well when section and reference are in different source files.
Automatic labels also work with figures. For example:
.. _my-figure:
.. figure:: whatever
Figure caption
In this case, a reference :ref:`my-figure` would insert a reference to the figure with link
text “Figure caption”.
The same works for tables that are given an explicit caption using the table97 directive.
• Labels that aren’t placed before a section title can still be referenced, but you must give the link
an explicit title, using this syntax: :ref:`Link title <label-name>`.
Note: Reference labels must start with an underscore. When referencing a label, the underscore
must be omitted (see examples above).
Using ref is advised over standard reStructuredText links to sections (like `Section title`_)
because it works across files, when section headings are changed, will raise warnings if incorrect,
and works for all builders that support cross-references.
Cross-referencing documents
24 Chapter 4. reStructuredText
Sphinx Documentation, Release 3.0.0+/0fb832baa
:doc:
Link to the specified document; the document name can be specified in absolute or relative fashion.
For example, if the reference :doc:`parrot` occurs in the document sketches/index, then the
link refers to sketches/parrot. If the reference is :doc:`/people` or :doc:`../people`,
the link refers to people.
If no explicit link text is given (like usual: :doc:`Monty Python members </people>`), the
link caption will be the title of the given document.
The given filename is usually relative to the directory the current source file is contained in, but if it
absolute (starting with /), it is taken as relative to the top source directory.
The example.py file will be copied to the output directory, and a suitable link generated to it.
Not to show unavailable download links, you should wrap whole paragraphs that have this role:
.. only:: builder_html
The following roles do possibly create a cross-reference, but do not refer to objects:
4.2. Roles 25
Sphinx Documentation, Release 3.0.0+/0fb832baa
:envvar:
An environment variable. Index entries are generated. Also generates a link to the matching envvar
directive, if it exists.
:token:
The name of a grammar token (used to create links between productionlist directives).
:keyword:
The name of a keyword in Python. This creates a link to a reference label with that name, if it exists.
:option:
A command-line option to an executable program. This generates a link to a option directive, if it
exists.
The following role creates a cross-reference to a term in a glossary:
:term:
Reference to a term in a glossary. A glossary is created using the glossary directive containing a
definition list with terms and definitions. It does not have to be in the same file as the term markup,
for example the Python docs have one global glossary in the glossary.rst file.
If you use a term that’s not explained in a glossary, you’ll get a warning during build.
4.2.2 Math
:math:
Role for inline math. Use like this:
:eq:
Same as math:numref.
The following roles don’t do anything special except formatting the text in a different style:
:abbr:
An abbreviation. If the role content contains a parenthesized explanation, it will be treated specially:
it will be shown in a tool-tip in HTML, and output only once in LaTeX.
Example: :abbr:`LIFO (last-in, first-out)`.
New in version 0.6.
:command:
The name of an OS-level command, such as rm.
:dfn:
Mark the defining instance of a term in the text. (No index entries are generated.)
:file:
The name of a file or directory. Within the contents, you can use curly braces to indicate a “variable”
part, for example:
In the built documentation, the x will be displayed differently to indicate that it is to be replaced by
the Python minor version.
26 Chapter 4. reStructuredText
Sphinx Documentation, Release 3.0.0+/0fb832baa
:guilabel:
Labels presented as part of an interactive user interface should be marked using guilabel. This
includes labels from text-based interfaces such as those created using curses or other text-based
libraries. Any label used in the interface should be marked with this role, including button labels,
window titles, field names, menu and menu selection names, and even values in selection lists.
Changed in version 1.0: An accelerator key for the GUI label can be included using an ampersand;
this will be stripped and displayed underlined in the output (example: :guilabel:`&Cancel`).
To include a literal ampersand, double it.
:kbd:
Mark a sequence of keystrokes. What form the key sequence takes may depend on platform- or
application-specific conventions. When there are no relevant conventions, the names of modifier
keys should be spelled out, to improve accessibility for new users and non-native speakers. For
example, an xemacs key sequence may be marked like :kbd:`C-x C-f`, but without reference
to a specific application or platform, the same sequence should be marked as :kbd:`Control-x
Control-f`.
:mailheader:
The name of an RFC 822-style mail header. This markup does not imply that the header is being used
in an email message, but can be used to refer to any header of the same “style.” This is also used
for headers defined by the various MIME specifications. The header name should be entered in the
same way it would normally be found in practice, with the camel-casing conventions being preferred
where there is more than one common usage. For example: :mailheader:`Content-Type`.
:makevar:
The name of a make variable.
:manpage:
A reference to a Unix manual page including the section, e.g. :manpage:`ls(1)`. Creates a
hyperlink to an external site rendering the manpage if manpages_url is defined.
:menuselection:
Menu selections should be marked using the menuselection role. This is used to mark a complete
sequence of menu selections, including selecting submenus and choosing a specific operation, or any
subsequence of such a sequence. The names of individual selections should be separated by -->.
For example, to mark the selection “Start > Programs”, use this markup:
When including a selection that includes some trailing indicator, such as the ellipsis some operating
systems use to indicate that the command opens a dialog, the indicator should be omitted from the
selection name.
menuselection also supports ampersand accelerators just like guilabel.
:mimetype:
The name of a MIME type, or a component of a MIME type (the major or minor portion, taken
alone).
:newsgroup:
The name of a Usenet newsgroup.
:program:
The name of an executable program. This may differ from the file name for the executable for some
platforms. In particular, the .exe (or other) extension should be omitted for Windows programs.
4.2. Roles 27
Sphinx Documentation, Release 3.0.0+/0fb832baa
:regexp:
A regular expression. Quotes should not be included.
:samp:
A piece of literal text, such as code. Within the contents, you can use curly braces to indicate a
“variable” part, as in file. For example, in :samp:`print 1+{variable}`, the part variable
would be emphasized.
If you don’t need the “variable part” indication, use the standard ``code`` instead.
Changed in version 1.8: Allowed to escape curly braces with backslash
There is also an index role to generate index entries.
The following roles generate external links:
:pep:
A reference to a Python Enhancement Proposal. This generates appropriate index entries. The text
“PEP number” is generated; in the HTML output, this text is a hyperlink to an online copy of the
specified PEP. You can link to a specific section by saying :pep:`number#anchor`.
:rfc:
A reference to an Internet Request for Comments. This generates appropriate index entries. The text
“RFC number” is generated; in the HTML output, this text is a hyperlink to an online copy of the
specified RFC. You can link to a specific section by saying :rfc:`number#anchor`.
Note that there are no special roles for including hyperlinks as you can use the standard reST markup for
that purpose.
4.2.4 Substitutions
The documentation system provides three substitutions that are defined by default. They are set in the
build configuration file.
|release|
Replaced by the project release the documentation refers to. This is meant to be the full version
string including alpha/beta/release candidate tags, e.g. 2.5.2b3. Set by release.
|version|
Replaced by the project version the documentation refers to. This is meant to consist only of the
major and minor version parts, e.g. 2.5, even for version 2.5.1. Set by version.
|today|
Replaced by either today’s date (the date on which the document is read), or the date set in the build
configuration file. Normally has the format April 14, 2007. Set by today_fmt and today.
4.3 Directives
As previously discussed, a directive is a generic block of explicit markup. While Docutils provides a number
of directives, Sphinx provides many more and uses directives as one of the primary extension mechanisms.
See Domains for roles added by domains.
See also:
Refer to the reStructuredText Primer for an overview of the directives provided by Docutils.
28 Chapter 4. reStructuredText
Sphinx Documentation, Release 3.0.0+/0fb832baa
Since reST does not have facilities to interconnect several documents, or split documents into multiple
output files, Sphinx uses a custom directive to add relations between the single files the documentation is
made of, as well as tables of contents. The toctree directive is the central element.
Note: Simple “inclusion” of one file in another can be done with the include98 directive.
Note: To create table of contents for current document (.rst file), use the standard reST contents directive99 .
.. toctree::
This directive inserts a “TOC tree” at the current location, using the individual TOCs (including
“sub-TOC trees”) of the documents given in the directive body. Relative document names (not
beginning with a slash) are relative to the document the directive occurs in, absolute names are
relative to the source directory. A numeric maxdepth option may be given to indicate the depth of
the tree; by default, all levels are included.110
Consider this example (taken from the Python docs’ library reference index):
.. toctree::
:maxdepth: 2
intro
strings
datatypes
numeric
(many more documents listed here)
.. toctree::
intro
All about strings <strings>
datatypes
The second line above will link to the strings document, but will use the title “All about strings”
instead of the title of the strings document.
You can also add external links, by giving an HTTP URL instead of a document name.
98 http://docutils.sourceforge.net/docs/ref/rst/directives.html#include
99 http://docutils.sourceforge.net/docs/ref/rst/directives.html#table-of-contents
110 The LaTeX writer only refers the maxdepth option of first toctree directive in the document.
4.3. Directives 29
Sphinx Documentation, Release 3.0.0+/0fb832baa
Section numbering
If you want to have section numbers even in HTML output, give the toplevel toctree a numbered
option. For example:
.. toctree::
:numbered:
foo
bar
Numbering then starts at the heading of foo. Sub-toctrees are automatically numbered (don’t give
the numbered flag to those).
Numbering up to a specific depth is also possible, by giving the depth as a numeric argument to
numbered.
Additional options
You can use caption option to provide a toctree caption and you can use name option to provide
implicit target name that can be referenced by using ref:
.. toctree::
:caption: Table of Contents
:name: mastertoc
foo
If you want only the titles of documents in the tree to show up, not other headings of the same level,
you can use the titlesonly option:
.. toctree::
:titlesonly:
foo
bar
You can use “globbing” in toctree directives, by giving the glob flag option. All entries are then
matched against the list of available documents, and matches are inserted into the list alphabetically.
Example:
.. toctree::
:glob:
intro*
recipe/*
*
This includes first all documents whose names start with intro, then all documents in the recipe
folder, then all remaining documents (except the one containing the directive, of course.)111
The special entry name self stands for the document containing the toctree directive. This is useful
if you want to generate a “sitemap” from the toctree.
You can use the reversed flag option to reverse the order of the entries in the list. This can be
useful when using the glob flag option to reverse the ordering of the files. Example:
111 A note on available globbing syntax: you can use the standard shell constructs , ?, [...] and [!...] with the feature that
*
these all don’t match slashes. A double star ** can be used to match any sequence of characters including slashes.
30 Chapter 4. reStructuredText
Sphinx Documentation, Release 3.0.0+/0fb832baa
.. toctree::
:glob:
:reversed:
recipe/*
You can also give a “hidden” option to the directive, like this:
.. toctree::
:hidden:
doc_1
doc_2
This will still notify Sphinx of the document hierarchy, but not insert links into the document at the
location of the directive – this makes sense if you intend to insert these links yourself, in a different
style, or in the HTML sidebar.
In cases where you want to have only one top-level toctree and hide all other lower level toctrees
you can add the “includehidden” option to the top-level toctree entry:
.. toctree::
:includehidden:
doc_1
doc_2
All other toctree entries can then be eliminated by the “hidden” option.
In the end, all documents in the source directory (or subdirectories) must occur in some toctree
directive; Sphinx will emit a warning if it finds a file that is not included, because that means that
this file will not be reachable through standard navigation.
Use exclude_patterns to explicitly exclude documents or directories from building completely.
Use the “orphan” metadata to let a document be built, but notify Sphinx that it is not reachable via a
toctree.
The “master document” (selected by master_doc) is the “root” of the TOC tree hierarchy. It can be
used as the documentation’s main page, or as a “full table of contents” if you don’t give a maxdepth
option.
Changed in version 0.3: Added “globbing” option.
Changed in version 0.6: Added “numbered” and “hidden” options as well as external links and
support for “self” references.
Changed in version 1.0: Added “titlesonly” option.
Changed in version 1.1: Added numeric argument to “numbered”.
Changed in version 1.2: Added “includehidden” option.
Changed in version 1.3: Added “caption” and “name” option.
Special names
Sphinx reserves some document names for its own use; you should not try to create documents with these
names – it will cause problems.
The special document names (and pages generated for them) are:
4.3. Directives 31
Sphinx Documentation, Release 3.0.0+/0fb832baa
Warning: Be careful with unusual characters in filenames. Some formats may interpret these charac-
ters in unexpected ways:
• Do not use the colon : for HTML based formats. Links to other parts may not work.
• Do not use the plus + for the ePub format. Some resources may not be found.
These directives create short paragraphs and can be used inside information units as well as normal text.
.. note::
An especially important bit of information about an API that a user should be aware of when using
whatever bit of API the note pertains to. The content of the directive should be written in complete
sentences and include all appropriate punctuation.
Example:
.. note::
.. warning::
An important bit of information about an API that a user should be very aware of when using
whatever bit of API the warning pertains to. The content of the directive should be written in
complete sentences and include all appropriate punctuation. This differs from note in that it is
recommended over note for information regarding security.
.. versionadded:: version
This directive documents the version of the project which added the described feature to the library
or C API. When this applies to an entire module, it should be placed at the top of the module section
before any prose.
The first argument must be given and is the version in question; you can add a second argument
consisting of a brief explanation of the change.
Example:
.. versionadded:: 2.5
The *spam* parameter.
32 Chapter 4. reStructuredText
Sphinx Documentation, Release 3.0.0+/0fb832baa
Note that there must be no blank line between the directive head and the explanation; this is to make
these blocks visually continuous in the markup.
.. versionchanged:: version
Similar to versionadded, but describes when and what changed in the named feature in some
way (new parameters, changed side effects, etc.).
.. deprecated:: version
Similar to versionchanged, but describes when the feature was deprecated. An explanation can
also be given, for example to inform the reader what should be used instead. Example:
.. deprecated:: 3.1
Use :func:`spam` instead.
.. seealso::
Many sections include a list of references to module documentation or external documents. These
lists are created using the seealso directive.
The seealso directive is typically placed in a section just before any subsections. For the HTML
output, it is shown boxed off from the main flow of the text.
The content of the seealso directive should be a reST definition list. Example:
.. seealso::
Module :py:mod:`zipfile`
Documentation of the :py:mod:`zipfile` standard module.
Note: If the title of the rubric is “Footnotes” (or the selected language’s equivalent), this rubric is
ignored by the LaTeX writer, since it is assumed to only contain footnote definitions and therefore
would create an empty heading.
.. centered::
This directive creates a centered boldfaced line of text. Use it as follows:
.. centered:: LICENSE AGREEMENT
Deprecated since version 1.1: This presentation-only directive is a legacy from older versions. Use a
rst-class directive instead and add an appropriate style.
.. hlist::
This directive must contain a bullet list. It will transform it into a more compact list by either
distributing more than one item horizontally, or reducing spacing between items, depending on the
builder.
For builders that support the horizontal distribution, there is a columns option that specifies the
number of columns; it defaults to 2. Example:
4.3. Directives 33
Sphinx Documentation, Release 3.0.0+/0fb832baa
.. hlist::
:columns: 3
* A list of
* short items
* that should be
* displayed
* horizontally
There are multiple ways to show syntax-highlighted literal code blocks in Sphinx: using reST doctest blocks;
using reST literal blocks, optionally in combination with the highlight directive; using the code-block
directive; and using the literalinclude directive. Doctest blocks can only be used to show interactive
Python sessions, while the remaining three can be used for other languages. Of these three, literal blocks
are useful when an entire document, or at least large sections of it, use code blocks with the same syntax
and which should be styled in the same manner. On the other hand, the code-block directive makes
more sense when you want more fine-tuned control over the styling of each block or when you have a
document containing code blocks using multiple varied syntaxes. Finally, the literalinclude directive
is useful for including entire code files in your documentation.
In all cases, Syntax highlighting is provided by Pygments100 . When using literal blocks, this is configured
using any highlight directives in the source file. When a highlight directive is encountered, it
is used until the next highlight directive is encountered. If there is no highlight directive in the
file, the global highlighting language is used. This defaults to python but can be configured using the
highlight_language config value. The following values are supported:
• none (no highlighting)
• default (similar to python3 but with a fallback to none without warning highlighting fails; the
default when highlight_language isn’t set)
• guess (let Pygments guess the lexer based on contents, only works with certain well-recognizable
languages)
• python
• rest
• c
• . . . and any other lexer alias that Pygments supports101
If highlighting with the selected language fails (i.e. Pygments emits an “Error” token), the block is not
highlighted in any way.
Important: The list of lexer aliases supported is tied to the Pygment version. If you want to ensure
consistent highlighting, you should fix your version of Pygments.
.. highlight:: language
Example:
100 http://pygments.org
101 http://pygments.org/docs/lexers/
34 Chapter 4. reStructuredText
Sphinx Documentation, Release 3.0.0+/0fb832baa
.. highlight:: c
This language is used until the next highlight directive is encountered. As discussed previously,
language can be any lexer alias supported by Pygments.
Additional options
Pygments can generate line numbers for code blocks. To enable this, use the linenothreshold
option.
.. highlight:: python
:linenothreshold: 5
This will produce line numbers for all code blocks longer than five lines.
To ignore minor errors on highlighting, you can specifiy :force: option.
Changed in version 2.1: :force: option.
.. code-block:: [language]
Example:
.. code-block:: ruby
The directive’s alias name sourcecode works as well. This directive takes a language name as
an argument. It can be any lexer alias supported by Pygments. If it is not given, the setting of
highlight directive will be used. If not set, highlight_language will be used.
Additional options
Pygments can generate line numbers for code blocks. To enable this for, use the linenos flag option.
.. code-block:: ruby
:linenos:
The first line number can be selected with the lineno-start option. If present, linenos flag is
automatically activated:
.. code-block:: ruby
:lineno-start: 10
.. code-block:: python
:emphasize-lines: 3,5
def some_function():
interesting = False
print 'This line is highlighted.'
print 'This one is not...'
print '...but this one is.'
4.3. Directives 35
Sphinx Documentation, Release 3.0.0+/0fb832baa
A caption option can be given to show that name before the code block. A name option can be
provided implicit target name that can be referenced by using ref. For example:
.. code-block:: python
:caption: this.py
:name: this-py
A dedent option can be given to strip indentation characters from the code block. For example:
.. code-block:: ruby
:dedent: 4
.. literalinclude:: example.py
The file name is usually relative to the current file’s path. However, if it is absolute (starting with /),
it is relative to the top source directory.
Additional options
Like code-block, the directive supports the linenos flag option to switch on line numbers, the
lineno-start option to select the first line number, the emphasize-lines option to emphasize
particular lines, the name option to provide an implicit target name, the dedent option to strip
indentation characters for the code block, and a language option to select a language different
from the current file’s standard language. In addition, it supports the caption option; however,
this can be provided with no argument to use the filename as the caption. Example with options:
.. literalinclude:: example.rb
:language: ruby
:emphasize-lines: 12,15-18
:linenos:
Tabs in the input are expanded if you give a tab-width option with the desired tab width.
Include files are assumed to be encoded in the source_encoding. If the file has a different encod-
ing, you can specify it with the encoding option:
.. literalinclude:: example.py
:encoding: latin-1
112 There is a standard .. include directive, but it raises errors if the file is not found. This one only emits a warning.
36 Chapter 4. reStructuredText
Sphinx Documentation, Release 3.0.0+/0fb832baa
The directive also supports including only parts of the file. If it is a Python module, you can select a
class, function or method to include using the pyobject option:
.. literalinclude:: example.py
:pyobject: Timer.start
This would only include the code lines belonging to the start() method in the Timer class within
the file.
Alternately, you can specify exactly which lines to include by giving a lines option:
.. literalinclude:: example.py
:lines: 1,3,5-10,20-
.. literalinclude:: example.py
:diff: example.py.orig
This shows the diff between example.py and example.py.orig with unified diff format.
A force option can ignore minor errors on highlighting.
Changed in version 0.4.3: Added the encoding option.
Changed in version 0.6: Added the pyobject, lines, start-after and end-before options, as
well as support for absolute filenames.
Changed in version 1.0: Added the prepend, append, and tab-width options.
Changed in version 1.3: Added the diff, lineno-match, caption, name, and dedent options.
Changed in version 1.5: Added the start-at, and end-at options.
Changed in version 1.6: With both start-after and lines in use, the first line as per
start-after is considered to be with line number 1 for lines.
Changed in version 2.1: Added the force option.
4.3. Directives 37
Sphinx Documentation, Release 3.0.0+/0fb832baa
4.3.4 Glossary
.. glossary::
This directive must contain a reST definition-list-like markup with terms and definitions. The defi-
nitions will then be referenceable with the term role. Example:
.. glossary::
environment
A structure where information about all documents under the root is
saved, and used for cross-referencing. The environment is pickled
after the parsing stage, so that successive runs only need to read
and parse new and changed documents.
source directory
The directory which, including its subdirectories, contains all
source files for one Sphinx project.
In contrast to regular definition lists, multiple terms per entry are allowed, and inline markup is
allowed in terms. You can link to all of the terms. For example:
.. glossary::
term 1
term 2
Definition of both terms.
(When the glossary is sorted, the first term determines the sort order.)
If you want to specify “grouping key” for general index entries, you can put a “key” as “term : key”.
For example:
.. glossary::
term 1 : A
term 2 : B
Definition of both terms.
Note that “key” is used for grouping key as is. The “key” isn’t normalized; key “A” and “a” become
different groups. The whole characters in “key” is used instead of a first character; it is used for
“Combining Character Sequence” and “Surrogate Pairs” grouping key.
In i18n situation, you can specify “localized term : key” even if original text only have “term” part.
In this case, translated “localized term” will be categorized in “key” group.
New in version 0.6: You can now give the glossary directive a :sorted: flag that will automatically
sort the entries alphabetically.
Changed in version 1.1: Now supports multiple terms and inline markup in terms.
Changed in version 1.4: Index key for glossary term should be considered experimental.
38 Chapter 4. reStructuredText
Sphinx Documentation, Release 3.0.0+/0fb832baa
that it can be used for presentation and email address. The domain name portion of the address
should be lower case. Example:
By default, this markup isn’t reflected in the output in any way (it helps keep track of contributions),
but you can set the configuration value show_authors to True to make them produce a paragraph
in the output.
.. codeauthor:: name <email>
The codeauthor directive, which can appear multiple times, names the authors of the described
code, just like sectionauthor names the author(s) of a piece of documentation. It too only pro-
duces output if the show_authors configuration value is True.
Sphinx automatically creates index entries from all object descriptions (like functions, classes or attributes)
like discussed in Domains.
However, there is also explicit markup available, to make the index more comprehensive and enable index
entries in documents where information is not mainly contained in information units, such as the language
reference.
.. index:: <entries>
This directive contains one or more index entries. Each entry consists of a type and a value, separated
by a colon.
For example:
.. index::
single: execution; context
module: __main__
module: sys
triple: module; search; path
...
This directive contains five entries, which will be converted to entries in the generated index which
link to the exact location of the index statement (or, in case of offline media, the corresponding page
number).
Since index directives generate cross-reference targets at their location in the source, it makes sense
to put them before the thing they refer to – e.g. a heading, as in the example above.
The possible entry types are:
single Creates a single index entry. Can be made a subentry by separating the subentry text with a
semicolon (this notation is also used below to describe what entries are created).
pair pair: loop; statement is a shortcut that creates two index entries, namely loop;
statement and statement; loop.
triple Likewise, triple: module; search; path is a shortcut that creates three index entries,
which are module; search path, search; path, module and path; module search.
see see: entry; other creates an index entry that refers from entry to other.
4.3. Directives 39
Sphinx Documentation, Release 3.0.0+/0fb832baa
.. index:: Python
.. index:: ! Python
then the backlink to the latter page is emphasized among the three backlinks.
For index directives containing only “single” entries, there is a shorthand notation:
.. only:: <expression>
Include the content of the directive only if the expression is true. The expression should consist of
tags, like this:
Undefined tags are false, defined tags (via the -t command-line option or within conf.py, see here)
are true. Boolean expressions, also using parentheses (like html and (latex or draft)) are
supported.
The format and the name of the current builder (html, latex or text) are always set as a tag113 .
To make the distinction between format and name explicit, they are also added with the prefix
format_ and builder_, e.g. the epub builder defines the tags html, epub, format_html and
builder_epub.
113 For most builders name and format are the same. At the moment only builders derived from the html builder distinguish
40 Chapter 4. reStructuredText
Sphinx Documentation, Release 3.0.0+/0fb832baa
These standard tags are set after the configuration file is read, so they are not available there.
All tags must follow the standard Python identifier syntax as set out in the Identifiers and key-
words102 documentation. That is, a tag expression may only consist of tags that conform to the
syntax of Python variables. In ASCII, this consists of the uppercase and lowercase letters A through
Z, the underscore _ and, except for the first character, the digits 0 through 9.
New in version 0.6.
Changed in version 1.2: Added the name of the builder and the prefixes.
Warning: This directive is designed to control only content of document. It could not control
sections, labels and so on.
4.3.8 Tables
|l|l|l|
which means three left-adjusted, nonbreaking columns. For columns with longer text that should
automatically be broken, use either the standard p{width} construct, or tabulary’s automatic spec-
ifiers:
The automatic widths of the LRCJ columns are attributed by tabulary in proportion to the ob-
served shares in a first pass where the table cells are rendered at their natural “horizontal” widths.
By default, Sphinx uses a table layout with J for every column.
New in version 0.3.
102 https://docs.python.org/3/reference/lexical_analysis.html#identifiers
103 http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#grid-tables
104 http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#simple-tables
105 http://docutils.sourceforge.net/docs/ref/rst/directives.html#csv-table
106 http://docutils.sourceforge.net/docs/ref/rst/directives.html#list-table
107 http://docutils.sourceforge.net/docs/ref/rst/directives.html#table
4.3. Directives 41
Sphinx Documentation, Release 3.0.0+/0fb832baa
Changed in version 1.6: Merged cells may now contain multiple paragraphs and are much better
handled, thanks to custom Sphinx LaTeX macros. This novel situation motivated the switch to J
specifier and not L by default.
Hint: Sphinx actually uses T specifier having done \newcolumntype{T}{J}. To revert to previous
default, insert \newcolumntype{T}{L} in the LaTeX preamble (see latex_elements).
A frequent issue with tabulary is that columns with little contents are “squeezed”. The minimal
column width is a tabulary parameter called \tymin. You may set it globally in the LaTeX preamble
via \setlength{\tymin}{40pt} for example.
Else, use the tabularcolumns directive with an explicit p{40pt} (for example) for that column.
You may use also l specifier but this makes the task of setting column widths more difficult if some
merged cell intersects that column.
Warning: Tables with more than 30 rows are rendered using longtable, not tabulary, in
order to allow pagebreaks. The L, R, . . . specifiers do not work for these tables.
Tables that contain list-like elements such as object descriptions, blockquotes or any kind of lists
cannot be set out of the box with tabulary. They are therefore set with the standard LaTeX
tabular (or longtable) environment if you don’t give a tabularcolumns directive. If you
do, the table will be set with tabulary but you must use the p{width} construct (or Sphinx’s
\X and \Y specifiers described below) for the columns containing these elements.
Literal blocks do not work with tabulary at all, so tables containing a literal block are always
set with tabular. The verbatim environment used for literal blocks only works in p{width}
(and \X or \Y) columns, hence Sphinx generates such column specs for tables containing literal
blocks.
Since Sphinx 1.5, the \X{a}{b} specifier is used (there is a backslash in the specifier letter). It is
like p{width} with the width set to a fraction a/b of the current line width. You can use it in the
tabularcolumns (it is not a problem if some LaTeX macro is also called \X.)
It is not needed for b to be the total number of columns, nor for the sum of the fractions of the \X
specifiers to add up to one. For example |\X{2}{5}|\X{1}{5}|\X{1}{5}| is legitimate and the
table will occupy 80% of the line width, the first of its three columns having the same width as the
sum of the next two.
This is used by the :widths: option of the table108 directive.
Since Sphinx 1.6, there is also the \Y{f} specifier which admits a decimal argument, such has
\Y{0.15}: this would have the same effect as \X{3}{20}.
Changed in version 1.6: Merged cells from complex grid tables (either multi-row, multi-column, or
both) now allow blockquotes, lists, literal blocks, . . . as do regular cells.
Sphinx’s merged cells interact well with p{width}, \X{a}{b}, Y{f} and tabulary’s columns.
Note: tabularcolumns conflicts with :widths: option of table directives. If both are specified,
:widths: option will be ignored.
108 http://docutils.sourceforge.net/docs/ref/rst/directives.html#table
42 Chapter 4. reStructuredText
Sphinx Documentation, Release 3.0.0+/0fb832baa
4.3.9 Math
The input language for mathematics is LaTeX markup. This is the de-facto standard for plain-text math
notation and has the added advantage that no further translation is necessary when building LaTeX out-
put.
Keep in mind that when you put math markup in Python docstrings read by autodoc, you either have
to double all backslashes, or use Python raw strings (r"raw").
.. math::
Directive for displayed math (math that takes the whole line for itself).
The directive supports multiple equations, which should be separated by a blank line:
.. math::
In addition, each single equation is set within a split environment, which means that you can have
multiple aligned lines in an equation, aligned at & and separated by \\:
.. math::
For more details, look into the documentation of the AmSMath LaTeX package109 .
When the math is only one line of text, it can also be given as a directive argument:
Normally, equations are not numbered. If you want your equation to get a number, use the label
option. When given, it selects an internal label for the equation, by which it can be cross-referenced,
and causes an equation number to be issued. See eq for an example. The numbering style depends
on the output format.
There is also an option nowrap that prevents any wrapping of the given math in a math environ-
ment. When you give this option, you must make sure yourself that the math is properly set up. For
example:
.. math::
:nowrap:
\begin{eqnarray}
y & = & ax^2 + bx + c \\
f(x) & = & x^2 + 2xy + y^2
\end{eqnarray}
See also:
Math support for HTML outputs in Sphinx Rendering options for math with HTML builders.
latex_engine Explains how to configure LaTeX builder to support Unicode literals in math mark-up.
109 https://www.ams.org/publications/authors/tex/amslatex
4.3. Directives 43
Sphinx Documentation, Release 3.0.0+/0fb832baa
Special markup is available for displaying the productions of a formal grammar. The markup is simple
and does not attempt to model all aspects of BNF (or any derived forms), but provides enough to allow
context-free grammars to be displayed in a way that causes uses of a symbol to be rendered as hyperlinks
to the definition of the symbol. There is this directive:
.. productionlist:: [name]
This directive is used to enclose a group of productions. Each production is given on a single line
and consists of a name, separated by a colon from the following definition. If the definition spans
multiple lines, each continuation line must begin with a colon placed at the same column as in the
first line.
The argument to productionlist serves to distinguish different sets of production lists that be-
long to different grammars.
Blank lines are not allowed within productionlist directive arguments.
The definition can contain token names which are marked as interpreted text (e.g. sum ::=
`integer` "+" `integer`) – this generates cross-references to the productions of these tokens.
Outside of the production list, you can reference to token productions using token.
Note that no further reST parsing is done in the production, so that you don’t have to escape * or |
characters.
The following is an example taken from the Python Reference Manual:
.. productionlist::
try_stmt: try1_stmt | try2_stmt
try1_stmt: "try" ":" `suite`
: ("except" [`expression` ["," `target`]] ":" `suite`)+
: ["else" ":" `suite`]
: ["finally" ":" `suite`]
try2_stmt: "try" ":" `suite`
: "finally" ":" `suite`
As previously discussed, field lists are sequences of fields marked up like this:
A field list near the top of a file is normally parsed by docutils as the docinfo which is generally used
to record the author, date of publication and other metadata. However, in Sphinx, a field list preceding
any other markup is moved from the docinfo to the Sphinx environment as document metadata and is not
displayed in the output; a field list appearing after the document title will be part of the docinfo as normal
and will be displayed in the output.
At the moment, these metadata fields are recognized:
tocdepth The maximum depth for a table of contents of this file.
44 Chapter 4. reStructuredText
Sphinx Documentation, Release 3.0.0+/0fb832baa
:tocdepth: 2
:nocomments:
orphan If set, warnings about this file not being included in any toctree will be suppressed.
:orphan:
4.5 Domains
Most domains provide a number of object description directives, used to describe specific objects provided
by modules. Each directive requires one or more signatures to provide basic information about what is
being described, and the content should be the description. The basic version makes entries in the general
index; if no index entry is desired, you can give the directive option flag :noindex:. An example using
a Python domain directive:
.. py:function:: spam(eggs)
ham(eggs)
4.5. Domains 45
Sphinx Documentation, Release 3.0.0+/0fb832baa
This describes the two Python functions spam and ham. (Note that when signatures become too long, you
can break them if you add a backslash to lines that are continued in the next line. Example:
As you can see, both directive and role names contain the domain name and the directive name.
Default Domain
For documentation describing objects from solely one domain, authors will not have to state again its
name at each directive, role, etc. . . after having specified a default. This can be done either via the config
value primary_domain or via this directive:
.. default-domain:: name
Select a new default domain. While the primary_domain selects a global default, this only has an
effect within the same file.
If no other default is selected, the Python domain (named py) is the default one, mostly for compatibility
with documentation written for older versions of Sphinx.
Directives and roles that belong to the default domain can be mentioned without giving the domain name,
i.e.
.. function:: pyfunc()
Reference to :func:`pyfunc`.
Cross-referencing syntax
For cross-reference roles provided by domains, the same facilities exist as for general cross-references. See
Cross-referencing syntax.
In short:
• You may supply an explicit title and reference target: :role:`title <target>` will refer to
target, but the link text will be title.
• If you prefix the content with !, no reference/hyperlink will be created.
• If you prefix the content with ~, the link text will only be the last component of the target. For
example, :py:meth:`~Queue.Queue.get` will refer to Queue.Queue.get but only display get
as the link text.
The Python domain (name py) provides the following directives for module declarations:
46 Chapter 4. reStructuredText
Sphinx Documentation, Release 3.0.0+/0fb832baa
.. py:module:: name
This directive marks the beginning of the description of a module (or package submodule, in which
case the name should be fully qualified, including the package name). It does not create content
(like e.g. py:class does).
This directive will also cause an entry in the global module index.
options
options
4.5. Domains 47
Sphinx Documentation, Release 3.0.0+/0fb832baa
.. py:class:: name
.. py:class:: name(parameters)
Describes a class. The signature can optionally include parentheses with parameters which will be
shown as the constructor arguments. See also Python Signatures.
Methods and attributes belonging to the class should be placed in this directive’s body. If they are
placed outside, the supplied name should contain the class name so that cross-references still work.
Example:
.. py:class:: Foo
.. py:method:: quux()
-- or --
.. py:class:: Bar
.. py:method:: Bar.quux()
options
48 Chapter 4. reStructuredText
Sphinx Documentation, Release 3.0.0+/0fb832baa
.. py:classmethod:: name(parameters)
Like py:method, but indicates that the method is a class method.
New in version 0.6.
.. py:decorator:: name
.. py:decorator:: name(parameters)
Describes a decorator function. The signature should represent the usage as a decorator. For exam-
ple, given the functions
def removename(func):
func.__name__ = ''
return func
def setnewname(name):
def decorator(func):
func.__name__ = name
return func
return decorator
.. py:decorator:: removename
.. py:decorator:: setnewname(name)
Python Signatures
Signatures of functions, methods and class constructors can be given like they would be written in Python.
Default values for optional arguments can be given (but if they contain commas, they will confuse the sig-
nature parser). Python 3-style argument annotations can also be given as well as return type annotations:
For functions with optional parameters that don’t have default values (typically functions implemented
in C extension modules without keyword argument support), you can use brackets to specify the optional
parts:
compile(source[, filename[, symbol ]])
It is customary to put the opening bracket before the comma.
4.5. Domains 49
Sphinx Documentation, Release 3.0.0+/0fb832baa
Note: In current release, all var, ivar and cvar are represented as “Variable”. There is no difference at
all.
The field names must consist of one of these keywords and an argument (except for returns and rtype,
which do not need an argument). This is best explained by an example:
50 Chapter 4. reStructuredText
Sphinx Documentation, Release 3.0.0+/0fb832baa
:param int priority: The priority of the message, can be a number 1-5
Multiple types in a type field will be linked automatically if separated by the word “or”:
The following roles refer to objects in modules and are possibly hyperlinked if a matching identifier is
found:
:py:mod:
Reference a module; a dotted name may be used. This should also be used for package names.
:py:func:
Reference a Python function; dotted names may be used. The role text needs not include
trailing parentheses to enhance readability; they will be added automatically by Sphinx if the
add_function_parentheses config value is True (the default).
:py:data:
Reference a module-level variable.
:py:const:
Reference a “defined” constant. This may be a Python variable that is not intended to be changed.
:py:class:
Reference a class; a dotted name may be used.
:py:meth:
Reference a method of an object. The role text can include the type name and the method name; if it
occurs within the description of a type, the type name can be omitted. A dotted name may be used.
:py:attr:
Reference a data attribute of an object.
:py:exc:
Reference an exception. A dotted name may be used.
:py:obj:
Reference an object of unspecified type. Useful e.g. as the default_role.
New in version 0.4.
4.5. Domains 51
Sphinx Documentation, Release 3.0.0+/0fb832baa
The name enclosed in this markup can include a module name and/or a class name. For example,
:py:func:`filter` could refer to a function named filter in the current module, or the built-in
function of that name. In contrast, :py:func:`foo.filter` clearly refers to the filter function in
the foo module.
Normally, names in these roles are searched first without any further qualification, then with the current
module name prepended, then with the current module and class name (if any) prepended. If you prefix
the name with a dot, this order is reversed. For example, in the documentation of Python’s codecs
module, :py:func:`open` always refers to the built-in function, while :py:func:`.open` refers to
codecs.open().
A similar heuristic is used to determine whether the name is an attribute of the currently documented
class.
Also, if the name is prefixed with a dot, and no exact match is found, the target is taken as a suffix and all
object names with that suffix are searched. For example, :py:meth:`.TarFile.close` references the
tarfile.TarFile.close() function, even if the current module is not tarfile. Since this can get
ambiguous, if there is more than one possible match, you will get a warning from Sphinx.
Note that you can combine the ~ and . prefixes: :py:meth:`~.TarFile.close` will reference the
tarfile.TarFile.close() method, but the visible link caption will only be close().
This is also used to describe function-like preprocessor macros. The names of the arguments should
be given so they may be used in the description.
Note that you don’t have to backslash-escape asterisks in the signature, as it is not parsed by the
reST inliner.
.. c:member:: declaration
Describes a C struct member. Example signature:
The text of the description should include the range of values allowed, how the value should be
interpreted, and whether the value can be changed. References to structure members in text should
use the member role.
.. c:macro:: name
Describes a “simple” C macro. Simple macros are macros which are used for code expansion,
but which do not take arguments so cannot be described as functions. This is a simple C-
language #define. Examples of its use in the Python documentation include PyObject_HEAD
and Py_BEGIN_ALLOW_THREADS.
.. c:type:: name
Describes a C type (whether defined by a typedef or struct). The signature should just be the type
name.
.. c:var:: declaration
Describes a global C variable. The signature should include the type, such as:
52 Chapter 4. reStructuredText
Sphinx Documentation, Release 3.0.0+/0fb832baa
Cross-referencing C constructs
The following roles create cross-references to C-language constructs if they are defined in the documenta-
tion:
:c:func:
Reference a C-language function. Should include trailing parentheses.
:c:member:
Reference a C-language member of a struct.
:c:macro:
Reference a “simple” C macro, as defined above.
:c:type:
Reference a C-language type.
:c:data:
Reference a C-language variable.
The following directives are available. All declarations can start with a visibility statement (public,
private or protected).
.. cpp:class:: class specifier
.. cpp:struct:: class specifier
Describe a class/struct, possibly with specification of inheritance, e.g.,:
The difference between cpp:class and cpp:struct is only cosmetic: the prefix rendered in the
output, and the specifier shown in the index.
The class can be directly declared inside a nested scope, e.g.,:
4.5. Domains 53
Sphinx Documentation, Release 3.0.0+/0fb832baa
.. cpp:class:: template<> \
std::array<bool, 256>
A casting operator.
A constexpr function.
.. cpp:function:: template<> \
void print(int i)
.. cpp:member:: int a = 42
54 Chapter 4. reStructuredText
Sphinx Documentation, Release 3.0.0+/0fb832baa
.. cpp:type:: MyContainer::const_iterator
.. cpp:enum:: MyEnum
An unscoped enum.
.. cpp:enum-class:: MyScopedEnum
(continues on next page)
4.5. Domains 55
Sphinx Documentation, Release 3.0.0+/0fb832baa
A scoped enum.
.. cpp:enumerator:: name
.. cpp:enumerator:: name = constant
Describe an enumerator, optionally with its value defined, e.g.,:
.. cpp:enumerator:: MyEnum::myEnumerator
.. cpp:enumerator:: MyEnum::myOtherEnumerator = 42
.. cpp:union:: name
Describe a union.
New in version 1.8.
.. cpp:concept:: template-parameter-list name
Warning: The support for concepts is experimental. It is based on the current draft standard
and the Concepts Technical Specification. The features may change as they evolve.
Describe a concept. It must have exactly 1 template parameter list. The name may be a nested name.
Example:
**Notation**
.. cpp:var:: It r
An lvalue.
**Valid Expressions**
56 Chapter 4. reStructuredText
Sphinx Documentation, Release 3.0.0+/0fb832baa
Notation
It r
An lvalue.
Valid Expressions
• *r, when r is dereferenceable.
• ++r, with return type It&, when r is incrementable.
New in version 1.5.
Options
Anonymous Entities
C++ supports anonymous namespaces, classes, enums, and unions. For the sake of documentation they
must be given some name that starts with @, e.g., @42 or @data. These names can also be used in cross-
references and (type) expressions, though nested symbols will be found even when omitted. The @...
name will always be rendered as [anonymous] (possibly as a link).
Example:
.. cpp:class:: Data
.. cpp:union:: @data
.. cpp:var:: int a
.. cpp:var:: double b
union [anonymous]
int a
double b
Explicit ref: Data::[anonymous]::a. Short-hand ref: Data::a.
New in version 1.8.
4.5. Domains 57
Sphinx Documentation, Release 3.0.0+/0fb832baa
Aliasing Declarations
Sometimes it may be helpful list declarations elsewhere than their main documentation, e.g., when creating
a synopsis of a class interface. The following directive can be used for this purpose.
.. cpp:alias:: name or function signature
Insert one or more alias declarations. Each entity can be specified as they can in the cpp:any role.
If the name of a function is given (as opposed to the complete signature), then all overloads of the
function will be listed.
For example:
.. cpp:alias:: Data::a
overload_example::C::f
becomes
int a
void f (double d) const
void f (double d)
void f (int i)
void f ()
whereas:
becomes
void f (double d) const
void f (double d)
New in version 2.0.
Constrained Templates
Warning: The support for concepts is experimental. It is based on the current draft standard and the
Concepts Technical Specification. The features may change as they evolve.
Placeholders
Declarations may use the name of a concept to introduce constrained template parameters, or the keyword
auto to introduce unconstrained template parameters:
58 Chapter 4. reStructuredText
Sphinx Documentation, Release 3.0.0+/0fb832baa
Template Introductions
Simple constrained function or class templates can be declared with a template introduction instead of a
template parameter list:
:cpp:expr:
:cpp:texpr:
Insert a C++ expression or type either as inline code (cpp:expr) or inline text (cpp:texpr). For
example:
.. cpp:var:: int a = 42
4.5. Domains 59
Sphinx Documentation, Release 3.0.0+/0fb832baa
Namespacing
Declarations in the C++ domain are as default placed in global scope. The current scope can be changed
using three namespace directives. They manage a stack declarations where cpp:namespace resets the
stack and changes a given scope.
The cpp:namespace-push directive changes the scope to a given inner scope of the current one.
The cpp:namespace-pop directive undoes the most recent cpp:namespace-push directive.
.. cpp:namespace:: scope specification
Changes the current scope for the subsequent objects to the given scope, and resets the namespace
directive stack. Note that the namespace does not need to correspond to C++ namespaces, but can
end in names of classes, e.g.,:
.. cpp:namespace:: Namespace1::Namespace2::SomeClass::AnInnerClass
All subsequent objects will be defined as if their name were declared with the scope prepended. The
subsequent cross-references will be searched for starting in the current scope.
Using NULL, 0, or nullptr as the scope will change to global scope.
A namespace declaration can also be templated, e.g.,:
declares size as a member function of the class template std::vector. Equivalently this could
have been declared using:
or:
.. cpp:namespace:: A::B
.. cpp:namespace-push:: C::D
60 Chapter 4. reStructuredText
Sphinx Documentation, Release 3.0.0+/0fb832baa
.. cpp:namespace:: A::B
.. cpp:namespace-push:: C::D
.. cpp:namespace-pop::
.. cpp:namespace:: nullptr
.. cpp:namespace-push:: A::B
The C++ directives support the following info fields (see also Info field lists):
• param, parameter, arg, argument: Description of a parameter.
• tparam: Description of a template parameter.
• returns, return: Description of a return value.
• throws, throw, exception: Description of a possibly thrown exception.
Cross-referencing
4.5. Domains 61
Sphinx Documentation, Release 3.0.0+/0fb832baa
These roles follow the Sphinx Cross-referencing syntax rules. This means care must be taken when refer-
encing a (partial) template specialization, e.g. if the link looks like this: :cpp:class:`MyClass<int>`.
This is interpreted as a link to int with a title of MyClass. In this case, escape the opening angle bracket
with a backslash, like this: :cpp:class:`MyClass\<int>`.
When a custom title is not needed it may be useful to use the roles for inline expressions, cpp:expr and
cpp:texpr, where angle brackets do not need escaping.
For linking to non-templated declarations the name must be a nested name, e.g., f or MyClass::f.
When a (member) function is referenced using just its name, the reference will point to an arbitrary
matching overload. The cpp:any and cpp:func roles use an alternative format, which simply is a
complete function declaration. This will resolve to the exact matching overload. As example, consider the
following class declaration:
class C
Templated declarations
template<typename TOuter>
class Outer
template<typename TInner>
class Inner
62 Chapter 4. reStructuredText
Sphinx Documentation, Release 3.0.0+/0fb832baa
In general the reference must include the template parameter declarations, and template arguments for
the prefix of qualified names. For example:
• template\<typename TOuter> Wrapper::Outer (template<typename TOuter>
Wrapper::Outer)
• template\<typename TOuter> template\<typename TInner>
Wrapper::Outer<TOuter>::Inner (template<typename TOuter> template<typename
TInner> Wrapper::Outer<TOuter>::Inner)
Currently the lookup only succeed if the template parameter identifiers are equal strings. That is,
template\<typename UOuter> Wrapper::Outer will not work.
As a shorthand notation, if a template parameter list is omitted, then the lookup will assume either a
primary template or a non-template, but not a partial template specialisation. This means the following
references work as well:
• Wrapper::Outer (Wrapper::Outer)
• Wrapper::Outer::Inner (Wrapper::Outer::Inner)
• template\<typename TInner> Wrapper::Outer::Inner (template<typename TInner>
Wrapper::Outer::Inner)
template<typename TInner>
class Inner
template<>
class Outer<int>
template<typename TInner>
class Inner
template<>
class Inner<bool>
In general the reference must include a template parameter list for each template argument list.
The full specialisation above can therefore be referenced with template\<> Outer\<int>
(template<> Outer<int>) and template\<> template\<> Outer\<int>::Inner\<bool>
(template<> template<> Outer<int>::Inner<bool>). As a shorthand the empty template
parameter list can be omitted, e.g., Outer\<int> (Outer<int>) and Outer\<int>::Inner\<bool>
(Outer<int>::Inner<bool>).
4.5. Domains 63
Sphinx Documentation, Release 3.0.0+/0fb832baa
References to partial specialisations must always include the template parameter lists, e.g.,
template\<typename T> Outer\<T*> (template<typename T> Outer<T*>). Currently the
lookup only succeed if the template parameter identifiers are equal strings.
Configuration Variables
The so-called “standard” domain collects all markup that doesn’t warrant a domain of its own. Its direc-
tives and roles are not prefixed with a domain name.
The standard domain is also where custom object descriptions, added using the add_object_type()
API, are placed.
There is a set of directives allowing documenting command-line programs:
.. option:: name args, name args, ...
Describes a command line argument or switch. Option argument names should be enclosed in angle
brackets. Examples:
.. option:: dest_dir
Destination directory.
The directive will create cross-reference targets for the given options, referenceable by option
(in the example case, you’d use something like :option:`dest_dir`, :option:`-m`, or
:option:`--module`).
cmdoption directive is a deprecated alias for the option directive.
.. envvar:: name
Describes an environment variable that the documented code or program uses or defines. Refer-
enceable by envvar.
.. program:: name
Like py:currentmodule, this directive produces no output. Instead, it serves to notify Sphinx that
all following option directives document options for the program called name.
If you use program, you have to qualify the references in your option roles by the program name,
so if you have the following situation
.. program:: rm
.. option:: -r
Work recursively.
.. program:: svn
.. option:: -r revision
(continues on next page)
64 Chapter 4. reStructuredText
Sphinx Documentation, Release 3.0.0+/0fb832baa
then :option:`rm -r` would refer to the first option, while :option:`svn -r` would refer to
the second one.
The program name may contain spaces (in case you want to document subcommands like svn add
and svn commit separately).
New in version 0.5.
There is also a very generic object description directive, which is not tied to any domain:
.. describe:: text
.. object:: text
This directive produces the same formatting as the specific ones provided by domains, but does not
create index entries or cross-referencing targets. Example:
.. describe:: PAPER
4.5. Domains 65
Sphinx Documentation, Release 3.0.0+/0fb832baa
.. rst:directive:: foo
Foo description.
Bar description.
66 Chapter 4. reStructuredText
Sphinx Documentation, Release 3.0.0+/0fb832baa
.. rst:directive:: toctree
.. rst:directive:option:: glob
options
.. rst:directive:: toctree
.. rst:directive:option:: maxdepth
:type: integer or no value
.. rst:role:: foo
Foo description.
4.5. Domains 67
Sphinx Documentation, Release 3.0.0+/0fb832baa
.. rst:role:: math:numref
Role for cross-referencing equations defined by math directive via their label. Example:
.. math:: e^{i\pi} + 1 = 0
:label: euler
The sphinx-contrib114 repository contains more domains available as extensions; currently Ada115 , Cof-
feeScript116 , Erlang117 , HTTP118 , Lasso119 , MATLAB120 , PHP121 , and Ruby122 domains. Also available are
domains for Chapel123 , Common Lisp124 , dqn125 , Go126 , Jinja127 , Operation128 , and Scala129 .
114 https://bitbucket.org/birkenfeld/sphinx-contrib/
115 https://pypi.org/project/sphinxcontrib-adadomain/
116 https://pypi.org/project/sphinxcontrib-coffee/
117 https://pypi.org/project/sphinxcontrib-erlangdomain/
118 https://pypi.org/project/sphinxcontrib-httpdomain/
119 https://pypi.org/project/sphinxcontrib-lassodomain/
120 https://pypi.org/project/sphinxcontrib-matlabdomain/
121 https://pypi.org/project/sphinxcontrib-phpdomain/
122 https://bitbucket.org/birkenfeld/sphinx-contrib/src/default/rubydomain
123 https://pypi.org/project/sphinxcontrib-chapeldomain/
124 https://pypi.org/project/sphinxcontrib-cldomain/
125 https://pypi.org/project/sphinxcontrib-dqndomain/
126 https://pypi.org/project/sphinxcontrib-golangdomain/
127 https://pypi.org/project/sphinxcontrib-jinjadomain/
128 https://pypi.org/project/sphinxcontrib-operationdomain/
129 https://pypi.org/project/sphinxcontrib-scaladomain/
68 Chapter 4. reStructuredText
CHAPTER
FIVE
MARKDOWN
Markdown130 is a lightweight markup language with a simplistic plain text formatting syntax. It exists in
many syntactically different flavors. To support Markdown-based documentation, Sphinx can use recom-
monmark131 . recommonmark is a Docutils bridge to CommonMark-py132 , a Python package for parsing
the CommonMark133 Markdown flavor.
5.1 Configuration
Note: The configuration as explained here requires recommonmark version 0.5.0 or later.
extensions = ['recommonmark']
Changed in version 1.8: Version 1.8 deprecates and version 3.0 removes the source_parsers con-
figuration variable that was used by older recommonmark versions.
3. If you want to use Markdown files with extensions other than .md, adjust the source_suffix
variable. The following example configures Sphinx to parse all files with the extensions .md and
.txt as Markdown:
source_suffix = {
'.rst': 'restructuredtext',
'.txt': 'markdown',
'.md': 'markdown',
}
4. You can further configure recommonmark to allow custom syntax that standard CommonMark doesn’t
support. Read more in the recommonmark documentation134 .
130 https://daringfireball.net/projects/markdown/
131 https://recommonmark.readthedocs.io/en/latest/index.html
132 https://github.com/rtfd/CommonMark-py
133 https://commonmark.org/
134 https://recommonmark.readthedocs.io/en/latest/auto_structify.html
69
Sphinx Documentation, Release 3.0.0+/0fb832baa
70 Chapter 5. Markdown
CHAPTER
SIX
CONFIGURATION
The configuration directory must contain a file named conf.py. This file (containing Python code) is called
the “build configuration file” and contains (almost) all configuration needed to customize Sphinx input
and output behavior.
An optional file docutils.conf135 can be added to the configuration directory to adjust Docu-
tils136 configuration if not otherwise overridden or set by Sphinx.
The configuration file is executed as Python code at build time (using execfile(), and with the current
directory set to its containing directory), and therefore can execute arbitrarily complex code. Sphinx then
reads simple names from the file’s namespace as its configuration.
Important points to note:
• If not otherwise documented, values must be strings, and their default is the empty string.
• The term “fully-qualified name” refers to a string that names an importable Python object inside a
module; for example, the FQN "sphinx.builders.Builder" means the Builder class in the
sphinx.builders module.
• Remember that document names use / as the path separator and don’t contain the file name exten-
sion.
• Since conf.py is read as a Python file, the usual rules apply for encodings and Unicode support.
• The contents of the config namespace are pickled (so that Sphinx can find out when configuration
changes), so it may not contain unpickleable values – delete them from the namespace with del if
appropriate. Modules are removed automatically, so you don’t need to del your imports after use.
• There is a special object named tags available in the config file. It can be used to query and change
the tags (see Including content based on tags). Use tags.has('tag') to query, tags.add('tag')
and tags.remove('tag') to change. Only tags set via the -t command-line option or via tags.
add('tag') can be queried using tags.has('tag'). Note that the current builder tag is not
available in conf.py, as it is created after the builder is initialized.
project
The documented project’s name.
author
The author name(s) of the document. The default value is 'unknown'.
copyright
A copyright statement in the style '2008, Author Name'.
135 http://docutils.sourceforge.net/docs/user/config.html
136 http://docutils.sourceforge.net/
71
Sphinx Documentation, Release 3.0.0+/0fb832baa
version
The major project version, used as the replacement for |version|. For example, for the Python
documentation, this may be something like 2.6.
release
The full project version, used as the replacement for |release| and e.g. in the HTML templates.
For example, for the Python documentation, this may be something like 2.6.0rc1.
If you don’t need the separation provided between version and release, just set them both to the
same value.
extensions
A list of strings that are module names of extensions. These can be extensions coming with Sphinx
(named sphinx.ext.*) or custom ones.
Note that you can extend sys.path within the conf file if your extensions live in another directory –
but make sure you use absolute paths. If your extension path is relative to the configuration directory,
use os.path.abspath() like so:
import sys, os
sys.path.append(os.path.abspath('sphinxext'))
extensions = ['extname']
That way, you can load an extension called extname from the subdirectory sphinxext.
The configuration file itself can be an extension; for that, you only need to provide a setup()
function in it.
source_suffix
The file extensions of source files. Sphinx considers the files with this suffix as sources. The value
can be a dictionary mapping file extensions to file types. For example:
source_suffix = {
'.rst': 'restructuredtext',
'.txt': 'restructuredtext',
'.md': 'markdown',
}
By default, Sphinx only supports 'restructuredtext' file type. You can add a new file type
using source parser extensions. Please read a document of the extension to know which file type the
extension supports.
The value may also be a list of file extensions: then Sphinx will consider that they all map to the
'restructuredtext' file type.
Default is {'.rst': 'restructuredtext'}.
72 Chapter 6. Configuration
Sphinx Documentation, Release 3.0.0+/0fb832baa
source_encoding
The encoding of all reST source files. The recommended encoding, and the default value, is
'utf-8-sig'.
New in version 0.5: Previously, Sphinx accepted only UTF-8 encoded sources.
source_parsers
If given, a dictionary of parser classes for different source suffices. The keys are the suffix, the values
can be either a class or a string giving a fully-qualified name of a parser class. The parser class can
be either docutils.parsers.Parser or sphinx.parsers.Parser. Files with a suffix that is
not in the dictionary will be parsed with the default reStructuredText parser.
For example:
Note: Refer to Markdown for more information on using Markdown with Sphinx.
of other builders (currently the changes builder). (Note that the template bridge must be made
theme-aware if HTML themes are to be used.)
rst_epilog
A string of reStructuredText that will be included at the end of every source file that is read.
This is a possible place to add substitutions that should be available in every file (another being
rst_prolog). An example:
rst_epilog = """
.. |psf| replace:: Python Software Foundation
"""
rst_prolog = """
.. |psf| replace:: Python Software Foundation
"""
74 Chapter 6. Configuration
Sphinx Documentation, Release 3.0.0+/0fb832baa
• app.add_source_parser
• download.not_readable
• image.not_readable
• ref.term
• ref.ref
• ref.numref
• ref.keyword
• ref.option
• ref.citation
• ref.footnote
• ref.doc
• ref.python
• misc.highlighting_failure
• toc.secnum
• epub.unknown_project_files
• autosectionlabel.*
You can choose from these types.
Now, this option should be considered experimental.
New in version 1.4.
Changed in version 1.5: Added misc.highlighting_failure
Changed in version 1.5.1: Added epub.unknown_project_files
Changed in version 1.6: Added ref.footnote
Changed in version 2.1: Added autosectionlabel.*
needs_sphinx
If set to a major.minor version string like '1.1', Sphinx will compare it with its version and
refuse to build if it is too old. Default is no requirement.
New in version 1.0.
Changed in version 1.4: also accepts micro version string
needs_extensions
This value can be a dictionary specifying version requirements for extensions in extensions,
e.g. needs_extensions = {'sphinxcontrib.something': '1.5'}. The version strings
should be in the form major.minor. Requirements do not have to be specified for all extensions,
only for those you want to check.
This requires that the extension specifies its version to Sphinx (see Developing extensions for Sphinx
for how to do that).
New in version 1.3.
manpages_url
A URL to cross-reference manpage directives. If this is defined to https://manpages.debian.
org/{path}, the :manpage:`man(1)` role will link to <https://manpages.debian.org/man(1)>.
The patterns available are:
• page - the manual page (man)
Note: This currently affects only HTML writers but could be expanded in the future.
Note: The LaTeX builder always assigns numbers whether this option is enabled or not.
76 Chapter 6. Configuration
Sphinx Documentation, Release 3.0.0+/0fb832baa
glish) and currently applying to many languages, will be used to convert quotes and dashes to
typographically correct entities. Default: True.
New in version 1.6.6: It replaces deprecated html_use_smartypants. It applies by default to all
builders except man and text (see smartquotes_excludes.)
A docutils.conf139 file located in the configuration directory (or a global ~/.docutils file) is obeyed
unconditionally if it deactivates smart quotes via the corresponding Docutils option140 . But if it
activates them, then smartquotes does prevail.
smartquotes_action
This string, for use with Docutils 0.14 or later, customizes the Smart Quotes transform. See the
file smartquotes.py at the Docutils repository141 for details. The default 'qDe' educates normal
quote characters ", ', em- and en-Dashes ---, --, and ellipses ....
New in version 1.6.6.
smartquotes_excludes
This is a dict whose default is:
Each entry gives a sufficient condition to ignore the smartquotes setting and deactivate the Smart
Quotes transform. Accepted keys are as above 'builders' or 'languages'. The values are lists.
Note: Currently, in case of invocation of make with multiple targets, the first target name is the
only one which is tested against the 'builders' entry and it decides for all. Also, a make text
following make html needs to be issued in the form make text O="-E" to force re-parsing of
source files, as the cached ones are already transformed. On the other hand the issue does not arise
with direct usage of sphinx-build as it caches (in its default usage) the parsed source files in per
builder locations.
Hint: An alternative way to effectively deactivate (or customize) the smart quotes for a given
builder, for example latex, is to use make this way:
This can follow some make html with no problem, in contrast to the situation from the prior note.
It requires Docutils 0.14 or later.
Tip: Sphinx uses requests142 as a HTTP library internally. Therefore, Sphinx refers a certification
file on the directory pointed REQUESTS_CA_BUNDLE environment variable if tls_cacerts not set.
today
today_fmt
These values determine how to format the current date, used as the replacement for |today|.
• If you set today to a non-empty value, it is used.
• Otherwise, the current time is formatted using time.strftime() and the format given in
today_fmt.
The default is now today and a today_fmt of '%B %d, %Y' (or, if translation is enabled with
language, an equivalent format for the selected locale).
highlight_language
The default language to highlight source code in. The default is 'python3'. The value should be a
valid Pygments lexer name, see Showing code examples for more details.
New in version 0.5.
Changed in version 1.4: The default is now 'default'. It is similar to 'python3'; it is mostly a
superset of 'python' but it fallbacks to 'none' without warning if failed. 'python3' and other
languages will emit warning if failed. If you prefer Python 2 only highlighting, you can set it back
to 'python'.
highlight_options
A dictionary of options that modify how the lexer specified by highlight_language generates
highlighted source code. These are lexer-specific; for the options understood by each, see the Pyg-
ments documentation143 .
New in version 1.3.
pygments_style
The style name to use for Pygments highlighting of source code. If not set, either the theme’s default
style or 'sphinx' is selected for HTML output.
Changed in version 0.3: If the value is a fully-qualified name of a custom Pygments style class, this
is then used as custom style.
add_function_parentheses
A boolean that decides whether parentheses are appended to function and method role text (e.g. the
content of :func:`input`) to signify that the name is callable. Default is True.
add_module_names
A boolean that decides whether module names are prepended to all object names (for object types
where a “module” of some kind is defined), e.g. for py:function directives. Default is True.
show_authors
A boolean that decides whether codeauthor and sectionauthor directives produce any output
in the built files.
modindex_common_prefix
A list of prefixes that are ignored for sorting the Python module index (e.g., if this is set to ['foo.
'], then foo.bar is shown under B, not F). This can be handy if you document a project that
consists of a single package. Works only for the HTML builder currently. Default is [].
New in version 0.6.
142 http://docs.python-requests.org/en/master/
143 http://pygments.org/docs/lexers/
78 Chapter 6. Configuration
Sphinx Documentation, Release 3.0.0+/0fb832baa
trim_footnote_reference_space
Trim spaces before footnote references that are necessary for the reST parser to recognize the foot-
note, but do not look too nice in the output.
New in version 0.6.
trim_doctest_flags
If true, doctest flags (comments looking like # doctest: FLAG, ...) at the ends of lines and
<BLANKLINE> markers are removed for all code blocks showing interactive Python sessions (i.e.
doctests). Default is True. See the extension doctest for more possibilities of including doctests.
New in version 1.0.
Changed in version 1.1: Now also removes <BLANKLINE>.
These options influence Sphinx’s Native Language Support. See the documentation on Internationalization
for details.
language
The code for the language the docs are written in. Any text automatically generated by Sphinx will
be in that language. Also, Sphinx will try to substitute individual paragraphs from your documents
with the translation sets obtained from locale_dirs. Sphinx will search language-specific figures
named by figure_language_filename and substitute them for original figures. In the LaTeX builder, a
suitable language will be selected as an option for the Babel package. Default is None, which means
that no translation will be done.
New in version 0.5.
Changed in version 1.4: Support figure substitution
Currently supported languages by Sphinx are:
• bn – Bengali
• ca – Catalan
• cs – Czech
• da – Danish
• de – German
• en – English
• es – Spanish
• et – Estonian
• eu – Basque
• fa – Iranian
• fi – Finnish
• fr – French
• he – Hebrew
• hr – Croatian
• hu – Hungarian
• id – Indonesian
• it – Italian
• ja – Japanese
• ko – Korean
• lt – Lithuanian
• lv – Latvian
• mk – Macedonian
• nb_NO – Norwegian Bokmal
• ne – Nepali
• nl – Dutch
• pl – Polish
• pt_BR – Brazilian Portuguese
• pt_PT – European Portuguese
• ru – Russian
• si – Sinhala
• sk – Slovak
• sl – Slovenian
• sv – Swedish
• tr – Turkish
• uk_UA – Ukrainian
• vi – Vietnamese
• zh_CN – Simplified Chinese
• zh_TW – Traditional Chinese
locale_dirs
New in version 0.5.
Directories in which to search for additional message catalogs (see language), relative to the source
directory. The directories on this path are searched by the standard gettext module.
Internal messages are fetched from a text domain of sphinx; so if you add the directory ./locale
to this setting, the message catalogs (compiled from .po format using msgfmt) must be in ./
locale/language/LC_MESSAGES/sphinx.mo. The text domain of individual documents de-
pends on gettext_compact.
The default is ['locales'].
Changed in version 1.5: Use locales directory as a default value
gettext_compact
New in version 1.1.
If true, a document’s text domain is its docname if it is a top-level project file and its very base
directory otherwise.
By default, the document markup/code.rst ends up in the markup text domain. With this option
set to False, it is markup/code.
gettext_uuid
If true, Sphinx generates uuid information for version tracking in message catalogs. It is used for:
• Add uid line for each msgids in .pot files.
80 Chapter 6. Configuration
Sphinx Documentation, Release 3.0.0+/0fb832baa
• Calculate similarity between new msgids and previously saved old msgids. This calculation
takes a long time.
If you want to accelerate the calculation, you can use python-levenshtein 3rd-party package
written in C by using pip install python-levenshtein.
The default is False.
New in version 1.3.
gettext_location
If true, Sphinx generates location information for messages in message catalogs.
The default is True.
New in version 1.3.
gettext_auto_build
If true, Sphinx builds mo file for each translation catalog files.
The default is True.
New in version 1.3.
gettext_additional_targets
To specify names to enable gettext extracting and translation applying for i18n additionally. You can
specify below names:
Index index terms
Literal-block literal blocks: :: and code-block.
Doctest-block doctest block
Raw raw content
Image image/figure uri and alt
For example: gettext_additional_targets = ['literal-block', 'image'].
The default is [].
New in version 1.3.
figure_language_filename
The filename format for language-specific figures. The default value is {root}.
{language}{ext}. It will be expanded to dirname/filename.en.png from .. image::
dirname/filename.png. The available format tokens are:
• {root} - the filename, including any path component, without the file extension, e.g.
dirname/filename
• {path} - the directory path component of the filename, with a trailing slash if non-empty, e.g.
dirname/
• {basename} - the filename without the directory path or file extension components, e.g.
filename
• {ext} - the file extension, e.g. .png
• {language} - the translation language, e.g. en
For example, setting this to {path}{language}/{basename}{ext} will expand to dirname/
en/filename.png instead.
New in version 1.4.
Changed in version 1.5: Added {path} and {basename} tokens.
These options influence HTML as well as HTML Help output, and other builders that use Sphinx’s HTML-
Writer class.
html_theme
The “theme” that the HTML output should use. See the section about theming. The default is
'alabaster'.
New in version 0.6.
html_theme_options
A dictionary of options that influence the look and feel of the selected theme. These are theme-
specific. For the options understood by the builtin themes, see this section.
New in version 0.6.
html_theme_path
A list of paths that contain custom themes, either as subdirectories or as zip files. Relative paths are
taken as relative to the configuration directory.
New in version 0.6.
html_style
The style sheet to use for HTML pages. A file of that name must exist either in Sphinx’s static/
path, or in one of the custom paths given in html_static_path. Default is the stylesheet given
by the selected theme. If you only want to add or override a few things compared to the theme’s
stylesheet, use CSS @import to import the theme’s stylesheet.
html_title
The “title” for HTML documentation generated with Sphinx’s own templates. This is appended to
the <title> tag of individual pages, and used in the navigation bar as the “topmost” element. It
defaults to '<project> v<revision> documentation'.
html_short_title
A shorter “title” for the HTML docs. This is used in for links in the header and in the HTML Help
docs. If not given, it defaults to the value of html_title.
New in version 0.4.
82 Chapter 6. Configuration
Sphinx Documentation, Release 3.0.0+/0fb832baa
html_baseurl
The URL which points to the root of the HTML documentation. It is used to indicate the location of
document like canonical_url.
New in version 1.8.
html_context
A dictionary of values to pass into the template engine’s context for all pages. Single values can also
be put in this dictionary using the -A command-line option of sphinx-build.
New in version 0.5.
html_logo
If given, this must be the name of an image file (path relative to the configuration directory) that is
the logo of the docs. It is placed at the top of the sidebar; its width should therefore not exceed 200
pixels. Default: None.
New in version 0.4.1: The image file will be copied to the _static directory of the output HTML,
but only if the file does not already exist there.
html_favicon
If given, this must be the name of an image file (path relative to the configuration directory) that is
the favicon of the docs. Modern browsers use this as the icon for tabs, windows and bookmarks. It
should be a Windows-style icon file (.ico), which is 16x16 or 32x32 pixels large. Default: None.
New in version 0.4: The image file will be copied to the _static directory of the output HTML,
but only if the file does not already exist there.
html_css_files
A list of CSS files. The entry must be a filename string or a tuple containing the filename string and
the attributes dictionary. The filename must be relative to the html_static_path, or a full URI with
scheme like http://example.org/style.css. The attributes is used for attributes of <link>
tag. It defaults to an empty list.
Example:
html_css_files = ['custom.css'
'https://example.com/css/custom.css',
('print.css', {'media': 'print'})]
html_js_files = ['script.js',
'https://example.com/scripts/custom.js',
('custom.js', {'async': 'async'})]
As these files are not meant to be built, they are automatically excluded from source files.
Note: For security reasons, dotfiles under html_static_path will not be copied. If you would
like to copy them intentionally, please add each filepath to this setting:
Another way to do that, you can also use html_extra_path. It allows to copy dotfiles under the
directories.
Changed in version 0.4: The paths in html_static_path can now contain subdirectories.
Changed in version 1.0: The entries in html_static_path can now be single files.
Changed in version 1.8: The files under html_static_path are excluded from source files.
html_extra_path
A list of paths that contain extra files not directly related to the documentation, such as robots.txt
or .htaccess. Relative paths are taken as relative to the configuration directory. They are copied
to the output directory. They will overwrite any existing file of the same name.
As these files are not meant to be built, they are automatically excluded from source files.
New in version 1.2.
Changed in version 1.4: The dotfiles in the extra directory will be copied to the output directory. And
it refers exclude_patterns on copying extra files and directories, and ignores if path matches to
patterns.
html_last_updated_fmt
If this is not None, a ‘Last updated on:’ timestamp is inserted at every page bottom, using the
given strftime() format. The empty string is equivalent to '%b %d, %Y' (or a locale-dependent
equivalent).
html_use_smartypants
If true, quotes and dashes are converted to typographically correct entities. Default: True.
Deprecated since version 1.6: To disable smart quotes, use rather smartquotes.
html_add_permalinks
Sphinx will add “permalinks” for each heading and description environment as paragraph signs
that become visible when the mouse hovers over them.
This value determines the text for the permalink; it defaults to "¶". Set it to None or the empty
string to disable permalinks.
New in version 0.6: Previously, this was always activated.
Changed in version 1.1: This can now be a string to select the actual text of the link. Previously, only
boolean values were accepted.
html_sidebars
Custom sidebar templates, must be a dictionary that maps document names to template names.
The keys can contain glob-style patterns1 , in which case all matching documents will get the specified
sidebars. (A warning is emitted when a more than one glob-style pattern matches for any document.)
The values can be either lists or single strings.
• If a value is a list, it specifies the complete list of sidebar templates to include. If all or some of
the default sidebars are to be included, they must be put into this list as well.
84 Chapter 6. Configuration
Sphinx Documentation, Release 3.0.0+/0fb832baa
The default sidebars (for documents that don’t match any pattern) are defined by theme itself.
Builtin themes are using these templates by default: ['localtoc.html', 'relations.
html', 'sourcelink.html', 'searchbox.html'].
• If a value is a single string, it specifies a custom sidebar to be added between the
'sourcelink.html' and 'searchbox.html' entries. This is for compatibility with Sphinx
versions before 1.0.
Deprecated since version 1.7: a single string value for html_sidebars will be removed in 2.0
Builtin sidebar templates that can be rendered are:
• localtoc.html – a fine-grained table of contents of the current document
• globaltoc.html – a coarse-grained table of contents for the whole documentation set, collapsed
• relations.html – two links to the previous and next documents
• sourcelink.html – a link to the source of the current document, if enabled in
html_show_sourcelink
• searchbox.html – the “quick search” box
Example:
html_sidebars = {
'**': ['globaltoc.html', 'sourcelink.html', 'searchbox.html'],
'using/windows': ['windowssidebar.html', 'searchbox.html'],
}
This will render the custom template windowssidebar.html and the quick search box within the
sidebar of the given document, and render the default sidebars for all other pages (except that the
local TOC is replaced by the global TOC).
New in version 1.0: The ability to use globbing keys and to specify multiple sidebars.
Note that this value only has no effect if the chosen theme does not possess a sidebar, like the builtin
scrolls and haiku themes.
html_additional_pages
Additional templates that should be rendered to HTML pages, must be a dictionary that maps
document names to template names.
Example:
html_additional_pages = {
'download': 'customdownload.html',
}
html_split_index
If true, the index is generated twice: once as a single page with all the entries, and once as one page
per starting letter. Default is False.
New in version 0.4.
html_copy_source
If true, the reST sources are included in the HTML build as _sources/name. The default is True.
html_show_sourcelink
If true (and html_copy_source is true as well), links to the reST sources will be added to the
sidebar. The default is True.
New in version 0.6.
html_sourcelink_suffix
Suffix to be appended to source links (see html_show_sourcelink), unless they have this suffix
already. Default is '.txt'.
New in version 1.5.
html_use_opensearch
If nonempty, an OpenSearch144 description file will be output, and all pages will contain a <link>
tag referring to it. Since OpenSearch doesn’t support relative URLs for its search page location, the
value of this option must be the base URL from which these documents are served (without trailing
slash), e.g. "https://docs.python.org". The default is ''.
html_file_suffix
This is the file name suffix for generated HTML files. The default is ".html".
New in version 0.4.
html_link_suffix
Suffix for generated links to HTML files. The default is whatever html_file_suffix is set to; it
can be set differently (e.g. to support different web server setups).
New in version 0.6.
html_show_copyright
If true, “(C) Copyright . . . ” is shown in the HTML footer. Default is True.
New in version 1.0.
html_show_sphinx
If true, “Created using Sphinx” is shown in the HTML footer. Default is True.
New in version 0.4.
html_output_encoding
Encoding of HTML output files. Default is 'utf-8'. Note that this encoding name must both be a
valid Python encoding name and a valid HTML charset value.
New in version 1.0.
html_compact_lists
If true, a list all whose items consist of a single paragraph and/or a sub-list all whose items etc. . .
(recursive definition) will not use the <p> element for any of its items. This is standard docutils
behavior. Default: True.
New in version 1.0.
html_secnumber_suffix
Suffix for section numbers. Default: ". ". Set to " " to suppress the final dot on section numbers.
New in version 1.0.
144 http://www.opensearch.org/Home
86 Chapter 6. Configuration
Sphinx Documentation, Release 3.0.0+/0fb832baa
html_search_language
Language to be used for generating the HTML full-text search index. This defaults to the global
language selected with language. If there is no support for this language, "en" is used which
selects the English language.
Support is present for these languages:
• da – Danish
• nl – Dutch
• en – English
• fi – Finnish
• fr – French
• de – German
• hu – Hungarian
• it – Italian
• ja – Japanese
• no – Norwegian
• pt – Portuguese
• ro – Romanian
• ru – Russian
• es – Spanish
• sv – Swedish
• tr – Turkish
• zh – Chinese
html_search_options = {
'type': 'mecab',
'dic_enc': 'utf-8',
'dict': '/path/to/mecab.dic',
'lib': '/path/to/libmecab.so',
}
88 Chapter 6. Configuration
Sphinx Documentation, Release 3.0.0+/0fb832baa
html_experimental_html5_writer
Output is processed with HTML5 writer. This feature needs docutils 0.13 or newer. Default is False.
New in version 1.6.
Deprecated since version 2.0.
html4_writer
Output is processed with HTML4 writer. Default is False.
singlehtml_sidebars
Custom sidebar templates, must be a dictionary that maps document names to template names.
And it only allows a key named ‘index’. All other keys are ignored. For more information, refer to
html_sidebars. By default, it is same as html_sidebars.
Note: Apple Help output will only work on Mac OS X 10.6 and higher, as it requires the hiutil and
codesign command line tools, neither of which are Open Source.
You can disable the use of these tools using applehelp_disable_external_tools, but the result will
not be a valid help book until the indexer is run over the .lproj folders within the bundle.
applehelp_bundle_name
The basename for the Apple Help Book. Defaults to the project name.
applehelp_bundle_id
The bundle ID for the help book bundle.
Warning: You must set this value in order to generate Apple Help.
applehelp_dev_region
The development region. Defaults to 'en-us', which is Apple’s recommended setting.
applehelp_bundle_version
The bundle version (as a string). Defaults to '1'.
applehelp_icon
The help bundle icon file, or None for no icon. According to Apple’s documentation, this should
be a 16-by-16 pixel version of the application’s icon with a transparent background, saved as a PNG
file.
applehelp_kb_product
The product tag for use with applehelp_kb_url. Defaults to '<project>-<release>'.
applehelp_kb_url
The URL for your knowledgebase server, e.g. https://example.com/kbsearch.py?
p='product'&q='query'&l='lang'. Help Viewer will replace the values 'product', 'query'
and 'lang' at runtime with the contents of applehelp_kb_product, the text entered by the user
in the search box and the user’s system language respectively.
Defaults to None for no remote search.
applehelp_remote_url
The URL for remote content. You can place a copy of your Help Book’s Resources folder at this
location and Help Viewer will attempt to use it to fetch updated content.
e.g. if you set it to https://example.com/help/Foo/ and Help Viewer wants a copy of index.
html for an English speaking customer, it will look at https://example.com/help/Foo/en.
lproj/index.html.
Defaults to None for no remote content.
applehelp_index_anchors
If True, tell the help indexer to index anchors in the generated HTML. This can be useful for jump-
ing to a particular topic using the AHLookupAnchor function or the openHelpAnchor:inBook:
method in your code. It also allows you to use help:anchor URLs; see the Apple documentation
for more information on this topic.
applehelp_min_term_length
Controls the minimum term length for the help indexer. Defaults to None, which means the default
will be used.
applehelp_stopwords
Either a language specification (to use the built-in stopwords), or the path to a stopwords plist, or
None if you do not want to use stopwords. The default stopwords plist can be found at /usr/
share/hiutil/Stopwords.plist and contains, at time of writing, stopwords for the following
languages:
Language Code
English en
German de
Spanish es
French fr
Swedish sv
Hungarian hu
Italian it
90 Chapter 6. Configuration
Sphinx Documentation, Release 3.0.0+/0fb832baa
applehelp_locale
Specifies the locale to generate help for. This is used to determine the name of the .lproj folder
inside the Help Book’s Resources, and is passed to the help indexer.
Defaults to language, or if that is not set, to en.
applehelp_title
Specifies the help book title. Defaults to '<project> Help'.
applehelp_codesign_identity
Specifies the identity to use for code signing, or None if code signing is not to be performed.
Defaults to the value of the environment variable CODE_SIGN_IDENTITY, which is set by Xcode for
script build phases, or None if that variable is not set.
applehelp_codesign_flags
A list of additional arguments to pass to codesign when signing the help book.
Defaults to a list based on the value of the environment variable OTHER_CODE_SIGN_FLAGS, which
is set by Xcode for script build phases, or the empty list if that variable is not set.
applehelp_indexer_path
The path to the hiutil program. Defaults to '/usr/bin/hiutil'.
applehelp_codesign_path
The path to the codesign program. Defaults to '/usr/bin/codesign'.
applehelp_disable_external_tools
If True, the builder will not run the indexer or the code signing tool, no matter what other settings
are specified.
This is mainly useful for testing, or where you want to run the Sphinx build on a non-Mac OS X
platform and then complete the final steps on OS X for some reason.
Defaults to False.
These options influence the epub output. As this builder derives from the HTML builder, the HTML
options also apply where appropriate. The actual values for some of the options is not really important,
they just have to be entered into the Dublin Core metadata148 .
epub_basename
The basename for the epub file. It defaults to the project name.
epub_theme
The HTML theme for the epub output. Since the default themes are not optimized for small screen
space, using the same theme for HTML and epub output is usually not wise. This defaults to
'epub', a theme designed to save visual space.
epub_theme_options
A dictionary of options that influence the look and feel of the selected theme. These are theme-
specific. For the options understood by the builtin themes, see this section.
New in version 1.2.
epub_title
The title of the document. It defaults to the html_title option but can be set independently for
epub creation. It defaults to the project option.
Changed in version 2.0: It defaults to the project option.
148 http://dublincore.org/
epub_description
The description of the document. The default value is 'unknown'.
New in version 1.4.
Changed in version 1.5: Renamed from epub3_description
epub_author
The author of the document. This is put in the Dublin Core metadata. It defaults to the author
option.
epub_contributor
The name of a person, organization, etc. that played a secondary role in the creation of the content
of an EPUB Publication. The default value is 'unknown'.
New in version 1.4.
Changed in version 1.5: Renamed from epub3_contributor
epub_language
The language of the document. This is put in the Dublin Core metadata. The default is the language
option or 'en' if unset.
epub_publisher
The publisher of the document. This is put in the Dublin Core metadata. You may use any sensible
string, e.g. the project homepage. The defaults to the author option.
epub_copyright
The copyright of the document. It defaults to the copyright option but can be set independently
for epub creation.
epub_identifier
An identifier for the document. This is put in the Dublin Core metadata. For published documents
this is the ISBN number, but you can also use an alternative scheme, e.g. the project homepage. The
default value is 'unknown'.
epub_scheme
The publication scheme for the epub_identifier. This is put in the Dublin Core metadata. For
published books the scheme is 'ISBN'. If you use the project homepage, 'URL' seems reasonable.
The default value is 'unknown'.
epub_uid
A unique identifier for the document. This is put in the Dublin Core metadata. You may use a XML’s
Name format149 string. You can’t use hyphen, period, numbers as a first character. The default value
is 'unknown'.
epub_cover
The cover page information. This is a tuple containing the filenames of the cover image and the html
template. The rendered html cover page is inserted as the first item in the spine in content.opf. If
the template filename is empty, no html cover page is created. No cover at all is created if the tuple
is empty. Examples:
92 Chapter 6. Configuration
Sphinx Documentation, Release 3.0.0+/0fb832baa
epub_css_files
A list of CSS files. The entry must be a filename string or a tuple containing the filename string and
the attributes dictionary. For more information, see html_css_files.
New in version 1.8.
epub_guide
Meta data for the guide element of content.opf. This is a sequence of tuples containing the
type, the uri and the title of the optional guide information. See the OPF documentation at http:
//idpf.org/epub for details. If possible, default entries for the cover and toc types are automatically
inserted. However, the types can be explicitly overwritten if the default entries are not appropriate.
Example:
epub_pre_files = [
('index.html', 'Welcome'),
]
epub_max_image_width
This option specifies the maximum width of images. If it is set to a value greater than zero, images
with a width larger than the given value are scaled accordingly. If it is zero, no scaling is performed.
The default value is 0. You need the Python Image Library (Pillow) installed to use this option.
New in version 1.2.
epub_show_urls
Control whether to display URL addresses. This is very useful for readers that have no other means
to display the linked URL. The settings can have the following values:
• 'inline' – display URLs inline in parentheses (default)
• 'footnote' – display URLs in footnotes
• 'no' – do not display URLs
The display of inline URLs can be customized by adding CSS rules for the class link-target.
New in version 1.2.
epub_use_index
If true, add an index to the epub document. It defaults to the html_use_index option but can be
set independently for epub creation.
New in version 1.2.
epub_writing_mode
It specifies writing direction. It can accept 'horizontal' (default) and 'vertical'
Note: 2.0 adds to 'pdflatex' support in Latin language document of occasional Cyrillic or Greek
letters or words. This is not automatic, see the discussion of the latex_elements 'fontenc' key.
If your project uses Unicode characters, setting the engine to 'xelatex' or 'lualatex' and
making sure to use an OpenType font with wide-enough glyph coverage is often easier than trying
150 https://developer.mozilla.org/en-US/docs/Web/CSS/writing-mode
94 Chapter 6. Configuration
Sphinx Documentation, Release 3.0.0+/0fb832baa
to make 'pdflatex' work with the extra Unicode characters. Since Sphinx 2.0 the default is the
GNU FreeFont which covers well Latin, Cyrillic and Greek.
Contrarily to MathJaX math rendering in HTML output, LaTeX requires some ex-
tra configuration to support Unicode literals in math: the only comprehensive so-
lution (as far as we know) is to use 'xelatex' or 'lualatex' and to add
r'\usepackage{unicode-math}' (e.g. via the latex_elements 'preamble' key). You
may prefer r'\usepackage[math-style=literal]{unicode-math}' to keep a Unicode
literal such as α (U+03B1) for example as is in output, rather than being rendered as α.
latex_documents
This value determines how to group the document tree into LaTeX source files. It must be a list of tu-
ples (startdocname, targetname, title, author, documentclass, toctree_only),
where the items are:
startdocname String that specifies the document name of the LaTeX file’s master document. All doc-
uments referenced by the startdoc document in TOC trees will be included in the LaTeX file. (If
you want to use the default master document for your LaTeX build, provide your master_doc
here.)
targetname File name of the LaTeX file in the output directory.
title LaTeX document title. Can be empty to use the title of the startdoc document. This is inserted
as LaTeX markup, so special characters like a backslash or ampersand must be represented by
the proper LaTeX commands if they are to be inserted literally.
author Author for the LaTeX document. The same LaTeX markup caveat as for title applies.
Use \\and to separate multiple authors, as in: 'John \\and Sarah' (backslashes must be
Python-escaped to reach LaTeX).
documentclass Normally, one of 'manual' or 'howto' (provided by Sphinx and based on
'report', resp. 'article'; Japanese documents use 'jsbook', resp. 'jreport'.)
“howto” (non-Japanese) documents will not get appendices. Also they have a simpler title
page. Other document classes can be given. Independently of the document class, the “sphinx”
package is always loaded in order to define Sphinx’s custom LaTeX commands.
toctree_only Must be True or False. If true, the startdoc document itself is not included in the
output, only the documents referenced by it via TOC trees. With this option, you can put extra
stuff in the master document that shows up in the HTML, but not the LaTeX output.
New in version 1.2: In the past including your own document class required you to prepend the
document class name with the string “sphinx”. This is not necessary anymore.
New in version 0.3: The 6th item toctree_only. Tuples with 5 items are still accepted.
latex_logo
If given, this must be the name of an image file (relative to the configuration directory) that is the
logo of the docs. It is placed at the top of the title page. Default: None.
latex_toplevel_sectioning
This value determines the topmost sectioning unit. It should be chosen from 'part', 'chapter'
or 'section'. The default is None; the topmost sectioning unit is switched by documentclass:
section is used if documentclass will be howto, otherwise chapter will be used.
Note that if LaTeX uses \part command, then the numbering of sectioning units one level deep gets
off-sync with HTML numbering, because LaTeX numbers continuously \chapter (or \section for
howto.)
New in version 1.4.
latex_appendices
A list of document names to append as an appendix to all manuals.
latex_domain_indices
If true, generate domain-specific indices in addition to the general index. For e.g. the Python domain,
this is the global module index. Default is True.
This value can be a bool or a list of index names that should be generated, like for
html_domain_indices.
New in version 1.0.
latex_show_pagerefs
If true, add page references after internal references. This is very useful for printed copies of the
manual. Default is False.
New in version 1.0.
latex_show_urls
Control whether to display URL addresses. This is very useful for printed copies of the manual. The
setting can have the following values:
• 'no' – do not display URLs (default)
• 'footnote' – display URLs in footnotes
• 'inline' – display URLs inline in parentheses
New in version 1.0.
Changed in version 1.1: This value is now a string; previously it was a boolean value, and a true
value selected the 'inline' display. For backwards compatibility, True is still accepted.
latex_use_latex_multicolumn
The default is False: it means that Sphinx’s own macros are used for merged cells from grid tables.
They allow general contents (literal blocks, lists, blockquotes, . . . ) but may have problems if the
tabularcolumns directive was used to inject LaTeX mark-up of the type >{..}, <{..}, @{..} as
column specification.
Setting to True means to use LaTeX’s standard \multicolumn; this is incompatible with literal
blocks in the horizontally merged cell, and also with multiple paragraphs in such cell if the table is
rendered using tabulary.
New in version 1.6.
latex_use_xindy
If True, the PDF build from the LaTeX files created by Sphinx will use xindy (doc151 ) rather than
makeindex for preparing the index of general terms (from index usage). This means that words
with UTF-8 characters will get ordered correctly for the language.
• This option is ignored if latex_engine is 'platex' (Japanese documents; mendex replaces
makeindex then).
• The default is True for 'xelatex' or 'lualatex' as makeindex, if any indexed term starts
with a non-ascii character, creates .ind files containing invalid bytes for UTF-8 encoding. With
'lualatex' this then breaks the PDF build.
• The default is False for 'pdflatex' but True is recommended for non-English documents
as soon as some indexed terms use non-ascii characters from the language script.
Sphinx adds to xindy base distribution some dedicated support for using 'pdflatex' engine with
Cyrillic scripts. And whether with 'pdflatex' or Unicode engines, Cyrillic documents handle
correctly the indexing of Latin names, even with diacritics.
New in version 1.8.
151 http://xindy.sourceforge.net/
96 Chapter 6. Configuration
Sphinx Documentation, Release 3.0.0+/0fb832baa
latex_elements
New in version 0.5.
Its documentation has moved to LaTeX customization.
latex_docclass
A dictionary mapping 'howto' and 'manual' to names of real document classes that will be used
as the base for the two Sphinx classes. Default is to use 'article' for 'howto' and 'report'
for 'manual'.
New in version 1.0.
Changed in version 1.5: In Japanese docs (language is 'ja'), by default 'jreport' is used for
'howto' and 'jsbook' for 'manual'.
latex_additional_files
A list of file names, relative to the configuration directory, to copy to the build directory when
building LaTeX output. This is useful to copy files that Sphinx doesn’t copy automatically, e.g. if
they are referenced in custom LaTeX added in latex_elements. Image files that are referenced in
source files (e.g. via .. image::) are copied automatically.
You have to make sure yourself that the filenames don’t collide with those of any automatically
copied files.
New in version 0.6.
Changed in version 1.2: This overrides the files which is provided from Sphinx such as sphinx.sty.
98 Chapter 6. Configuration
Sphinx Documentation, Release 3.0.0+/0fb832baa
toctree_only Must be True or False. If true, the startdoc document itself is not included in the
output, only the documents referenced by it via TOC trees. With this option, you can put extra
stuff in the master document that shows up in the HTML, but not the Texinfo output.
New in version 1.1.
texinfo_appendices
A list of document names to append as an appendix to all manuals.
New in version 1.1.
texinfo_domain_indices
If true, generate domain-specific indices in addition to the general index. For e.g. the Python domain,
this is the global module index. Default is True.
This value can be a bool or a list of index names that should be generated, like for
html_domain_indices.
New in version 1.1.
texinfo_show_urls
Control how to display URL addresses.
• 'footnote' – display URLs in footnotes (default)
• 'no' – do not display URLs
• 'inline' – display URLs inline in parentheses
New in version 1.1.
texinfo_no_detailmenu
If true, do not generate a @detailmenu in the “Top” node’s menu containing entries for each sub-
node in the document. Default is False.
New in version 1.2.
texinfo_elements
A dictionary that contains Texinfo snippets that override those Sphinx usually puts into the gener-
ated .texi files.
• Keys that you may want to override include:
'paragraphindent' Number of spaces to indent the first line of each paragraph, default 2.
Specify 0 for no indentation.
'exampleindent' Number of spaces to indent the lines for examples or literal blocks, default
4. Specify 0 for no indentation.
'preamble' Texinfo markup inserted near the beginning of the file.
'copying' Texinfo markup inserted within the @copying block and displayed after the title.
The default value consists of a simple title page identifying the project.
• Keys that are set by other options and therefore should not be overridden are:
'author' 'body' 'date' 'direntry' 'filename' 'project' 'release' 'title'
New in version 1.1.
These options influence qthelp output. As this builder derives from the HTML builder, the HTML options
also apply where appropriate.
qthelp_basename
The basename for the qthelp file. It defaults to the project name.
qthelp_namespace
The namespace for the qthelp file. It defaults to org.sphinx.<project_name>.
<project_version>.
qthelp_theme
The HTML theme for the qthelp output. This defaults to 'nonav'.
qthelp_theme_options
A dictionary of options that influence the look and feel of the selected theme. These are theme-
specific. For the options understood by the builtin themes, see this section.
linkcheck_ignore
A list of regular expressions that match URIs that should not be checked when doing a linkcheck
build. Example:
linkcheck_ignore = [r'http://localhost:\d+/']
Note: If you want to ignore anchors of a specific page or of pages that match a specific pattern
(but still check occurrences of the same page(s) that don’t have anchors), use linkcheck_ignore
instead, for example as follows:
linkcheck_ignore = [
'http://www.sphinx-doc.org/en/1.7/intro.html#'
]
cpp_index_common_prefix
A list of prefixes that will be ignored when sorting C++ objects in the global index. For example
['awesome_lib::'].
New in version 1.5.
cpp_id_attributes
A list of strings that the parser additionally should accept as attributes. This can for example be
used when attributes have been #define d for portability.
New in version 1.5.
cpp_paren_attributes
A list of strings that the parser additionally should accept as attributes with one argument. That
is, if my_align_as is in the list, then my_align_as(X) is parsed as an attribute for all strings X
that have balanced braces ((), [], and {}). This can for example be used when attributes have been
#define d for portability.
New in version 1.5.
#
(continues on next page)
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = []
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = u'test'
# The full version, including alpha/beta/rc tags.
release = u'test'
# The reST default role (used for this markup: `text`) to use for all
# documents.
#
# default_role = None
# keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
(continues on next page)
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []
# A shorter title for the navigation bar. Default is the same as html_title.
#
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#
# html_logo = None
# the docs. This file should be a Windows icon file (.ico) being 16x16 or
,→32x32
# pixels large.
#
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#
# html_extra_path = []
# If true, the index is split into individual pages for each letter.
#
# html_split_index = False
#
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None
# A dictionary with options for the search language support, empty by default.
# 'ja' uses this config value.
# 'zh' user can custom change `jieba` dictionary path.
#
(continues on next page)
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The name of an image file (relative to this directory) to place at the top
,→of
numfig = True
#language = 'ja'
extensions.append('sphinx.ext.todo')
extensions.append('sphinx.ext.autodoc')
#extensions.append('sphinx.ext.autosummary')
extensions.append('sphinx.ext.intersphinx')
extensions.append('sphinx.ext.mathjax')
extensions.append('sphinx.ext.viewcode')
extensions.append('sphinx.ext.graphviz')
autosummary_generate = True
html_theme = 'default'
#source_suffix = ['.rst', '.txt']
SEVEN
BUILDERS
These are the built-in Sphinx builders. More builders can be added by extensions.
The builder’s “name” must be given to the -b command-line option of sphinx-build to select a builder.
class sphinx.builders.html.StandaloneHTMLBuilder
This is the standard HTML builder. Its output is a directory with HTML files, complete with style
sheets and optionally the reST sources. There are quite a few configuration values that customize
the output of this builder, see the chapter Options for HTML output for details.
name = 'html'
format = 'html'
supported_image_types = ['image/svg+xml', 'image/png', 'image/gif', 'image/jpeg']
class sphinx.builders.dirhtml.DirectoryHTMLBuilder
This is a subclass of the standard HTML builder. Its output is a directory with HTML files, where
each file is called index.html and placed in a subdirectory named like its page name. For exam-
ple, the document markup/rest.rst will not result in an output file markup/rest.html, but
markup/rest/index.html. When generating links between pages, the index.html is omitted,
so that the URL would look like markup/rest/.
name = 'dirhtml'
format = 'html'
supported_image_types = ['image/svg+xml', 'image/png', 'image/gif', 'image/jpeg']
New in version 0.6.
class sphinx.builders.singlehtml.SingleFileHTMLBuilder
This is an HTML builder that combines the whole project in one output file. (Obviously this only
works with smaller projects.) The file is named like the master document. No indices will be
generated.
name = 'singlehtml'
format = 'html'
supported_image_types = ['image/svg+xml', 'image/png', 'image/gif', 'image/jpeg']
New in version 1.0.
class sphinxcontrib.htmlhelp.HTMLHelpBuilder
This builder produces the same output as the standalone HTML builder, but also generates HTML
Help support files that allow the Microsoft HTML Help Workshop to compile them into a CHM file.
name = 'htmlhelp'
format = 'html'
109
Sphinx Documentation, Release 3.0.0+/0fb832baa
class sphinx.builders.latex.LaTeXBuilder
This builder produces a bunch of LaTeX files in the output directory. You have to specify which
documents are to be included in which LaTeX files via the latex_documents configuration value.
There are a few configuration values that customize the output of this builder, see the chapter Options
for LaTeX output for details.
The produced LaTeX file uses several LaTeX packages that may not be present in a “minimal” TeX
distribution installation.
On Ubuntu xenial, the following packages need to be installed for successful PDF builds:
• texlive-latex-recommended
• texlive-fonts-recommended
• texlive-latex-extra
• latexmk (this is a Sphinx requirement on GNU/Linux and MacOS X for functioning of make
latexpdf)
Additional packages are needed in some circumstances (see the discussion of the 'fontpkg' key
of latex_elements for more information):
• to support occasional Cyrillic letters or words, and a fortiori if language is set to a Cyrillic lan-
guage, the package texlive-lang-cyrillic is required, and, with unmodified 'fontpkg',
also cm-super or cm-super-minimal,
• to support occasional Greek letters or words (in text, not in math directive contents),
texlive-lang-greek is required, and, with unmodified 'fontpkg', also cm-super or
cm-super-minimal,
• for 'xelatex' or 'lualatex' (see latex_engine), texlive-xetex resp.
texlive-luatex, and, if leaving unchanged 'fontpkg', fonts-freefont-otf.
The testing of Sphinx LaTeX is done on Ubuntu xenial whose TeX distribution is based on a TeXLive
2015 snapshot dated March 2016.
Changed in version 1.6: Formerly, testing had been done on Ubuntu precise (TeXLive 2009).
Changed in version 2.0: Formerly, testing had been done on Ubuntu trusty (TeXLive 2013).
Note: Since 1.6, make latexpdf uses latexmk (not on Windows). This makes sure the needed
number of runs is automatically executed to get the cross-references, bookmarks, indices, and tables
of contents right.
One can pass to latexmk options via the LATEXMKOPTS Makefile variable. For example:
name = 'latex'
format = 'latex'
supported_image_types = ['application/pdf', 'image/png', 'image/jpeg']
111
Sphinx Documentation, Release 3.0.0+/0fb832baa
Note that a direct PDF builder is being provided by rinohtype154 . The builder’s name is rinoh. Refer to
the rinohtype manual155 for details.
class sphinx.builders.text.TextBuilder
This builder produces a text file for each reST file – this is almost the same as the reST source, but
with much of the markup stripped for better readability.
name = 'text'
format = 'text'
supported_image_types = []
New in version 0.4.
class sphinx.builders.manpage.ManualPageBuilder
This builder produces manual pages in the groff format. You have to specify which documents are
to be included in which manual pages via the man_pages configuration value.
name = 'man'
format = 'man'
supported_image_types = []
New in version 1.0.
class sphinx.builders.texinfo.TexinfoBuilder
This builder produces Texinfo files that can be processed into Info files by the makeinfo pro-
gram. You have to specify which documents are to be included in which Texinfo files via the
texinfo_documents configuration value.
The Info format is the basis of the on-line help system used by GNU Emacs and the terminal-based
program info. See Texinfo info for more details. The Texinfo format is the official documentation
system used by the GNU project. More information on Texinfo can be found at https://www.gnu.
org/software/texinfo/.
name = 'texinfo'
format = 'texinfo'
supported_image_types = ['image/png', 'image/jpeg', 'image/gif']
New in version 1.1.
class sphinxcontrib.serializinghtml.SerializingHTMLBuilder
This builder uses a module that implements the Python serialization API (pickle, simplejson, phpseri-
alize, and others) to dump the generated HTML documentation. The pickle builder is a subclass of
it.
A concrete subclass of this builder serializing to the PHP serialization156 format could look like this:
import phpserialize
class PHPSerializedBuilder(SerializingHTMLBuilder):
name = 'phpserialized'
implementation = phpserialize
out_suffix = '.file.phpdump'
globalcontext_filename = 'globalcontext.phpdump'
searchindex_filename = 'searchindex.phpdump'
154 https://github.com/brechtm/rinohtype
155 https://www.mos6581.org/rinohtype/quickstart.html#sphinx-builder
156 https://pypi.org/project/phpserialize/
implementation
A module that implements dump(), load(), dumps() and loads() functions that conform to the
functions with the same names from the pickle module. Known modules implementing this
interface are simplejson, phpserialize, plistlib, and others.
out_suffix
The suffix for all regular files.
globalcontext_filename
The filename for the file that contains the “global context”. This is a dict with some general
configuration values such as the name of the project.
searchindex_filename
The filename for the search index Sphinx generates.
See Serialization builder details for details about the output format.
New in version 0.5.
class sphinxcontrib.serializinghtml.PickleHTMLBuilder
This builder produces a directory with pickle files containing mostly HTML fragments and TOC in-
formation, for use of a web application (or custom postprocessing tool) that doesn’t use the standard
HTML templates.
See Serialization builder details for details about the output format.
name = 'pickle'
The old name web still works as well.
format = 'html'
supported_image_types = ['image/svg+xml', 'image/png', 'image/gif', 'image/jpeg']
The file suffix is .fpickle. The global context is called globalcontext.pickle, the search index
searchindex.pickle.
class sphinxcontrib.serializinghtml.JSONHTMLBuilder
This builder produces a directory with JSON files containing mostly HTML fragments and TOC in-
formation, for use of a web application (or custom postprocessing tool) that doesn’t use the standard
HTML templates.
See Serialization builder details for details about the output format.
name = 'json'
format = 'html'
supported_image_types = ['image/svg+xml', 'image/png', 'image/gif', 'image/jpeg']
The file suffix is .fjson. The global context is called globalcontext.json, the search index
searchindex.json.
New in version 0.5.
class sphinx.builders.gettext.MessageCatalogBuilder
This builder produces gettext-style message catalogs. Each top-level file or subdirectory grows a
single .pot catalog template.
See the documentation on Internationalization for further reference.
name = 'gettext'
format = ''
supported_image_types = []
New in version 1.1.
113
Sphinx Documentation, Release 3.0.0+/0fb832baa
class sphinx.builders.changes.ChangesBuilder
This builder produces an HTML overview of all versionadded, versionchanged and
deprecated directives for the current version. This is useful to generate a ChangeLog file, for
example.
name = 'changes'
format = ''
supported_image_types = []
class sphinx.builders.dummy.DummyBuilder
This builder produces no output. The input is only parsed and checked for consistency. This is
useful for linting purposes.
name = 'dummy'
supported_image_types = []
New in version 1.4.
class sphinx.builders.linkcheck.CheckExternalLinksBuilder
This builder scans all documents for external links, tries to open them with requests, and writes
an overview which ones are broken and redirected to standard output and to output.txt in the
output directory.
name = 'linkcheck'
format = ''
supported_image_types = []
Changed in version 1.5: Since Sphinx-1.5, the linkcheck builder comes to use requests module.
class sphinx.builders.xml.XMLBuilder
This builder produces Docutils-native XML files. The output can be transformed with standard XML
tools such as XSLT processors into arbitrary final forms.
name = 'xml'
format = 'xml'
supported_image_types = []
New in version 1.2.
class sphinx.builders.xml.PseudoXMLBuilder
This builder is used for debugging the Sphinx/Docutils “Reader to Transform to Writer” pipeline.
It produces compact pretty-printed “pseudo-XML”, files where nesting is indicated by indentation
(no end-tags). External attributes for all elements are output, and internal attributes for any leftover
“pending” elements are also given.
name = 'pseudoxml'
format = 'pseudoxml'
supported_image_types = []
New in version 1.2.
Built-in Sphinx extensions that offer more builders are:
• doctest
• coverage
All serialization builders outputs one file per source file and a few special files. They also copy the reST
source files in the directory _sources under the output directory.
The PickleHTMLBuilder is a builtin subclass that implements the pickle serialization interface.
The files per source file have the extensions of out_suffix, and are arranged in directories just as the
source files are. They unserialize to a dictionary (or dictionary like structure) with these keys:
body The HTML “body” (that is, the HTML rendering of the source file), as rendered by the HTML
translator.
title The title of the document, as HTML (may contain markup).
toc The table of contents for the file, rendered as an HTML <ul>.
display_toc A boolean that is True if the toc contains more than one entry.
current_page_name The document name of the current file.
parents, prev and next Information about related chapters in the TOC tree. Each relation is a dic-
tionary with the keys link (HREF for the relation) and title (title of the related document, as
HTML). parents is a list of relations, while prev and next are a single relation.
sourcename The name of the source file under _sources.
The special files are located in the root output directory. They are:
SerializingHTMLBuilder.globalcontext_filename A pickled dict with these keys:
project, copyright, release, version The same values as given in the configuration file.
style html_style.
last_updated Date of last build.
builder Name of the used builder, in the case of pickles this is always 'pickle'.
titles A dictionary of all documents’ titles, as HTML strings.
SerializingHTMLBuilder.searchindex_filename An index that can be used for searching the
documentation. It is a pickled list with these entries:
• A list of indexed docnames.
• A list of document titles, as HTML strings, in the same order as the first list.
• A dict mapping word roots (processed by an English-language stemmer) to a list of integers,
which are indices into the first list.
environment.pickle The build environment. This is always a pickle file, independent of the builder
and a copy of the environment that was used when the builder was started.
Unlike the other pickle files this pickle file requires that the sphinx package is available on unpick-
ling.
EIGHT
EXTENSIONS
Since many projects will need special features in their documentation, Sphinx allows adding “extensions”
to the build process, each of which can modify almost any aspect of document processing.
This chapter describes the extensions bundled with Sphinx. For the API documentation on writing your
own extension, refer to Developing extensions for Sphinx.
These extensions are built in and can be activated by respective entries in the extensions configuration
value:
This extension can import the modules you are documenting, and pull in documentation from docstrings
in a semi-automatic way.
Note: For Sphinx (actually, the Python interpreter that executes Sphinx) to find your module, it must be
importable. That means that the module or the package must be in one of the directories on sys.path –
adapt your sys.path in the configuration file accordingly.
Warning: autodoc imports the modules to be documented. If any modules have side effects on
import, these will be executed by autodoc when sphinx-build is run.
If you document scripts (as opposed to library modules), make sure their main routine is protected by
a if __name__ == '__main__' condition.
For this to work, the docstrings must of course be written in correct reStructuredText. You can then use all
of the usual Sphinx markup in the docstrings, and it will end up correctly in the documentation. Together
with hand-written documentation, this technique eases the pain of having to maintain two locations for
documentation, while at the same time avoiding auto-generated-looking pure API documentation.
If you prefer NumPy157 or Google158 style docstrings over reStructuredText, you can also enable the
napoleon extension. napoleon is a preprocessor that converts your docstrings to correct reStructured-
Text before autodoc processes them.
157 https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt
158 https://github.com/google/styleguide/blob/gh-pages/pyguide.md#38-comments-and-docstrings
117
Sphinx Documentation, Release 3.0.0+/0fb832baa
Directives
autodoc provides several directives that are versions of the usual py:module, py:class and so forth.
On parsing time, they import the corresponding module and extract the docstring of the given objects,
inserting them into the page source under a suitable py:module, py:class etc. directive.
Note: Just as py:class respects the current py:module, autoclass will also do so. Likewise,
automethod will respect the current py:class.
.. automodule::
.. autoclass::
.. autoexception::
Document a module, class or exception. All three directives will by default only insert the docstring
of the object itself:
.. autoclass:: Noodle
.. class:: Noodle
Noodle's docstring.
The “auto” directives can also contain content of their own, it will be inserted into the resulting
non-auto directive source after the docstring (but before any automatic member documentation).
Therefore, you can also mix automatic and non-automatic member documentation, like so:
.. autoclass:: Noodle
:members: eat, slurp
.. method:: boil(time=10)
.. automodule:: noodle
:members:
.. autoclass:: Noodle
:members:
will document all non-private member functions and properties (that is, those whose name
doesn’t start with _).
For modules, __all__ will be respected when looking for members unless you give the
ignore-module-all flag option. Without ignore-module-all, the order of the members
will also be the order in __all__.
You can also give an explicit list of members; only these will then be documented:
.. autoclass:: Noodle
:members: eat, slurp
• If you want to make the members option (or other options described below) the default, see
autodoc_default_options.
Tip: You can use a negated form, 'no-flag', as an option of autodoc directive, to disable it
temporarily. For example:
.. automodule:: foo
:no-undoc-members:
• Members without docstrings will be left out, unless you give the undoc-members flag option:
.. automodule:: noodle
:members:
:undoc-members:
• “Private” members (that is, those named like _private or __private) will be included if the
private-members flag option is given.
New in version 1.1.
• Python “special” members (that is, those named like __special__) will be included if the
special-members flag option is given:
.. autoclass:: my.Class
:members:
:private-members:
:special-members:
.. autoclass:: Noodle
:members:
:inherited-members:
This can be combined with undoc-members to document all available members of the class or
module.
Note: this will lead to markup errors if the inherited members come from a module whose
docstrings are not reST formatted.
New in version 0.3.
• It’s possible to override the signature for explicitly documented callable objects (functions,
methods, classes) with the regular syntax that will override the signature gained from intro-
spection:
.. autoclass:: Noodle(type)
.. automethod:: eat(persona)
.. autodata:: CD_DRIVE
:annotation:
You can tell sphinx what should be printed after the name:
.. autodata:: CD_DRIVE
:annotation: = your CD device name
For module data members and class attributes, documentation can either be put into a comment
with special formatting (using a #: to start the comment instead of just #), or in a docstring after the
definition. Comments need to be either on a line of their own before the definition, or immediately
after the assignment on the same line. The latter form is restricted to one line only.
This means that in the following class definition, all attributes can be autodocumented:
class Foo:
"""Docstring for class Foo."""
baz = 2
"""Docstring for class attribute Foo.baz."""
def __init__(self):
#: Doc comment for instance attribute qux.
self.qux = 3
self.spam = 4
"""Docstring for instance attribute spam."""
Changed in version 0.6: autodata and autoattribute can now extract docstrings.
Changed in version 1.1: Comment docs are now allowed on the same line after an assignment.
Changed in version 1.2: autodata and autoattribute have an annotation option.
Changed in version 2.0: autodecorator added.
Note: If you document decorated functions or methods, keep in mind that autodoc retrieves its
docstrings by importing the module and inspecting the __doc__ attribute of the given function or
method. That means that if a decorator replaces the decorated function with another, it must copy
the original __doc__ to the new function.
From Python 2.5, functools.wraps() can be used to create well-behaved decorating functions.
Configuration
"class" Only the class’ docstring is inserted. This is the default. You can still document __init__
as a separate method using automethod or the members option to autoclass.
"both" Both the class’ and the __init__ method’s docstring are concatenated and inserted.
"init" Only the __init__ method’s docstring is inserted.
New in version 0.3.
If the class has no __init__ method or if the __init__ method’s docstring is empty, but the class
has a __new__ method’s docstring, it is used instead.
New in version 1.4.
autodoc_member_order
This value selects if automatically documented members are sorted alphabetical (value
'alphabetical'), by member type (value 'groupwise') or by source order (value 'bysource').
The default is alphabetical.
Note that for source order, the module must be a Python module with the source code available.
New in version 0.6.
Changed in version 1.0: Support for 'bysource'.
autodoc_default_flags
This value is a list of autodoc directive flags that should be automatically applied
to all autodoc directives. The supported flags are 'members', 'undoc-members',
'private-members', 'special-members', 'inherited-members', 'show-inheritance',
'ignore-module-all' and 'exclude-members'.
New in version 1.0.
Deprecated since version 1.8: Integrated into autodoc_default_options.
autodoc_default_options
The default options for autodoc directives. They are applied to all autodoc directives automatically.
It must be a dictionary which maps option names to the values. For example:
autodoc_default_options = {
'members': 'var1, var2',
'member-order': 'bysource',
'special-members': '__init__',
'undoc-members': True,
'exclude-members': '__weakref__'
}
Setting None or True to the value is equivalent to giving only the option name to the directives.
The supported options are 'members', 'member-order', 'undoc-members',
'private-members', 'special-members', 'inherited-members', 'show-inheritance',
'ignore-module-all', 'imported-members' and 'exclude-members'.
New in version 1.8.
Changed in version 2.0: Accepts True as a value.
Changed in version 2.1: Added 'imported-members'.
autodoc_docstring_signature
Functions imported from C modules cannot be introspected, and therefore the signature for such
functions cannot be automatically determined. However, it is an often-used convention to put the
signature into the first line of the function’s docstring.
If this boolean value is set to True (which is the default), autodoc will look at the first line of the
docstring for functions and methods, and if it looks like a signature, use the line as the signature
and remove it from the docstring content.
New in version 1.1.
autodoc_mock_imports
This value contains a list of modules to be mocked up. This is useful when some external depen-
dencies are not met at build time and break the building process. You may only specify the root
package of the dependencies themselves and omit the sub-modules:
autodoc_mock_imports = ["django"]
Docstring preprocessing
Skipping members
autodoc allows the user to define a custom method for determining whether a member should be included
in the documentation by using the following event:
A Plain Title
-------------
Internally, this extension generates the labels for each section. If same section names are used in whole of
document, any one is used for a target by default. The autosectionlabel_prefix_document config-
uration variable can be used to make headings which appear multiple times but in different documents
unique.
Configuration
autosectionlabel_prefix_document
True to prefix each section label with the name of the document it is in, followed by a colon. For
example, index:Introduction for a section called Introduction that appears in document
index.rst. Useful for avoiding ambiguity when the same section heading appears in different
documents.
autosectionlabel_maxdepth
If set, autosectionlabel chooses the sections for labeling by its depth. For example, when set 1
to autosectionlabel_maxdepth, labels are generated only for top level sections, and deeper
sections are not labeled. It defaults to None (disabled).
.. currentmodule:: sphinx
.. autosummary::
environment.BuildEnvironment
util.relative_uri
.. autosummary::
:toctree: DIRNAME
sphinx.environment.BuildEnvironment
sphinx.util.relative_uri
The toctree option also signals to the sphinx-autogen script that stub pages should be
generated for the entries listed in this directive. The option accepts a directory name as an
argument; sphinx-autogen will by default place its output in this directory. If no argument
is given, output is placed in the same directory as the file that contains the directive.
• If you don’t want the autosummary to show function signatures in the listing, include the
nosignatures option:
.. autosummary::
:nosignatures:
sphinx.environment.BuildEnvironment
sphinx.util.relative_uri
• You can specify a custom template with the template option. For example,
.. autosummary::
:template: mytemplate.rst
sphinx.environment.BuildEnvironment
would use the template mytemplate.rst in your templates_path to generate the pages for
all entries listed. See Customizing templates below.
New in version 1.0.
The sphinx-autogen script can be used to conveniently generate stub documentation pages for items
included in autosummary listings.
For example, the command
will read all autosummary tables in the *.rst files that have the :toctree: option set, and output
corresponding stub pages in directory generated for all documented items. The generated pages by
default contain text of the form:
sphinx.util.relative_uri
========================
.. autofunction:: sphinx.util.relative_uri
If the -o option is not given, the script will place the output files in the directories specified in the
:toctree: options.
For more information, refer to the sphinx-autogen documentation
If you do not want to create stub pages with sphinx-autogen, you can also use these config values:
autosummary_generate
Boolean indicating whether to scan all found documents for autosummary directives, and to generate
stub pages for each.
Can also be a list of documents for which stub pages should be generated.
The new files will be placed in the directories specified in the :toctree: options of the directives.
autosummary_mock_imports
This value contains a list of modules to be mocked up. See autodoc_mock_imports for more
details. It defaults to autodoc_mock_imports.
New in version 2.0.
autosummary_imported_members
A boolean flag indicating whether to document classes and functions imported in modules. Default
is False
New in version 2.1.
Customizing templates
Note: If you find yourself spending much time tailoring the stub templates, this may indicate that it’s a
better idea to write custom narrative documentation instead.
functions
List containing names of “public” functions in the module. Here, “public” here means that the name
does not start with an underscore. Only available for modules.
classes
List containing names of “public” classes in the module. Only available for modules.
exceptions
List containing names of “public” exceptions in the module. Only available for modules.
methods
List containing names of “public” methods in the class. Only available for classes.
attributes
List containing names of “public” attributes in the class. Only available for classes.
Additionally, the following filters are available
escape(s)
Escape any special characters in the text to be used in formatting RST contexts. For instance, this
prevents asterisks making things bold. This replaces the builtin Jinja escape filter159 that does html-
escaping.
underline(s, line=’=’)
Add a title underline to a piece of text.
For instance, {{ fullname | escape | underline }} should be used to produce the title of a page.
Note: You can use the autosummary directive in the stub pages. Stub pages are generated also based
on these directives.
Several configuration values can be used to specify what the builder should check:
coverage_ignore_modules
coverage_ignore_functions
coverage_ignore_classes
coverage_ignore_pyobjects
List of Python regular expressions160 .
If any of these regular expressions matches any part of the full import path of a Python object, that
Python object is excluded from the documentation coverage report.
New in version 2.1.
coverage_c_path
159 http://jinja.pocoo.org/docs/2.9/templates/#escape
160 https://docs.python.org/library/re
coverage_c_regexes
coverage_ignore_c_items
coverage_write_headline
Set to False to not write headlines.
New in version 1.1.
coverage_skip_undoc_in_source
Skip objects that are not documented in the source with a docstring. False by default.
New in version 1.1.
This extension allows you to test snippets in the documentation in a natural way. It works by collecting
specially-marked up code blocks and running them as doctest tests.
Within one document, test code is partitioned in groups, where each group consists of:
• zero or more setup code blocks (e.g. importing the module to test)
• one or more test blocks
When building the docs with the doctest builder, groups are collected for each document and run one
after the other, first executing setup code blocks, then the test blocks in the order they appear in the file.
There are two kinds of test blocks:
• doctest-style blocks mimic interactive sessions by interleaving Python code (including the interpreter
prompt) and output.
• code-output-style blocks consist of an ordinary piece of Python code, and optionally, a piece of output
for that code.
Directives
The group argument below is interpreted as follows: if it is empty, the block is assigned to the group
named default. If it is *, the block is assigned to all groups (including the default group). Otherwise,
it must be a comma-separated list of group names.
.. testsetup:: [group]
A setup code block. This code is not shown in the output for other builders, but executed before the
doctests of the group(s) it belongs to.
.. testcleanup:: [group]
A cleanup code block. This code is not shown in the output for other builders, but executed after
the doctests of the group(s) it belongs to.
New in version 1.1.
.. doctest:: [group]
A doctest-style code block. You can use standard doctest flags for controlling how actual out-
put is compared with what you give as output. The default set of flags is specified by the
doctest_default_flags configuration variable.
This directive supports three options:
• hide, a flag option, hides the doctest block in other builders. By default it is shown as a
highlighted doctest block.
• options, a string option, can be used to give a comma-separated list of doctest flags that
apply to each example in the tests. (You still can give explicit flags per example, with doctest
comments, but they will show up in other builders too.)
• pyversion, a string option, can be used to specify the required Python version for the example
to be tested. For instance, in the following case the example will be tested only for Python
versions greater than 3.3:
.. doctest::
:pyversion: > 3.3
They will be respected when the test is run, but stripped from presentation output.
.. testcode:: [group]
A code block for a code-output-style test.
This directive supports one option:
• hide, a flag option, hides the code block in other builders. By default it is shown as a high-
lighted code block.
Note: Code in a testcode block is always executed all at once, no matter how many statements it
contains. Therefore, output will not be generated for bare expressions – use print. Example:
.. testcode::
.. testoutput::
161 https://www.python.org/dev/peps/pep-0440/#version-specifiers
Also, please be aware that since the doctest module does not support mixing regular output and an
exception message in the same snippet, this applies to testcode/testoutput as well.
.. testoutput:: [group]
The corresponding output, or the exception message, for the last testcode block.
This directive supports two options:
• hide, a flag option, hides the output block in other builders. By default it is shown as a literal
block without highlighting.
• options, a string option, can be used to give doctest flags (comma-separated) just like in
normal doctest blocks.
Example:
.. testcode::
.. testoutput::
:hide:
:options: -ELLIPSIS, +NORMALIZE_WHITESPACE
Output text.
The following is an example for the usage of the directives. The test via doctest and the test via
testcode and testoutput are equivalent.
.. testsetup:: *
import parrot
Doctest example:
.. doctest::
>>> parrot.voom(3000)
This parrot wouldn't voom if you put 3000 volts through it!
Test-Output example:
.. testcode::
parrot.voom(3000)
.. testoutput::
This parrot wouldn't voom if you put 3000 volts through it!
skipif, a string option, can be used to skip directives conditionally. This may be useful e.g. when
a different set of tests should be run depending on the environment (hardware, network/VPN, optional
dependencies or different versions of dependencies). The skipif option is supported by all of the doctest
directives. Below are typical use cases for skipif when used for different directives:
• testsetup and testcleanup
– conditionally skip test setup and/or cleanup
– customize setup/cleanup code per environment
• doctest
– conditionally skip both a test and its output verification
• testcode
– conditionally skip a test
– customize test code per environment
• testoutput
– conditionally skip output assertion for a skipped test
– expect different output depending on the environment
The value of the skipif option is evaluated as a Python expression. If the result is a true value, the
directive is omitted from the test run just as if it wasn’t present in the file at all.
Instead of repeating an expression, the doctest_global_setup configuration option can be used to
assign it to a variable which can then be used instead.
Here’s an example which skips some tests if Pandas is not installed:
Listing 1: conf.py
extensions = ['sphinx.ext.doctest']
doctest_global_setup = '''
try:
import pandas as pd
except ImportError:
pd = None
'''
Listing 2: contents.rst
.. testsetup::
:skipif: pd is None
data = pd.Series([42])
.. doctest::
:skipif: pd is None
>>> data.iloc[0]
42
.. testcode::
:skipif: pd is None
(continues on next page)
print(data.iloc[-1])
.. testoutput::
:skipif: pd is None
42
Configuration
>>> print 1
1
(Note that no special :: is used to introduce a doctest block; docutils recognizes them from the
leading >>>. Also, no additional indentation is used, though it doesn’t hurt.)
If this value is left at its default value, the above snippet is interpreted by the doctest builder exactly
like the following:
.. doctest::
>>> print 1
1
This feature makes it easy for you to test doctests in docstrings included with the autodoc extension
without marking them up with a special directive.
Note though that you can’t have blank lines in reST doctest blocks. They will be interpreted as one
block ending and another one starting. Also, removal of <BLANKLINE> and # doctest: options
only works in doctest blocks, though you may set trim_doctest_flags to achieve that in all
code blocks with Python console content.
Now, you can use the alias name as a new role, e.g. :issue:`123`. This then inserts a link to
https://github.com/sphinx-doc/sphinx/issues/123. As you can see, the target given in the role is
substituted in the base URL in the place of %s.
The link caption depends on the second item in the tuple, the prefix:
• If the prefix is None, the link caption is the full URL.
• If the prefix is the empty string, the link caption is the partial URL given in the role content
(123 in this case.)
• If the prefix is a non-empty string, the link caption is the partial URL, prepended by the prefix
– in the above example, the link caption would be issue 123.
You can also use the usual “explicit title” syntax supported by other roles that generate links, i.e.
:issue:`this issue <123>`. In this case, the prefix is not relevant.
Note: Since links are generated from the role in the reading stage, they appear as ordinary links to e.g.
the linkcheck builder.
.. graphviz::
digraph foo {
"bar" -> "baz";
}
In HTML output, the code will be rendered to a PNG or SVG image (see
graphviz_output_format). In LaTeX output, the code will be rendered to an embeddable
PDF file.
You can also embed external dot files, by giving the file name as an argument to graphviz and no
additional content:
.. graphviz:: external.dot
As for all file references in Sphinx, if the filename is absolute, it is taken as relative to the source
directory.
Changed in version 1.1: Added support for external files.
options
.. graph:: foo
"bar" -- "baz";
Note: The graph name is passed unchanged to Graphviz. If it contains non-alphanumeric characters
(e.g. a dash), you will have to double-quote it.
options
Same as graphviz.
:alt: alternate text (text)
New in version 1.0.
:align: alignment of the graph (left, center or right)
New in version 1.5.
:caption: caption of the graph (text)
New in version 1.1.
:layout: layout type of the graph (text)
New in version 1.4.
Changed in version 2.2: Renamed from graphviz_dot
:name: label (text)
New in version 1.6.
.. digraph::
Directive for embedding a single directed graph. The name is given as a directive argument, the
contents of the graph are the directive content. This is a convenience directive to generate digraph
<name> { <content> }.
For example:
.. digraph:: foo
options
Same as graphviz.
:alt: alternate text (text)
New in version 1.0.
:align: alignment of the graph (left, center or right)
New in version 1.5.
:caption: caption of the graph (text)
New in version 1.1.
:layout: layout type of the graph (text)
New in version 1.4.
Changed in version 2.2: Renamed from graphviz_dot
:name: label (text)
New in version 1.6.
There are also these config values:
graphviz_dot
The command name with which to invoke dot. The default is 'dot'; you may need to set this to a
full path if dot is not in the executable search path.
Since this setting is not portable from system to system, it is normally not useful to set it in conf.py;
rather, giving it on the sphinx-build command line via the -D option should be preferable, like
this:
graphviz_dot_args
Additional command-line arguments to give to dot, as a list. The default is an empty list. This is the
right place to set global graph, node or edge attributes via dot’s -G, -N and -E options.
graphviz_output_format
The output format for Graphviz when building HTML files. This must be either 'png' or 'svg';
the default is 'png'. If 'svg' is used, in order to make the URL links work properly, an appropriate
target attribute must be set, such as "_top" and "_blank". For example, the link in the following
graph should work in the svg output:
.. graphviz::
digraph example {
a [label="sphinx", href="http://sphinx-doc.org", target="_top"];
b [label="other"];
a -> b;
}
Warning: This directive is designed to control only content of document. It could not control sections,
labels and so on.
.. ifconfig::
Include content of the directive only if the Python expression given as an argument is True, evalu-
ated in the namespace of the project’s configuration (that is, all registered variables from conf.py
are available).
For example, one could write
This stuff is only included in the built docs for unstable versions.
To make a custom config value known to Sphinx, use add_config_value() in the setup function
in conf.py, e.g.:
def setup(app):
app.add_config_value('releaselevel', '', 'env')
The second argument is the default value, the third should always be 'env' for such values (it
selects if Sphinx re-reads the documents if the value changes).
Note: Imagemagick rasterizes a SVG image on conversion. As a result, the image becomes not scalable. To
avoid that, please use other image converters like sphinxcontrib-svg2pdfconverter164 (which uses Inkscape
or rsvg-convert).
Configuration
image_converter
A path to convert command. By default, the imgconverter uses the command from search paths.
image_converter_args
Additional command-line arguments to give to convert, as a list. The default is an empty list [].
163 https://www.imagemagick.org/script/index.php
164 https://github.com/missinglinkelectronics/sphinxcontrib-svg2pdfconverter
class A:
pass
class B(A):
pass
class C(A):
pass
class E(B):
pass
(continues on next page)
class F(C):
pass
.. inheritance-diagram:: dummy.test
:top-classes: dummy.test.B, dummy.test.C
any base classes which are ancestors to top-classes and are also defined in the same module will
be rendered as stand alone nodes. In this example class A will be rendered as stand alone node in
the graph. This is a known issue due to how this extension works internally.
If you don’t want class A (or any other ancestors) to be visible then specify only the classes you
would like to generate the diagram for like this:
Changed in version 1.7: Added top-classes option to limit the scope of inheritance graphs.
Examples
The following are different inheritance diagrams for the internal InheritanceDiagram class that imple-
ments the directive.
With full names:
.. inheritance-diagram:: sphinx.ext.inheritance_diagram.InheritanceDiagram
.. inheritance-diagram:: sphinx.ext.inheritance_diagram.InheritanceDiagram
:parts: 1
.. inheritance-diagram:: sphinx.ext.inheritance_diagram.InheritanceDiagram
:top-classes: sphinx.util.docutils.SphinxDirective
:parts: -1
util.docutils.SphinxDirective ext.inheritance_diagram.InheritanceDiagram
Configuration
inheritance_graph_attrs
A dictionary of graphviz graph attributes for inheritance diagrams.
For example:
inheritance_node_attrs
A dictionary of graphviz node attributes for inheritance diagrams.
For example:
inheritance_edge_attrs
A dictionary of graphviz edge attributes for inheritance diagrams.
inheritance_alias
Allows mapping the full qualified name of the class to custom values (useful when exposing the
underlying path of a class is not desirable, e.g. it’s a private class and should not be instantiated by
the user).
For example:
Configuration
To use Intersphinx linking, add 'sphinx.ext.intersphinx' to your extensions config value, and
use these config values to activate linking:
intersphinx_mapping
This config value contains the locations and names of other projects that should be linked to in this
documentation.
Relative local paths for target locations are taken as relative to the base of the built documentation,
while relative local paths for inventory locations are taken as relative to the source directory.
When fetching remote inventory files, proxy settings will be read from the $HTTP_PROXY environ-
ment variable.
Old format for this config value
This is the format used before Sphinx 1.0. It is still recognized.
A dictionary mapping URIs to either None or an URI. The keys are the base URI of the foreign
Sphinx documentation sets and can be local paths or HTTP URIs. The values indicate where the
inventory file can be found: they can be None (at the same location as the base URI) or another local
or HTTP URI.
New format for this config value
New in version 1.0.
A dictionary mapping unique identifiers to a tuple (target, inventory). Each target is the
base URI of a foreign Sphinx documentation set and can be a local path or an HTTP URI. The
inventory indicates where the inventory file can be found: it can be None (at the same location as
the base URI) or another local or HTTP URI.
The unique identifier can be used to prefix cross-reference targets, so that it is clear which intersphinx
set the target belongs to. A link like :ref:`comparison manual <python:comparisons>`
will link to the label “comparisons” in the doc set “python”, if it exists.
Example
To add links to modules and objects in the Python standard library documentation, use:
This will download the corresponding objects.inv file from the Internet and generate links to the
pages under the given URI. The downloaded inventory is cached in the Sphinx environment, so it
must be re-downloaded whenever you do a full rebuild.
A second example, showing the meaning of a non-None value of the second tuple item:
This will read the inventory from python-inv.txt in the source directory, but still generate links
to the pages under https://docs.python.org/3. It is up to you to update the inventory file as
new objects are added to the Python documentation.
Multiple target for the inventory
New in version 1.3.
Alternative files can be specified for each inventory. One can give a tuple for the second inventory
tuple item as shown in the following example. This will read the inventory iterating through the
(second) tuple items until the first successful fetch. The primary use case for this to specify mirror
sites for server downtime of the primary inventory:
intersphinx_cache_limit
The maximum number of days to cache remote inventories. The default is 5, meaning five days. Set
this to a negative value to cache inventories for unlimited time.
intersphinx_timeout
The number of seconds for timeout. The default is None, meaning do not timeout.
Note: timeout is not a time limit on the entire response download; rather, an exception is raised if
the server has not issued a response for timeout seconds.
To show all Intersphinx links and their targets of an Intersphinx mapping file, run python -msphinx.
ext.intersphinx url-or-path. This is helpful when searching for the root cause of a broken In-
tersphinx link in a documentation project. The following example prints the Intersphinx mapping of the
Python 3 documentation:
Configuration
linkcode_resolve
This is a function linkcode_resolve(domain, info), which should return the URL to source
code corresponding to the object in given domain with given information.
The function should return None if no link is to be added.
The argument domain specifies the language domain the object is in. info is a dictionary with the
following keys guaranteed to be present (dependent on the domain):
• py: module (name of the module), fullname (name of the object)
• c: names (list of names for the object)
• cpp: names (list of names for the object)
• javascript: object (name of the object), fullname (name of the item)
Example:
an inline image should use this “depth” in a vertical-align style to get correctly aligned with
surrounding text.
This mechanism requires the LaTeX preview package169 (available as preview-latex-style on
Ubuntu xenial). Therefore, the default for this option is False but it is strongly recommended to
set it to True.
Changed in version 2.1: This option can be used with the 'svg' imgmath_image_format.
imgmath_add_tooltips
Default: True. If false, do not add the LaTeX code as an “alt” attribute for math images.
imgmath_font_size
The font size (in pt) of the displayed math. The default value is 12. It must be a positive integer.
imgmath_latex
The command name with which to invoke LaTeX. The default is 'latex'; you may need to set this
to a full path if latex is not in the executable search path.
Since this setting is not portable from system to system, it is normally not useful to set it in conf.py;
rather, giving it on the sphinx-build command line via the -D option should be preferable, like
this:
This value should only contain the path to the latex executable, not further arguments; use
imgmath_latex_args for that purpose.
imgmath_latex_args
Additional arguments to give to latex, as a list. The default is an empty list.
imgmath_latex_preamble
Additional LaTeX code to put into the preamble of the LaTeX files used to translate the math snippets.
This is left empty by default. Use it e.g. to add packages which modify the fonts used for math,
such as '\\usepackage{newtxsf}' for sans-serif fonts, or '\\usepackage{fouriernc}' for
serif fonts. Indeed, the default LaTeX math fonts have rather thin glyphs which (in HTML output)
often do not match well with the font for text.
imgmath_dvipng
The command name to invoke dvipng. The default is 'dvipng'; you may need to set this
to a full path if dvipng is not in the executable search path. This option is only used when
imgmath_image_format is set to 'png'.
imgmath_dvipng_args
Additional arguments to give to dvipng, as a list. The default value is ['-gamma', '1.5', '-D',
'110', '-bg', 'Transparent'] which makes the image a bit darker and larger then it is by
default (this compensates somewhat for the thinness of default LaTeX math fonts), and produces
PNGs with a transparent background. This option is used only when imgmath_image_format is
'png'.
imgmath_dvisvgm
The command name to invoke dvisvgm. The default is 'dvisvgm'; you may need to set this
to a full path if dvisvgm is not in the executable search path. This option is only used when
imgmath_image_format is 'svg'.
imgmath_dvisvgm_args
Additional arguments to give to dvisvgm, as a list. The default value is ['--no-fonts'], which
means that dvisvgm will render glyphs as path elements (cf the dvisvgm FAQ170 ). This option is
used only when imgmath_image_format is 'svg'.
169 https://www.gnu.org/software/auctex/preview-latex.html
170 https://dvisvgm.de/FAQ
Attention: You should use the math directive and role, not the native MathJax $$, \(, etc.
mathjax_path
The path to the JavaScript file to include in the HTML files in order to load MathJax.
The default is the https:// URL that loads the JS files from the cdnjs172 Content Delivery Network.
See the MathJax Getting Started page173 for details. If you want MathJax to be available offline or
without including resources from a third-party site, you have to download it and set this value to a
different path.
The path can be absolute or relative; if it is relative, it is relative to the _static directory of the
built docs.
For example, if you put MathJax into the static path of the Sphinx docs, this value would be
MathJax/MathJax.js. If you host more than one Sphinx documentation set on one server, it
is advisable to install MathJax in a shared location.
You can also give a full https:// URL different from the CDN URL.
mathjax_options
The options to script tag for mathjax. For example, you can set integrity option with following
setting:
mathjax_options = {
'integrity': 'sha384-......',
}
mathjax_config = {
'extensions': ['tex2jax.js'],
'jax': ['input/TeX', 'output/HTML-CSS'],
}
This extension works just as the MathJax extension does, but uses the older package jsMath175 . It provides
this config value:
jsmath_path
The path to the JavaScript file to include in the HTML files in order to load JSMath. There is no
default.
The path can be absolute or relative; if it is relative, it is relative to the _static directory of the
built docs.
For example, if you put JSMath into the static path of the Sphinx docs, this value would be jsMath/
easy/load.js. If you host more than one Sphinx documentation set on one server, it is advisable
to install jsMath in a shared location.
Overview
reStructuredText176 is great, but it creates visually dense, hard to read docstrings177 . Compare the jumble
above to the same thing rewritten according to the Google Python Style Guide178 :
Args:
path (str): The path of the file to wrap
field_storage (FileStorage): The :class:`FileStorage` instance to wrap
temporary (bool): Whether or not to delete the file when the File
instance is destructed
Returns:
BufferedFileStorage: A buffered writable file descriptor
Napoleon is a extension that enables Sphinx to parse both NumPy179 and Google180 style docstrings - the
style recommended by Khan Academy181 .
Napoleon is a pre-processor that parses NumPy182 and Google183 style docstrings and converts them
to reStructuredText before Sphinx attempts to parse them. This happens in an intermediate step while
Sphinx is processing the documentation, so it doesn’t modify any of the docstrings in your actual source
code files.
Getting Started
1. After setting up Sphinx to build your docs, enable napoleon in the Sphinx conf.py file:
# conf.py
Docstrings
Napoleon interprets every docstring that autodoc can find, including docstrings on: modules, classes,
attributes, methods, functions, and variables. Inside each docstring, specially formatted Sections
are parsed and converted to reStructuredText.
All standard reStructuredText formatting still works as expected.
Docstring Sections
Google vs NumPy
Napoleon supports two styles of docstrings: Google184 and NumPy185 . The main difference between the
two styles is that Google uses indentation to separate sections, whereas NumPy uses underlines.
Google style:
Args:
arg1 (int): Description of arg1
arg2 (str): Description of arg2
Returns:
bool: Description of return value
"""
return True
NumPy style:
184 https://google.github.io/styleguide/pyguide.html#Comments
185 https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt
Parameters
----------
arg1 : int
Description of arg1
arg2 : str
Description of arg2
Returns
-------
bool
Description of return value
"""
return True
NumPy style tends to require more vertical space, whereas Google style tends to use more horizontal
space. Google style tends to be easier to read for short and simple docstrings, whereas NumPy style tends
be easier to read for long and in-depth docstrings.
The Khan Academy186 recommends using Google style.
The choice between styles is largely aesthetic, but the two styles should not be mixed. Choose one style
for your project and be consistent with it.
See also:
For complete examples:
• example_google
• example_numpy
Type Annotations
PEP 484187 introduced a standard way to express types in Python code. This is an alternative to expressing
types directly in docstrings. One benefit of expressing types according to PEP 484188 is that type checkers
and IDEs can take advantage of them for static code analysis.
Google style with Python 3 type annotations:
Args:
arg1: Description of arg1
arg2: Description of arg2
(continues on next page)
186 https://github.com/Khan/style-guides/blob/master/style/python.md#docstrings
187 https://www.python.org/dev/peps/pep-0484/
188 https://www.python.org/dev/peps/pep-0484/
Returns:
Description of return value
"""
return True
Args:
arg1 (int): Description of arg1
arg2 (str): Description of arg2
Returns:
bool: Description of return value
"""
return True
Note: Python 2/3 compatible annotations189 aren’t currently supported by Sphinx and won’t show up in
the docs.
Configuration
Listed below are all the settings used by napoleon and their default values. These settings can be changed
in the Sphinx conf.py file. Make sure that “sphinx.ext.napoleon” is enabled in conf.py:
# conf.py
# Napoleon settings
napoleon_google_docstring = True
napoleon_numpy_docstring = True
napoleon_include_init_with_doc = False
napoleon_include_private_with_doc = False
napoleon_include_special_with_doc = True
napoleon_use_admonition_for_examples = False
napoleon_use_admonition_for_notes = False
napoleon_use_admonition_for_references = False
napoleon_use_ivar = False
napoleon_use_param = True
napoleon_use_rtype = True
189 https://www.python.org/dev/peps/pep-0484/#suggested-syntax-for-python-2-7-and-straddling-code
napoleon_google_docstring
True to parse Google style190 docstrings. False to disable support for Google style docstrings. De-
faults to True.
napoleon_numpy_docstring
True to parse NumPy style191 docstrings. False to disable support for NumPy style docstrings.
Defaults to True.
napoleon_include_init_with_doc
True to list __init___ docstrings separately from the class docstring. False to fall back to Sphinx’s
default behavior, which considers the __init___ docstring as part of the class documentation.
Defaults to False.
If True:
def __init__(self):
\"\"\"
This will be included in the docs because it has a docstring
\"\"\"
def __init__(self):
# This will NOT be included in the docs
napoleon_include_private_with_doc
True to include private members (like _membername) with docstrings in the documentation. False
to fall back to Sphinx’s default behavior. Defaults to False.
If True:
def _included(self):
"""
This will be included in the docs because it has a docstring
"""
pass
def _skipped(self):
# This will NOT be included in the docs
pass
napoleon_include_special_with_doc
True to include special members (like __membername__) with docstrings in the documentation.
False to fall back to Sphinx’s default behavior. Defaults to True.
If True:
def __str__(self):
"""
This will be included in the docs because it has a docstring
"""
return unicode(self).encode('utf-8')
def __unicode__(self):
# This will NOT be included in the docs
return unicode(self.__class__.__name__)
190 https://google.github.io/styleguide/pyguide.html
191 https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt
napoleon_use_admonition_for_examples
True to use the .. admonition:: directive for the Example and Examples sections. False to use
the .. rubric:: directive instead. One may look better than the other depending on what HTML
theme is used. Defaults to False.
This NumPy style192 snippet will be converted as follows:
Example
-------
This is just a quick example
If True:
.. admonition:: Example
If False:
.. rubric:: Example
napoleon_use_admonition_for_notes
True to use the .. admonition:: directive for Notes sections. False to use the .. rubric::
directive instead. Defaults to False.
Note: The singular Note section will always be converted to a .. note:: directive.
See also:
napoleon_use_admonition_for_examples
napoleon_use_admonition_for_references
True to use the .. admonition:: directive for References sections. False to use the .. rubric::
directive instead. Defaults to False.
See also:
napoleon_use_admonition_for_examples
napoleon_use_ivar
True to use the :ivar: role for instance variables. False to use the .. attribute:: directive
instead. Defaults to False.
This NumPy style193 snippet will be converted as follows:
Attributes
----------
attr1 : int
Description of `attr1`
If True:
192 https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt
193 https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt
If False:
.. attribute:: attr1
Description of `attr1`
:type: int
napoleon_use_param
True to use a :param: role for each function parameter. False to use a single :parameters: role
for all the parameters. Defaults to True.
This NumPy style194 snippet will be converted as follows:
Parameters
----------
arg1 : str
Description of `arg1`
arg2 : int, optional
Description of `arg2`, defaults to 0
If True:
If False:
napoleon_use_keyword
True to use a :keyword: role for each function keyword argument. False to use a single :keyword
arguments: role for all the keywords. Defaults to True.
This behaves similarly to napoleon_use_param. Note unlike docutils, :keyword: and :param:
will not be treated the same way - there will be a separate “Keyword Arguments” section, rendered
in the same fashion as “Parameters” section (type links created if possible)
See also:
napoleon_use_param
napoleon_use_rtype
True to use the :rtype: role for the return type. False to output the return type inline with the
description. Defaults to True.
This NumPy style195 snippet will be converted as follows:
Returns
-------
(continues on next page)
194 https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt
195 https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt
If True:
If False:
Configuration
todo_include_todos
If this is True, todo and todolist produce output, else they produce nothing. The default is
False.
todo_emit_warnings
If this is True, todo emits a warning for each TODO entries. The default is False.
New in version 1.5.
todo_link_only
If this is True, todolist produce output without file path and line, The default is False.
New in version 1.4.
autodoc provides the following an additional event:
todo-defined(app, node)
New in version 1.5.
Emitted when a todo is defined. node is the defined sphinx.ext.todo.todo_node node.
Warning: Basically, viewcode extension will import the modules being linked to. If any modules
have side effects on import, these will be executed when sphinx-build is run.
If you document scripts (as opposed to library modules), make sure their main routine is protected by
a if __name__ == '__main__' condition.
In addition, if you don’t want to import the modules by viewcode, you can tell the location of the
location of source code to viewcode using the viewcode-find-source event.
If viewcode_follow_imported_members is enabled, you will also need to resolve imported at-
tributes using the viewcode-follow-imported event.
This extension works only on HTML related builders like html, applehelp, devhelp, htmlhelp,
qthelp and so on except singlehtml. By default epub builder doesn’t support this extension (see
viewcode_enable_epub).
Configuration
viewcode_follow_imported_members
If this is True, viewcode extension will emit viewcode-follow-imported event to resolve the
name of the module by other extensions. The default is True.
New in version 1.3.
Changed in version 1.8: Renamed from viewcode_import to
viewcode_follow_imported_members.
viewcode_enable_epub
If this is True, viewcode extension is also enabled even if you use epub builders. This extension
generates pages outside toctree, but this is not preferred as epub format.
Until 1.4.x, this extension is always enabled. If you want to generate epub as same as 1.4.x, you
should set True, but epub format checker’s score becomes worse.
The default is False.
New in version 1.5.
Warning: Not all epub readers support pages generated by viewcode extension. These readers
ignore links to pages are not under toctree.
Some reader’s rendering result are corrupted and epubcheck196 ’s score becomes worse even if
the reader supports.
196 https://github.com/IDPF/epubcheck
viewcode-find-source(app, modname)
New in version 1.8.
Find the source code for a module. An event handler for this event should return a tuple of the
source code itself and a dictionary of tags. The dictionary maps the name of a class, function,
attribute, etc to a tuple of its type, the start line number, and the end line number. The type should
be one of “class”, “def”, or “other”.
Parameters
• app – The Sphinx application object.
• modname – The name of the module to find source code for.
viewcode-follow-imported(app, modname, attribute)
New in version 1.8.
Find the name of the original module for an attribute.
Parameters
• app – The Sphinx application object.
• modname – The name of the module that the attribute belongs to.
• attribute – The name of the member to follow.
You can find several extensions contributed by users in the Sphinx Contrib197 repository. It is open
for anyone who wants to maintain an extension publicly; just send a short message asking for write
permissions.
There are also several extensions hosted elsewhere. The Sphinx extension survey198 and awesome-
sphinxdoc199 contains a comprehensive list.
If you write an extension that you think others will find useful or you think should be included as a part
of Sphinx, please write to the project mailing list (join here200 ).
Extensions local to a project should be put within the project’s directory structure. Set Python’s module
search path, sys.path, accordingly so that Sphinx can find them. For example, if your extension foo.py
lies in the exts subdirectory of the project root, put into conf.py:
import sys, os
sys.path.append(os.path.abspath('exts'))
extensions = ['foo']
You can also install extensions anywhere else on sys.path, e.g. in the site-packages directory.
197 https://bitbucket.org/birkenfeld/sphinx-contrib
198 https://sphinxext-survey.readthedocs.io/
199 https://github.com/yoloseem/awesome-sphinxdoc
200 https://groups.google.com/forum/#!forum/sphinx-dev
NINE
HTML
9.1 Builders
9.2 Themes
Note: This section provides information about using pre-existing HTML themes. If you wish to create
your own theme, refer to HTML theming support.
Sphinx supports changing the appearance of its HTML output via themes. A theme is a collection of HTML
templates, stylesheet(s) and other static files. Additionally, it has a configuration file which specifies from
which theme to inherit, which highlighting style to use, and what options exist for customizing the theme’s
look and feel.
Themes are meant to be project-unaware, so they can be used for different projects without change.
Using a theme provided with Sphinx is easy. Since these do not need to be installed, you only need to set the
html_theme config value. For example, to enable the classic theme, add the following to conf.py:
html_theme = "classic"
You can also set theme-specific options using the html_theme_options config value. These options are
generally used to change the look and feel of the theme. For example, to place the sidebar on the right
side and a black background for the relation bar (the bar with the navigation links at the page’s top and
bottom), add the following conf.py:
html_theme_options = {
"rightsidebar": "true",
"relbarbgcolor": "black"
}
159
Sphinx Documentation, Release 3.0.0+/0fb832baa
If the theme does not come with Sphinx, it can be in two static forms or as a Python package. For the
static forms, either a directory (containing theme.conf and other needed files), or a zip file with the
same contents is supported. The directory or zipfile must be put where Sphinx can find it; for this there is
the config value html_theme_path. This can be a list of directories, relative to the directory containing
conf.py, that can contain theme directories or zip files. For example, if you have a theme in the file
blue.zip, you can put it right in the directory containing conf.py and use this configuration:
html_theme = "blue"
html_theme_path = ["."]
The third form is a Python package. If a theme you want to use is distributed as a Python package, you
can use it after installing
Once installed, this can be used in the same manner as a directory or zipfile-based theme:
html_theme = "dotted"
For more information on the design of themes, including information about writing your own themes,
refer to HTML theming support.
Theme overview
alabaster classic
Continued on next page
sphinxdoc scrolls
agogo traditional
nature haiku
Continued on next page
pyramid bizstyle
Note: The Sphinx documentation now uses an adjusted version of the sphinxdoc theme204 .
scrolls A more lightweight theme, based on the Jinja documentation205 . The following color options are
available:
• headerbordercolor
• subheadlinecolor
• linkcolor
• visitedlinkcolor
• admonitioncolor
agogo A theme created by Andi Albrecht. The following options are supported:
• bodyfont (CSS font family): Font for normal text.
• headerfont (CSS font family): Font for headings.
• pagewidth (CSS length): Width of the page content, default 70em.
204 https://github.com/sphinx-doc/sphinx/tree/master/doc/_themes/sphinx13
205 http://jinja.pocoo.org/
• documentwidth (CSS length): Width of the document (without sidebar), default 50em.
• sidebarwidth (CSS length): Width of the sidebar, default 20em.
• bgcolor (CSS color): Background color.
• headerbg (CSS value for “background”): background for the header area, default a grayish
gradient.
• footerbg (CSS value for “background”): background for the footer area, default a light gray
gradient.
• linkcolor (CSS color): Body link color.
• headercolor1, headercolor2 (CSS color): colors for <h1> and <h2> headings.
• headerlinkcolor (CSS color): Color for the backreference link in headings.
• textalign (CSS text-align value): Text alignment for the body, default is justify.
nature A greenish theme. There are currently no options beyond nosidebar and sidebarwidth.
pyramid A theme from the Pyramid web framework project, designed by Blaise Laflamme. There are
currently no options beyond nosidebar and sidebarwidth.
haiku A theme without sidebar inspired by the Haiku OS user guide206 . The following options are
supported:
• full_logo (true or false, default False): If this is true, the header will only show the
html_logo. Use this for large logos. If this is false, the logo (if present) will be shown floating
right, and the documentation title will be put in the header.
• textcolor, headingcolor, linkcolor, visitedlinkcolor, hoverlinkcolor (CSS colors): Colors for
various body elements.
traditional A theme resembling the old Python documentation. There are currently no options beyond
nosidebar and sidebarwidth.
epub A theme for the epub builder. This theme tries to save visual space which is a sparse resource on
ebook readers. The following options are supported:
• relbar1 (true or false, default True): If this is true, the relbar1 block is inserted in the epub
output, otherwise it is omitted.
• footer (true or false, default True): If this is true, the footer block is inserted in the epub output,
otherwise it is omitted.
bizstyle A simple bluish theme. The following options are supported beyond nosidebar and sidebarwidth:
• rightsidebar (true or false): Put the sidebar on the right side. Defaults to False.
New in version 1.3: ‘alabaster’, ‘sphinx_rtd_theme’ and ‘bizstyle’ theme.
Changed in version 1.3: The ‘default’ theme has been renamed to ‘classic’. ‘default’ is still available,
however it will emit a notice that it is an alias for the new ‘alabaster’ theme.
Theme overview
Continued on next page
206 https://www.haiku-os.org/docs/userguide/en/contents.html
sphinx_rtd_theme
There are many third-party themes available. Some of these are general use, while others are specific to an
individual project. A section of third-party themes is listed below. Many more can be found on PyPI207 ,
GitHub208 and sphinx-themes.org209 .
sphinx_rtd_theme Read the Docs Sphinx Theme210 . This is a mobile-friendly sphinx theme that was
made for readthedocs.org. View a working demo over on readthedocs.org. You can get install and
options information at Read the Docs Sphinx Theme211 page.
Changed in version 1.4: sphinx_rtd_theme has become optional.
207 https://pypi.org/search/?q=&o=&c=Framework+%3A%3A+Sphinx+%3A%3A+Theme
208 https://github.com/search?utf8=%E2%9C%93&q=sphinx+theme&type=
209 https://sphinx-themes.org/
210 https://pypi.org/project/sphinx_rtd_theme/
211 https://pypi.org/project/sphinx_rtd_theme/
TEN
INTERNATIONALIZATION
Fig. 1: Workflow visualization of translations in Sphinx. (The stick-figure is taken from an XKCD comic212 .)
212 https://xkcd.com/779/
167
Sphinx Documentation, Release 3.0.0+/0fb832baa
gettext1 is an established standard for internationalization and localization. It naively maps messages in a
program to a translated string. Sphinx uses these facilities to translate whole documents.
Initially project maintainers have to collect all translatable strings (also referred to as messages) to make
them known to translators. Sphinx extracts these through invocation of sphinx-build -b gettext.
Every single element in the doctree will end up in a single message which results in lists being equally
split into different chunks while large paragraphs will remain as coarsely-grained as they were in the
original document. This grants seamless document updates while still providing a little bit of context for
translators in free-text passages. It is the maintainer’s task to split up paragraphs which are too large as
there is no sane automated way to do that.
After Sphinx successfully ran the MessageCatalogBuilder you will find a collection of .pot files in
your output directory. These are catalog templates and contain messages in your original language only.
They can be delivered to translators which will transform them to .po files — so called message catalogs
— containing a mapping from the original messages to foreign-language strings.
gettext compiles them into a binary format known as binary catalogs through msgfmt for efficiency
reasons. If you make these files discoverable with locale_dirs for your language, Sphinx will pick
them up automatically.
An example: you have a document usage.rst in your Sphinx project. The gettext builder will put its
messages into usage.pot. Imagine you have Spanish translations2 stored in usage.po — for your builds
to be translated you need to follow these instructions:
• Compile your message catalog to a locale directory, say locale, so it ends up in ./locale/es/
LC_MESSAGES/usage.mo in your source directory (where es is the language code for Spanish.)
sphinx-intl213 is a useful tool to work with Sphinx translation flow. This section describe an easy way to
translate with sphinx-intl.
1. Install sphinx-intl214 .
1 See the GNU gettext utilities222 for details on that software suite.
222 https://www.gnu.org/software/gettext/manual/gettext.html#Introduction
2 Because nobody expects the Spanish Inquisition!
213 https://pypi.org/project/sphinx-intl/
214 https://pypi.org/project/sphinx-intl/
This case-study assumes that locale_dirs is set to locale/ and gettext_compact is set to
False (the Sphinx document is already configured as such).
3. Extract translatable messages into pot files.
$ make gettext
Once completed, the generated po files will be placed in the below directories:
• ./locale/de/LC_MESSAGES/
• ./locale/ja/LC_MESSAGES/
5. Translate po files.
AS noted above, these are located in the ./locale/<lang>/LC_MESSAGES directory. An example
of one such file, from Sphinx, builders.po, is given below.
# a5600c3d2e3d48fc8c261ea0284db79b
#: ../../builders.rst:4
msgid "Available builders"
msgstr "<FILL HERE BY TARGET LANGUAGE>"
# 302558364e1d41c69b3277277e34b184
#: ../../builders.rst:9
msgid ""
"These are the built-in Sphinx builders. More builders can be added by "
":ref:`extensions <extensions>`."
msgstr ""
"FILL HERE BY TARGET LANGUAGE FILL HERE BY TARGET LANGUAGE FILL HERE "
"BY TARGET LANGUAGE :ref:`EXTENSIONS <extensions>` FILL HERE."
Please be careful not to break reST notation. Most po-editors will help you with that.
6. Build translated document.
You need a language parameter in conf.py or you may also specify the parameter on the com-
mand line.
For for BSD/GNU make, run:
10.2.2 Translating
If a document is updated, it is necessary to generate updated pot files and to apply differences to translated
po files. In order to apply the updates from a pot file to the po file, use the sphinx-intl update
command.
Transifex215 is one of several services that allow collaborative translation via a web interface. It has a nifty
Python-based command line client that makes it easy to fetch and push translations.
1. Install transifex-client216 .
You need tx command to upload resources (pot files).
See also:
Transifex Client documentation217
2. Create your transifex218 account and create new project for your document.
Currently, transifex does not allow for a translation project to have more than one version of the
document, so you’d better include a version number in your project name.
For example:
Project ID sphinx-document-test_1_0
Project URL https://www.transifex.com/projects/p/
sphinx-document-test_1_0/
215 https://www.transifex.com/
216 https://pypi.org/project/transifex-client/
217 https://docs.transifex.com/client/introduction/
218 https://www.transifex.com/
$ tx init
Creating .tx folder...
Transifex instance [https://www.transifex.com]:
...
Please enter your transifex username: <transifex-username>
Password: <transifex-password>
...
Done.
$ cd /your/document/root
$ sphinx-intl update-txconfig-resources --pot-dir _build/locale \
--transifex-project-name sphinx-document-test_1_0
$ tx push -s
Pushing translations for resource sphinx-document-test_1_0.builders:
Pushing source file (locale/pot/builders.pot)
Resource does not exist. Creating...
...
Done.
$ cd /your/document/root
$ tx pull -l de
Pulling translations for resource sphinx-document-test_1_0.builders (...)
-> de: locale/de/LC_MESSAGES/builders.po
...
Done.
That’s all!
The recommended way for new contributors to translate Sphinx reference is to join the translation team
on Transifex.
There is sphinx translation page219 for Sphinx (master) documentation.
1. Login to transifex220 service.
2. Go to sphinx translation page221 .
3. Click Request language and fill form.
4. Wait acceptance by transifex sphinx translation maintainers.
5. (After acceptance) Translate on transifex.
219 https://www.transifex.com/sphinx-doc/sphinx-doc/
220 https://www.transifex.com/
221 https://www.transifex.com/sphinx-doc/sphinx-doc/
ELEVEN
SETUPTOOLS INTEGRATION
Sphinx supports integration with setuptools and distutils through a custom command - BuildDoc.
The Sphinx build can then be triggered from distutils, and some Sphinx options can be set in setup.py
or setup.cfg instead of Sphinx’s own configuration file.
For instance, from setup.py:
Note: If you set Sphinx options directly in the setup() command, replace hyphens in variable names
with underscores. In the example above, source-dir becomes source_dir.
[build_sphinx]
project = 'My project'
version = 1.2
(continues on next page)
173
Sphinx Documentation, Release 3.0.0+/0fb832baa
all-files
A boolean that determines whether all files should be built from scratch. Default is false.
This can also be set by passing the -a flag to setup.py:
source-dir
The target source directory. This can be relative to the setup.py or setup.cfg file, or it can be
absolute. It defaults to ./doc or ./docs if either contains a file named conf.py (checking ./doc
first); otherwise it defaults to the current directory.
This can also be set by passing the -s flag to setup.py:
build-dir
The target build directory. This can be relative to the setup.py or setup.cfg file, or it can be
absolute. Default is ./build/sphinx.
config-dir
Location of the configuration directory. This can be relative to the setup.py or setup.cfg file, or
it can be absolute. Default is to use source-dir.
This can also be set by passing the -c flag to setup.py:
Changed in version 1.6: This can now be a comma- or space-separated list of builders
warning-is-error
A boolean that ensures Sphinx warnings will result in a failed build. Default is false.
This can also be set by passing the -W flag to setup.py:
TWELVE
To make use of the web support package in your application you’ll need to build the data it uses. This
data includes pickle files representing documents, search indices, and node data that is used to track
where comments and other things are in a document. To do this you will need to create an instance of the
WebSupport class and call its build() method:
support = WebSupport(srcdir='/path/to/rst/sources/',
builddir='/path/to/build/outdir',
search='xapian')
support.build()
This will read reStructuredText sources from srcdir and place the necessary data in builddir. The
builddir will contain two sub-directories: one named “data” that contains all the data needed to display
documents, search through documents, and add comments to documents. The other directory will be
called “static” and contains static files that should be served from “/static”.
Note: If you wish to serve static files from a path other than “/static”, you can do so by providing the
staticdir keyword argument when creating the WebSupport object.
Now that the data is built, it’s time to do something useful with it. Start off by creating a WebSupport
object for your application:
177
Sphinx Documentation, Release 3.0.0+/0fb832baa
You’ll only need one of these for each set of documentation you will be working with. You can then call
its get_document() method to access individual documents:
contents = support.get_document('contents')
{% block css %}
{{ super() }}
{{ document.css|safe }}
<link rel="stylesheet" href="/static/websupport-custom.css" type="text/css
,→">
{% endblock %}
223 http://jinja.pocoo.org/
Authentication
To use certain features such as voting, it must be possible to authenticate users. The details of the authen-
tication are left to your application. Once a user has been authenticated you can pass the user’s details
to certain WebSupport methods using the username and moderator keyword arguments. The web support
package will store the username with comments and votes. The only caveat is that if you allow users to
change their username you must update the websupport package’s data:
support.update_username(old_username, new_username)
username should be a unique string which identifies a user, and moderator should be a boolean representing
whether the user has moderation privileges. The default value for moderator is False.
An example Flask224 function that checks whether a user is logged in and then retrieves a document is:
@app.route('/<path:docname>')
def doc(docname):
username = g.user.name if g.user else ''
moderator = g.user.moderator if g.user else False
try:
document = support.get_document(docname, username, moderator)
except DocumentNotFoundError:
abort(404)
return render_template('doc.html', document=document)
The first thing to notice is that the docname is just the request path. This makes accessing the correct
document easy from a single view. If the user is authenticated, then the username and moderation status
are passed along with the docname to get_document(). The web support package will then add this
data to the COMMENT_OPTIONS that are used in the template.
Note: This only works if your documentation is served from your document root. If it is served from
another directory, you will need to prefix the url route with that directory, and give the docroot keyword
argument when creating the web support object:
@app.route('/docs/<path:docname>')
To use the search form built-in to the Sphinx sidebar, create a function to handle requests to the URL
‘search’ relative to the documentation root. The user’s search query will be in the GET parameters, with
the key q. Then use the get_search_results() method to retrieve search results. In Flask225 that
would be like this:
@app.route('/search')
def search():
q = request.args.get('q')
(continues on next page)
224 http://flask.pocoo.org/
225 http://flask.pocoo.org/
Note that we used the same template to render our search results as we did to render our doc-
uments. That’s because get_search_results() returns a context dict in the same format that
get_document() does.
Now that this is done it’s time to define the functions that handle the AJAX calls from the script. You
will need three functions. The first function is used to add a new comment, and will call the web support
method add_comment():
@app.route('/docs/add_comment', methods=['POST'])
def add_comment():
parent_id = request.form.get('parent', '')
node_id = request.form.get('node', '')
text = request.form.get('text', '')
proposal = request.form.get('proposal', '')
username = g.user.name if g.user is not None else 'Anonymous'
comment = support.add_comment(text, node_id='node_id',
parent_id='parent_id',
username=username, proposal=proposal)
return jsonify(comment=comment)
You’ll notice that both a parent_id and node_id are sent with the request. If the comment is being
attached directly to a node, parent_id will be empty. If the comment is a child of another comment,
then node_id will be empty. Then next function handles the retrieval of comments for a specific node,
and is aptly named get_data():
@app.route('/docs/get_comments')
def get_comments():
username = g.user.name if g.user else None
moderator = g.user.moderator if g.user else False
node_id = request.args.get('node', '')
data = support.get_data(node_id, username, moderator)
return jsonify(**data)
The final function that is needed will call process_vote(), and will handle user votes on comments:
@app.route('/docs/process_vote', methods=['POST'])
def process_vote():
if g.user is None:
abort(401)
comment_id = request.form.get('comment_id')
value = request.form.get('value')
if value is None or comment_id is None:
abort(400)
support.process_vote(comment_id, g.user.id, value)
return "success"
By default, all comments added through add_comment() are automatically displayed. If you wish to
have some form of moderation, you can pass the displayed keyword argument:
You can then create a new view to handle the moderation of comments. It will be called when a moderator
decides a comment should be accepted and displayed:
@app.route('/docs/accept_comment', methods=['POST'])
def accept_comment():
moderator = g.user.moderator if g.user else False
comment_id = request.form.get('id')
support.accept_comment(comment_id, moderator=moderator)
return 'OK'
def moderation_callback(comment):
"""Do something..."""
The moderation callback must take one argument, which will be the same comment dict that is returned
by add_comment().
staticdir If the static files should be created in a different location and not in '/static', this
should be a string with the name of that location (e.g. builddir + '/static_files').
Note: If you specify staticdir, you will typically want to adjust staticroot accordingly.
staticroot If the static files are not served from '/static', this should be a string with the name
of that location (e.g. '/static_files').
docroot If the documentation is not served from the base path of a URL, this should be a string
specifying that path (e.g. 'docs').
Changed in version 1.6: WebSupport class is moved to sphinxcontrib.websupport from
sphinx.websupport. Please add sphinxcontrib-websupport package in your dependency and use
moved class instead.
12.2.1 Methods
WebSupport.build()
Build the documentation. Places the data into the outdir directory. Use it like this:
This will read reStructured text files from srcdir. Then it will build the pickles and search index,
placing them into builddir. It will also save node data to the database.
WebSupport.get_document(docname, username=”, moderator=False)
Load and return a document from a pickle. The document will be a dict object which can be used
to render a template:
support = WebSupport(datadir=datadir)
support.get_document('index', username, moderator)
In most cases docname will be taken from the request path and passed directly to this function. In
Flask, that would be something like this:
@app.route('/<path:docname>')
def index(docname):
username = g.user.name if g.user else ''
moderator = g.user.moderator if g.user else False
try:
document = support.get_document(docname, username,
moderator)
except DocumentNotFoundError:
abort(404)
render_template('doc.html', document=document)
The document dict that is returned contains the following items to be used during template render-
ing.
• body: The main body of the document as HTML
• sidebar: The sidebar of the document as HTML
• relbar: A div containing links to related documents
• title: The title of the document
Key Contents
text The comment text.
user- The username that was stored with the comment.
name
id The comment’s unique identifier.
rat- The comment’s current rating.
ing
age The time in seconds since the comment was added.
time A dict containing time information. It contains the following keys: year, month, day,
hour, minute, second, iso, and delta. iso is the time formatted in ISO 8601 format. delta is
a printable form of how old the comment is (e.g. “3 hours ago”).
vote If user_id was given, this will be an integer representing the vote. 1 for an upvote, -1 for a
downvote, or 0 if unvoted.
node The id of the node that the comment is attached to. If the comment’s parent is another
comment rather than a node, this will be null.
par- The id of the comment that this comment is attached to if it is not attached to a node.
ent
chil- A list of all children, in this format.
dren
pro- An HTML representation of the differences between the the current source and the user’s
posal_diff
proposed source.
Parameters
• node_id – the id of the node to get comments for.
• username – the username of the user viewing the comments.
• moderator – whether the user is a moderator.
If the comment is the child of another comment, provide the parent’s id (as a string) with the parent
keyword argument:
If you would like to store a username with the comment, pass in the optional username keyword
argument:
Parameters
• parent_id – the prefixed id of the comment’s parent.
• text – the text of the comment.
• displayed – for moderation purposes
• username – the username of the user making the comment.
• time – the time the comment was created, defaults to now.
@app.route('/docs/process_vote', methods=['POST'])
def process_vote():
if g.user is None:
abort(401)
comment_id = request.form.get('comment_id')
value = request.form.get('value')
if value is None or comment_id is None:
abort(400)
support.process_vote(comment_id, g.user.name, value)
return "success"
Parameters
• comment_id – the comment being voted on
• username – the unique username of the user voting
• value – 1 for an upvote, -1 for a downvote, 0 for an unvote.
WebSupport.get_search_results(q)
Perform a search for the query q, and create a set of search results. Then render the search results as
html and return a context dict like the one created by get_document():
document = support.get_search_results(q)
To create a custom search adapter you will need to subclass the BaseSearch class. Then create an
instance of the new class and pass that as the search keyword argument when you create the WebSupport
object:
support = WebSupport(srcdir=srcdir,
builddir=builddir,
search=MySearch())
For more information about creating a custom search adapter, please see the documentation of the
BaseSearch class below.
class sphinxcontrib.websupport.search.BaseSearch
Defines an interface for search adapters.
Changed in version 1.6: BaseSearch class is moved to sphinxcontrib.websupport.search from
sphinx.websupport.search.
12.3.1 Methods
The following methods are defined in the BaseSearch class. Some methods do not need to be overridden,
but some (add_document() and handle_query()) must be overridden in your subclass. For a working
example, look at the built-in adapter for whoosh.
BaseSearch.init_indexing(changed=[])
Called by the builder to initialize the search indexer. changed is a list of pagenames that will be
reindexed. You may want to remove these from the search index before indexing begins.
Parameters changed – a list of pagenames that will be re-indexed
BaseSearch.finish_indexing()
Called by the builder when writing has been completed. Use this to perform any finalization or
cleanup actions after indexing is complete.
BaseSearch.feed(pagename, filename, title, doctree)
Called by the builder to add a doctree to the index. Converts the doctree to text and passes it to
add_document(). You probably won’t want to override this unless you need access to the doctree.
Override add_document() instead.
Parameters
• pagename – the name of the page to be indexed
• filename – the name of the original source file
• title – the title of the page to be indexed
• doctree – is the docutils doctree representation of the page
BaseSearch.add_document(pagename, filename, title, text)
Called by feed() to add a document to the search index. This method should should do everything
necessary to add a single document to the search index.
pagename is name of the page being indexed. It is the combination of the source files relative path
and filename, minus the extension. For example, if the source file is “ext/builders.rst”, the pagename
would be “ext/builders”. This will need to be returned with search results when processing a query.
Parameters
• pagename – the name of the page being indexed
• filename – the name of the original source file
• title – the page’s title
• text – the full text of the page
BaseSearch.query(q)
Called by the web support api to get search results. This method compiles the regular expres-
sion to be used when extracting context, then calls handle_query(). You won’t want to
override this unless you don’t want to use the included extract_context() method. Override
handle_query() instead.
Parameters q – the search query string.
BaseSearch.handle_query(q)
Called by query() to retrieve search results for a search query q. This should return an iterable
containing tuples of the following format:
path and title are the same values that were passed to add_document(), and context should be a
short text snippet of the text surrounding the search query in the document.
The extract_context() method is provided as a simple way to create the context.
Parameters q – the search query
BaseSearch.extract_context(text, length=240)
Extract the context for the search query from the document’s full text.
Parameters
• text – the full text of the document to create the context for
• length – the length of the context snippet to return.
To create a custom storage backend you will need to subclass the StorageBackend class. Then create an
instance of the new class and pass that as the storage keyword argument when you create the WebSupport
object:
support = WebSupport(srcdir=srcdir,
builddir=builddir,
storage=MyStorage())
For more information about creating a custom storage backend, please see the documentation of the
StorageBackend class below.
class sphinxcontrib.websupport.storage.StorageBackend
Defines an interface for storage backends.
Changed in version 1.6: StorageBackend class is moved to sphinxcontrib.websupport.storage from
sphinx.websupport.storage.
12.4.1 Methods
StorageBackend.pre_build()
Called immediately before the build process begins. Use this to prepare the StorageBackend for the
addition of nodes.
StorageBackend.add_node(id, document, source)
Add a node to the StorageBackend.
Parameters
Parameters
• old_username – The username being changed.
• new_username – What the username is being changed to.
StorageBackend.accept_comment(comment_id)
Called when a moderator accepts a comment. After the method is called the comment should be
displayed to all users.
Parameters comment_id – The id of the comment being accepted.
THIRTEEN
MAN PAGES
13.1.1 sphinx-quickstart
Synopsis
sphinx-quickstart
Description
sphinx-quickstart is an interactive tool that asks some questions about your project and then gener-
ates a complete documentation directory and sample Makefile to be used with sphinx-build(1).
Options
-q, --quiet
Quiet mode that will skip interactive wizard to specify options. This option requires -p, -a and -v
options.
-h, --help, --version
Display usage summary or Sphinx version.
Structure Options
--sep
If specified, separate source and build directories.
--dot=DOT
Inside the root directory, two more directories will be created; “_templates” for custom HTML tem-
plates and “_static” for custom stylesheets and other static files. You can enter another prefix (such
as “.”) to replace the underscore.
-p PROJECT, --project=PROJECT
Project name will be set. (see project).
189
Sphinx Documentation, Release 3.0.0+/0fb832baa
-a AUTHOR, --author=AUTHOR
Author names. (see copyright).
-v VERSION
Version of project. (see version).
-r RELEASE, --release=RELEASE
Release of project. (see release).
-l LANGUAGE, --language=LANGUAGE
Document language. (see language).
--suffix=SUFFIX
Source file suffix. (see source_suffix).
--master=MASTER
Master document name. (see master_doc).
Extension Options
--ext-autodoc
Enable sphinx.ext.autodoc extension.
--ext-doctest
Enable sphinx.ext.doctest extension.
--ext-intersphinx
Enable sphinx.ext.intersphinx extension.
--ext-todo
Enable sphinx.ext.todo extension.
--ext-coverage
Enable sphinx.ext.coverage extension.
--ext-imgmath
Enable sphinx.ext.imgmath extension.
--ext-mathjax
Enable sphinx.ext.mathjax extension.
--ext-ifconfig
Enable sphinx.ext.ifconfig extension.
--ext-viewcode
Enable sphinx.ext.viewcode extension.
--ext-githubpages
Enable sphinx.ext.githubpages extension.
--extensions=EXTENSIONS
Enable arbitrary extensions.
--batchfile, --no-batchfile
Create (or not create) batchfile
Project templating
See also
sphinx-build(1)
13.1.2 sphinx-build
Synopsis
Description
sphinx-build generates documentation from the files in <sourcedir> and places it in the
<outputdir>.
sphinx-build looks for <sourcedir>/conf.py for the configuration settings.
sphinx-quickstart(1) may be used to generate template files, including conf.py.
sphinx-build can create documentation in different formats. A format is selected by specifying the
builder name on the command line; it defaults to HTML. Builders can also perform other tasks related to
documentation processing.
By default, everything that is outdated is built. Output only for selected files can be built by specifying
individual filenames.
For a list of available options, refer to sphinx-build -b.
Options
-b buildername
The most important option: it selects a builder. The most common builders are:
html Build HTML pages. This is the default builder.
dirhtml Build HTML pages, but with a single directory per document. Makes for prettier URLs (no
.html) if served from a webserver.
singlehtml Build a single HTML with the whole content.
htmlhelp, qthelp, devhelp, epub Build HTML files with additional information for building a doc-
umentation collection in one of these formats.
applehelp Build an Apple Help Book. Requires hiutil and codesign, which are not Open Source
and presently only available on Mac OS X 10.6 and higher.
latex Build LaTeX sources that can be compiled to a PDF document using pdflatex.
man Build manual pages in groff format for UNIX systems.
texinfo Build Texinfo files that can be processed into Info files using makeinfo.
text Build plain text files.
gettext Build gettext-style message catalogs (.pot files).
doctest Run all doctests in the documentation, if the doctest extension is enabled.
linkcheck Check the integrity of all external links.
xml Build Docutils-native XML files.
pseudoxml Build compact pretty-printed “pseudo-XML” files displaying the internal structure of
the intermediate document trees.
See Builders for a list of all builders shipped with Sphinx. Extensions can add their own builders.
-M buildername
Alternative to -b. Uses the Sphinx make_mode module, which provides the same build functionality
as a default Makefile or Make.bat. In addition to all Sphinx Builders, the following build pipelines are
available:
latexpdf Build LaTeX files and run them through pdflatex, or as per latex_engine setting. If
language is set to 'ja', will use automatically the platex/dvipdfmx latex to PDF pipeline.
info Build Texinfo files and run them through makeinfo.
-d path
Since Sphinx has to read and parse all source files before it can write an output file, the parsed source
files are cached as “doctree pickles”. Normally, these files are put in a directory called .doctrees
under the build directory; with this option you can select a different cache directory (the doctrees
can be shared between all builders).
-j N
Distribute the build over N processes in parallel, to make building on multiprocessor machines more
effective. Note that not all parts and not all builders of Sphinx can be parallelized. If auto argument
is given, Sphinx uses the number of CPUs as N.
New in version 1.2: This option should be considered experimental.
Changed in version 1.7: Support auto argument.
-c path
Don’t look for the conf.py in the source directory, but use the given configuration directory instead.
Note that various other files and paths given by configuration values are expected to be relative to
the configuration directory, so they will have to be present at this location too.
New in version 0.3.
-C
Don’t look for a configuration file; only take options via the -D option.
New in version 0.5.
-D setting=value
Override a configuration value set in the conf.py file. The value must be a number, string, list or
dictionary value.
For lists, you can separate elements with a comma like this: -D html_theme_path=path1,path2.
For dictionary values, supply the setting name and key like this: -D latex_elements.
docclass=scrartcl.
For boolean values, use 0 or 1 as the value.
Changed in version 0.6: The value can now be a dictionary value.
Changed in version 1.3: The value can now also be a list value.
-A name=value
Make the name assigned to value in the HTML templates.
New in version 0.5.
-n
Run in nit-picky mode. Currently, this generates warnings for all missing references. See the config
value nitpick_ignore for a way to exclude some references as “known missing”.
-N
Do not emit colored output.
-v
Increase verbosity (loglevel). This option can be given up to three times to get more debug logging
output. It implies -T.
New in version 1.2.
-q
Do not output anything on standard output, only write warnings and errors to standard error.
-Q
Do not output anything on standard output, also suppress warnings. Only errors are written to
standard error.
-w file
Write warnings (and errors) to the given file, in addition to standard error.
-W
Turn warnings into errors. This means that the build stops at the first warning and sphinx-build
exits with exit status 1.
--keep-going
With -W option, keep going processing when getting warnings to the end of build, and
sphinx-build exits with exit status 1.
New in version 1.8.
-T
Display the full traceback when an unhandled exception occurs. Otherwise, only a summary is
displayed and the traceback information is saved to a file for further analysis.
New in version 1.2.
-P
(Useful for debugging only.) Run the Python debugger, pdb, if an unhandled exception occurs while
building.
-h, --help, --version
Display usage summary or Sphinx version.
New in version 1.2.
You can also give one or more filenames on the command line after the source and build directories.
Sphinx will then try to build only these output files (and their dependencies).
Environment Variables
Makefile Options
The Makefile and make.bat files created by sphinx-quickstart usually run sphinx-build only
with the -b and -d options. However, they support the following variables to customize behavior:
PAPER
This sets the 'papersize' key of latex_elements: i.e. PAPER=a4 sets it to 'a4paper' and
PAPER=letter to 'letterpaper'.
Note: Usage of this environment variable got broken at Sphinx 1.5 as a4 or letter ended up as
option to LaTeX document in place of the needed a4paper, resp. letterpaper. Fixed at 1.7.7.
SPHINXBUILD
The command to use instead of sphinx-build.
BUILDDIR
The build directory to use instead of the one chosen in sphinx-quickstart.
SPHINXOPTS
Additional options for sphinx-build. These options can also be set via the shortcut variable O
(capital ‘o’).
Deprecation Warnings
If any deprecation warning like RemovedInSphinxXXXWarning are displayed when building a user’s
document, some Sphinx extension is using deprecated features. In that case, please report it to author of
the extension.
To disable the deprecation warnings, please set PYTHONWARNINGS= environment variable to your envi-
ronment. For example:
• PYTHONWARNINGS= make html (Linux/Mac)
• export PYTHONWARNINGS= and do make html (Linux/Mac)
• set PYTHONWARNINGS= and do make html (Windows)
• modify your Makefile/make.bat and set the environment variable
See also
sphinx-quickstart(1)
13.2.1 sphinx-apidoc
Synopsis
Description
sphinx-apidoc is a tool for automatic generation of Sphinx sources that, using the autodoc extension,
document a whole package in the style of other automatic API documentation tools.
MODULE_PATH is the path to a Python package to document, and OUTPUT_PATH is the directory
where the generated sources are placed. Any EXCLUDE_PATTERNs given are fnmatch-style226 file and/or
directory patterns that will be excluded from generation.
Warning: sphinx-apidoc generates source files that use sphinx.ext.autodoc to document all
found modules. If any modules have side effects on import, these will be executed by autodoc when
sphinx-build is run.
If you document scripts (as opposed to library modules), make sure their main routine is protected by
a if __name__ == '__main__' condition.
Options
-o <OUTPUT_PATH>
Directory to place the output files. If it does not exist, it is created.
-f, --force
Force overwriting of any existing generated files.
226 https://docs.python.org/3/library/fnmatch.html
-l, --follow-links
Follow symbolic links.
-n, --dry-run
Do not create any files.
-s <suffix>
Suffix for the source files generated. Defaults to rst.
-d <MAXDEPTH>
Maximum depth for the generated table of contents file.
--tocfile
Filename for a table of contents file. Defaults to modules.
-T, --no-toc
Do not create a table of contents file. Ignored when --full is provided.
-F, --full
Generate a full Sphinx project (conf.py, Makefile etc.) using the same mechanism as
sphinx-quickstart.
-e, --separate
Put documentation for each module on its own page.
New in version 1.2.
-E, --no-headings
Do not create headings for the modules/packages. This is useful, for example, when docstrings
already contain headings.
-P, --private
Include “_private” modules.
New in version 1.2.
--implicit-namespaces
By default sphinx-apidoc processes sys.path searching for modules only. Python 3.3 introduced
PEP 420227 implicit namespaces that allow module path structures such as foo/bar/module.py
or foo/bar/baz/__init__.py (notice that bar and foo are namespaces, not modules).
Interpret paths recursively according to PEP-0420.
-M, --module-first
Put module documentation before submodule documentation.
These options are used when --full is specified:
-a
Append module_path to sys.path.
-H <project>
Sets the project name to put in generated files (see project).
-A <author>
Sets the author name(s) to put in generated files (see copyright).
-V <version>
Sets the project version to put in generated files (see version).
-R <release>
Sets the project release to put in generated files (see release).
227 https://www.python.org/dev/peps/pep-0420
Environment
SPHINX_APIDOC_OPTIONS
A comma-separated list of option to append to generated automodule directives. Defaults to
members,undoc-members,show-inheritance.
See also
sphinx-build(1), sphinx-autogen(1)
13.2.2 sphinx-autogen
Synopsis
Description
sphinx-autogen is a tool for automatic generation of Sphinx sources that, using the autodoc extension,
document items included in autosummary listing(s).
sourcefile is the path to one or more reStructuredText documents containing autosummary entries with
the :toctree:: option set. sourcefile can be an fnmatch-style pattern.
Options
-o <outputdir>
Directory to place the output file. If it does not exist, it is created. Defaults to the value passed to
the :toctree: option.
-s <suffix>, --suffix <suffix>
Default suffix to use for generated files. Defaults to rst.
-t <templates>, --templates <templates>
Custom template directory. Defaults to None.
-i, --imported-members
Document imported members.
Example
docs
index.rst
...
foobar
foo
__init__.py
bar
__init__.py
baz
__init__.py
Modules
=======
.. autosummary::
:toctree: modules
foobar.foo
foobar.bar
foobar.bar.baz
docs
index.rst
modules
foobar.bar.rst
foobar.bar.baz.rst
foobar.foo.rst
and each of those files will contain a autodoc directive and some other information.
See also
sphinx-build(1), sphinx-apidoc(1)
FOURTEEN
Note: This document provides information about creating your own theme. If you simply wish to use a
pre-existing HTML themes, refer to HTML.
Sphinx supports changing the appearance of its HTML output via themes. A theme is a collection of HTML
templates, stylesheet(s) and other static files. Additionally, it has a configuration file which specifies from
which theme to inherit, which highlighting style to use, and what options exist for customizing the theme’s
look and feel.
Themes are meant to be project-unaware, so they can be used for different projects without change.
Themes take the form of either a directory or a zipfile (whose name is the theme name), containing the
following:
• A theme.conf file.
• HTML templates, if needed.
• A static/ directory containing any static files that will be copied to the output static directory on
build. These can be images, styles, script files.
The theme.conf file is in INI format1 (readable by the standard Python ConfigParser module) and
has the following structure:
[theme]
inherit = base theme
stylesheet = main CSS name
pygments_style = stylename
sidebars = localtoc.html, relations.html, sourcelink.html, searchbox.html
[options]
variable = default value
• The inherit setting gives the name of a “base theme”, or none. The base theme will be used to locate
missing templates (most themes will not have to supply most templates if they use basic as the
base theme), its options will be inherited, and all of its static files will be used as well. If you want
to also inherit the stylesheet, include it via CSS’ @import in your own.
1 It is not an executable Python file, as opposed to conf.py, because that would pose an unnecessary security risk if themes are
shared.
199
Sphinx Documentation, Release 3.0.0+/0fb832baa
• The stylesheet setting gives the name of a CSS file which will be referenced in the HTML header.
If you need more than one CSS file, either include one from the other via CSS’ @import, or use
a custom HTML template that adds <link rel="stylesheet"> tags as necessary. Setting the
html_style config value will override this setting.
• The pygments_style setting gives the name of a Pygments style to use for highlighting. This can be
overridden by the user in the pygments_style config value.
• The sidebars setting gives the comma separated list of sidebar templates for constructing sidebars.
This can be overridden by the user in the html_sidebars config value.
• The options section contains pairs of variable names and default values. These options can
be overridden by the user in html_theme_options and are accessible from all templates as
theme_<name>.
New in version 1.7: sidebar settings
As a way to distribute your theme, you can use Python package. Python package brings to users easy
setting up ways.
To distribute your theme as a Python package, please define an entry point called sphinx.html_themes
in your setup.py file, and write a setup() function to register your themes using add_html_theme()
API in it:
# 'setup.py'
setup(
...
entry_points = {
'sphinx.html_themes': [
'name_of_theme = your_package',
]
},
...
)
# 'your_package.py'
from os import path
def setup(app):
app.add_html_theme('name_of_theme', path.abspath(path.dirname(__file__)))
If your theme package contains two or more themes, please call add_html_theme() twice or more.
New in version 1.2: ‘sphinx_themes’ entry_points feature.
Deprecated since version 1.6: sphinx_themes entry_points has been deprecated.
New in version 1.6: sphinx.html_themes entry_points feature.
14.3 Templating
The guide to templating is helpful if you want to write your own templates. What is important to keep in
mind is the order in which Sphinx searches for templates:
Since theme options are meant for the user to configure a theme more easily, without having to write a
custom stylesheet, it is necessary to be able to template static files as well as HTML files. Therefore, Sphinx
supports so-called “static templates”, like this:
If the name of a file in the static/ directory of a theme (or in the user’s static path, for that matter) ends
with _t, it will be processed by the template engine. The _t will be left from the final file name. For
example, the classic theme has a file static/classic.css_t which uses templating to put the color
options into the stylesheet. When a documentation is built with the classic theme, the output directory
will contain a _static/classic.css file where all template tags have been processed.
FIFTEEN
TEMPLATING
Sphinx uses the Jinja228 templating engine for its HTML templates. Jinja is a text-based engine, and
inspired by Django templates, so anyone having used Django will already be familiar with it. It also has
excellent documentation for those who need to make themselves familiar with it.
The default templating language in Sphinx is Jinja. It’s Django/Smarty inspired and easy to understand.
The most important concept in Jinja is template inheritance, which means that you can overwrite only
specific blocks within a template, customizing it while also keeping the changes at a minimum.
To customize the output of your documentation you can override all the templates (both the layout tem-
plates and the child templates) by adding files with the same name as the original filename into the
template directory of the structure the Sphinx quickstart generated for you.
Sphinx will look for templates in the folders of templates_path first, and if it can’t find the template
it’s looking for there, it falls back to the selected theme’s templates.
A template contains variables, which are replaced with values when the template is evaluated, tags, which
control the logic of the template and blocks which are used for template inheritance.
Sphinx’s basic theme provides base templates with a couple of blocks it will fill with data. These are
located in the themes/basic subdirectory of the Sphinx installation directory, and used by all builtin
Sphinx themes. Templates with the same name in the templates_path override templates supplied by
the selected theme.
For example, to add a new link to the template area containing related links all you have to do is to add a
new template called layout.html with the following contents:
228 http://jinja.pocoo.org
203
Sphinx Documentation, Release 3.0.0+/0fb832baa
{% extends "!layout.html" %}
{% block rootrellink %}
<li><a href="https://project.invalid/">Project Homepage</a> »</li>
{{ super() }}
{% endblock %}
By prefixing the name of the overridden template with an exclamation mark, Sphinx will load the layout
template from the underlying HTML theme.
Important: If you override a block, call {{ super() }} somewhere to render the block’s original content
in the extended template – unless you don’t want that content to show up.
The builtin basic theme supplies the templates that all builtin Sphinx themes are based on. It has the
following elements you can override or use:
15.3.1 Blocks
rootrellink / relbaritems Inside the relbar there are three sections: The rootrellink, the links from the doc-
umentation and the custom relbaritems. The rootrellink is a block that by default contains a list item
pointing to the master document by default, the relbaritems is an empty block. If you override them
to add extra links into the bar make sure that they are list items and end with the reldelim1.
document The contents of the document itself. It contains the block “body” where the individual content
is put by subtemplates like page.html.
sidebar1 / sidebar2 A possible location for a sidebar. sidebar1 appears before the document and is empty
by default, sidebar2 after the document and contains the default sidebar. If you want to swap the
sidebar location override this and call the sidebar helper:
(The sidebar2 location for the sidebar is needed by the sphinxdoc.css stylesheet, for example.)
sidebarlogo The logo location within the sidebar. Override this if you want to place some content at the
top of the sidebar.
footer The block for the footer div. If you want a custom footer or markup before or after it, override this
one.
The following four blocks are only used for pages that do not have assigned a list of custom sidebars in
the html_sidebars config value. Their use is deprecated in favor of separate sidebar templates, which
can be included via html_sidebars.
sidebartoc The table of contents within the sidebar.
Deprecated since version 1.0.
sidebarrel The relation links (previous, next document) within the sidebar.
Deprecated since version 1.0.
sidebarsourcelink The “Show source” link within the sidebar (normally only shown if this is enabled by
html_show_sourcelink).
Deprecated since version 1.0.
sidebarsearch The search box within the sidebar. Override this if you want to place some content at the
bottom of the sidebar.
Deprecated since version 1.0.
Inside templates you can set a couple of variables used by the layout template using the {% set %} tag:
reldelim1
The delimiter for the items on the left side of the related bar. This defaults to ' »' Each
item in the related bar ends with the value of this variable.
reldelim2
The delimiter for the items on the right side of the related bar. This defaults to ' |'. Each item
except of the last one in the related bar ends with the value of this variable.
Overriding works like this:
{% extends "!layout.html" %}
{% set reldelim1 = ' >' %}
script_files
Add additional script files here, like this:
Sphinx provides various Jinja functions as helpers in the template. You can use them to generate links or
output multiply used elements.
pathto(document)
Return the path to a Sphinx document as a URL. Use this to refer to built documents.
pathto(file, 1)
Return the path to a file which is a filename relative to the root of the generated output. Use this to
refer to static files.
hasdoc(document)
Check if a document with the name document exists.
sidebar()
Return the rendered sidebar.
relbar()
Return the rendered relation bar.
warning(message)
Emit a warning message.
These global variables are available in every template and are safe to use. There are more, but most of
them are an implementation detail and might change in the future.
builder
The name of the builder (e.g. html or htmlhelp).
copyright
The value of copyright.
docstitle
The title of the documentation (the value of html_title), except when the “single-file” builder is
used, when it is set to None.
embedded
True if the built HTML is meant to be embedded in some viewing application that handles naviga-
tion, not the web browser, such as for HTML help or Qt help formats. In this case, the sidebar is not
included.
favicon
The path to the HTML favicon in the static path, or ''.
file_suffix
The value of the builder’s out_suffix attribute, i.e. the file name extension that the output files
will get. For a standard HTML builder, this is usually .html.
has_source
True if the reST document sources are copied (if html_copy_source is True).
language
The value of language.
last_updated
The build date.
logo
The path to the HTML logo image in the static path, or ''.
master_doc
The value of master_doc, for usage with pathto().
pagename
The “page name” of the current file, i.e. either the document name if the file is generated from
a reST source, or the equivalent hierarchical name relative to the output directory ([directory/
]filename_without_extension).
project
The value of project.
release
The value of release.
rellinks
A list of links to put at the left side of the relbar, next to “next” and “prev”. This usually contains
links to the general index and other indices, such as the Python module index. If you add something
yourself, it must be a tuple (pagename, link title, accesskey, link text).
shorttitle
The value of html_short_title.
show_source
True if html_show_sourcelink is True.
sphinx_version
The version of Sphinx used to build.
style
The name of the main stylesheet, as given by the theme or html_style.
title
The title of the current document, as used in the <title> tag.
use_opensearch
The value of html_use_opensearch.
version
The value of version.
In addition to these values, there are also all theme options available (prefixed by theme_), as well as the
values given by the user in html_context.
In documents that are created from source files (as opposed to automatically-generated files like the
module index, or documents that already are in HTML form), these variables are also available:
body
A string containing the content of the page in HTML form as produced by the HTML builder, before
the theme is applied.
display_toc
A boolean that is True if the toc contains more than one entry.
meta
Document metadata (a dictionary), see File-wide metadata.
metatags
A string containing the page’s HTML meta229 tags.
next
The next document for the navigation. This variable is either false or has two attributes link and title.
The title contains HTML markup. For example, to generate a link to the next page, you can use this
snippet:
{% if next %}
<a href="{{ next.link|e }}">{{ next.title }}</a>
{% endif %}
page_source_suffix
The suffix of the file that was rendered. Since we support a list of source_suffix, this will allow
you to properly link to the original source file.
229 http://docutils.sourceforge.net/docs/ref/rst/directives.html#meta
parents
A list of parent documents for navigation, structured like the next item.
prev
Like next, but for the previous page.
sourcename
The name of the copied source file for the current document. This is only nonempty if the
html_copy_source value is True. This has empty value on creating automatically-generated
files.
title
The page title.
toc
The local table of contents for the current page, rendered as HTML bullet lists.
toctree
A callable yielding the global TOC tree containing the current page, rendered as HTML bullet lists.
Optional keyword arguments:
• collapse (True by default): if true, all TOC entries that are not ancestors of the current page
are collapsed
• maxdepth (defaults to the max depth selected in the toctree directive): the maximum depth of
the tree; set it to -1 to allow unlimited depth
• titles_only (False by default): if true, put only toplevel document titles in the tree
• includehidden (False by default): if true, the TOC tree will also contain hidden entries.
SIXTEEN
LATEX CUSTOMIZATION
16.1 Example
Keep in mind that backslashes must be doubled in Python string literals to avoid interpretation as escape
sequences, or use raw strings (as is done here).
# inside conf.py
latex_engine = 'xelatex'
latex_elements = {
'fontpkg': r'''
\setmainfont{DejaVu Serif}
\setsansfont{DejaVu Sans}
\setmonofont{DejaVu Sans Mono}
''',
'preamble': r'''
\usepackage[titles]{tocloft}
\cftsetpnumwidth {1.25cm}\cftsetrmarg{1.5cm}
\setlength{\cftchapnumwidth}{0.75cm}
\setlength{\cftsecindent}{\cftchapnumwidth}
\setlength{\cftsecnumwidth}{1.25cm}
''',
'fncychap': r'\usepackage[Bjornstrup]{fncychap}',
'printindex': r'\footnotesize\raggedright\printindex',
}
latex_show_urls = 'footnote'
A dictionary that contains LaTeX snippets overriding those Sphinx usually puts into the generated .tex
files. Its 'sphinxsetup' key is described separately.
• Keys that you may want to override include:
'papersize' Paper size option of the document class ('a4paper' or 'letterpaper'), default
'letterpaper'.
209
Sphinx Documentation, Release 3.0.0+/0fb832baa
'pointsize' Point size option of the document class ('10pt', '11pt' or '12pt'), default
'10pt'.
'pxunit' the value of the px when used in image attributes width and height. The default
value is '0.75bp' which achieves 96px=1in (in TeX 1in = 72bp = 72.27pt.) To obtain
for example 100px=1in use '0.01in' or '0.7227pt' (the latter leads to TeX computing a
more precise value, due to the smaller unit used in the specification); for 72px=1in, simply
use '1bp'; for 90px=1in, use '0.8bp' or '0.803pt'.
New in version 1.5.
'passoptionstopackages' A string which will be positioned early in the preamble, designed
to contain \\PassOptionsToPackage{options}{foo} commands. Default empty.
New in version 1.4.
'babel' “babel” package inclusion, default '\\usepackage{babel}' (the suitable document
language string is passed as class option, and english is used if no language.) For Japanese
documents, the default is the empty string.
With XeLaTeX and LuaLaTeX, Sphinx configures the LaTeX document to use polyglossia230 , but
one should be aware that current babel231 has improved its support for Unicode engines in
recent years and for some languages it may make sense to prefer babel over polyglossia.
Hint: After modifiying a core LaTeX key like this one, clean up the LaTeX build repertory
before next PDF build, else left-over auxiliary files are likely to break the build.
\substitutefont{LGR}{\rmdefault}{cmr}
\substitutefont{LGR}{\sfdefault}{cmss}
\substitutefont{LGR}{\ttdefault}{cmtt}
\substitutefont{X2}{\rmdefault}{cmr}
\substitutefont{X2}{\sfdefault}{cmss}
\substitutefont{X2}{\ttdefault}{cmtt}
but this is activated only under the condition that the 'fontenc' key is configured to load
the LGR (Greek) and/or X2 (Cyrillic) pdflatex-font encodings (if the language is set to
a Cyrillic language, this 'fontpkg' key must be used as “times” package has no direct
support for it; then keep only LGR lines from the above, if support is needed for Greek in
the text).
230 https://ctan.org/pkg/polyglossia
231 https://ctan.org/pkg/babel
The \substitutefont command is from the eponymous LaTeX package, which is loaded
by Sphinx if needed (on Ubuntu xenial it is part of texlive-latex-extra which is a
Sphinx requirement).
Only if the document actually does contain Unicode Greek letters (in text) or Cyrillic letters,
will the above default set-up cause additional requirements for the PDF build. On Ubuntu
xenial, texlive-lang-greek, texlive-lang-cyrillic, and (with the above choice
of fonts) the cm-super (or cm-super-minimal) package.
– For 'xelatex' and 'lualatex', the default is to use the FreeFont family: this Open-
Type font family supports both Cyrillic and Greek scripts and is available as separate
Ubuntu xenial package fonts-freefont-otf, it is not needed to install the big pack-
age texlive-fonts-extra.
– 'platex' (Japanese documents) engine supports individual Cyrillic and Greek letters with
no need of extra user set-up.
'fncychap' Inclusion of the “fncychap” package (which makes fancy chapter titles), default
'\\usepackage[Bjarne]{fncychap}' for English documentation (this option is slightly
customized by Sphinx), '\\usepackage[Sonny]{fncychap}' for internationalized docs
(because the “Bjarne” style uses numbers spelled out in English). Other “fncychap” styles
you can try are “Lenny”, “Glenn”, “Conny”, “Rejne” and “Bjornstrup”. You can also set this to
'' to disable fncychap.
The default is '' for Japanese documents.
'preamble' Additional preamble content, default empty. One may move all needed macros into
some file mystyle.tex.txt of the project source repertory, and get LaTeX to import it at run
time:
'preamble': r'\input{mystyle.tex.txt}',
# or, if the \ProvidesPackage LaTeX macro is used in a file mystyle.
,→sty
'preamble': r'\usepackage{mystyle}',
latex_additional_files = ["mystyle.sty"]
'figure_align' Latex figure float alignment, default ‘htbp’ (here, top, bottom, page). Whenever
an image doesn’t fit into the current page, it will be ‘floated’ into the next page but may be
preceded by any other text. If you don’t like this behavior, use ‘H’ which will disable floating
and position figures strictly in the order they appear in the source.
New in version 1.3.
'atendofbody' Additional document content (right before the indices), default empty.
New in version 1.5.
'footer' Additional footer content (before the indices), default empty.
Deprecated since version 1.5: Use 'atendofbody' key instead.
• Keys that don’t need to be overridden unless in special cases are:
'extraclassoptions' The default is the empty string. Example: 'extraclassoptions':
'openany' will allow chapters (for documents of the 'manual' type) to start on any page.
New in version 1.2.
Changed in version 1.6: Added this documentation.
'maxlistdepth' LaTeX allows by default at most 6 levels for nesting list and quote-like environ-
ments, with at most 4 enumerated lists, and 4 bullet lists. Setting this key for example to '10'
(as a string) will allow up to 10 nested levels (of all sorts). Leaving it to the empty string means
to obey the LaTeX default.
Warning:
– Using this key may prove incompatible with some LaTeX packages or special document
classes which do their own list customization.
– The key setting is silently ignored if \usepackage{enumitem} is executed inside the
document preamble. Use then rather the dedicated commands of this LaTeX package.
r'\usepackage[LGR,X2,T1]{fontenc}'
Attention: Prior to 2.0, Unicode Greek letters were escaped to use LaTeX math mark-up.
This is not the case anymore, and the above must be used (only in case of 'pdflatex'
engine) if the source contains such Unicode Greek.
On Ubuntu xenial, packages texlive-lang-greek and cm-super (for the latter, only
if the 'fontpkg' setting is left to its default) are needed for LGR to work. In place of
cm-super one can install smaller cm-super-minimal, but it requires the LaTeX document
to execute \usepackage[10pt]{type1ec} before loading fontenc. Thus, use this key
with this extra at its start if needed.
Hint: Unicode Greek (but no further Unicode symbols) in math can be supported by
'pdflatex' from setting this key to r'\usepackage{textalpha,alphabeta}'. Then
:math:`α` (U+03B1) will render as α. For wider Unicode support in math input, see the
discussion of latex_engine.
New in version 1.5: Previously this was done from inside sphinx.sty.
'maketitle' “maketitle” call, default '\\sphinxmaketitle'. Override if you want to generate
a differently styled title page.
Changed in version 1.8.3: Original \maketitle from document class is not overwritten, hence
is re-usable as part of some custom setting for this key.
New in version 1.8.3: \sphinxbackoftitlepage optional macro. It can also be defined
inside 'preamble' key rather than this one.
'releasename' value that prefixes 'release' element on title page, default 'Release'. As for
title and author used in the tuples of latex_documents, it is inserted as LaTeX markup.
'tableofcontents' “tableofcontents” call, default '\\sphinxtableofcontents' (it is a
wrapper of unmodified \tableofcontents, which may itself be customized by user loaded
packages.) Override if you want to generate a different table of contents or put content between
the title page and the TOC.
Changed in version 1.5: Previously the meaning of \tableofcontents itself was modified
by Sphinx. This created an incompatibility with dedicated packages modifying it also such as
“tocloft” or “etoc”.
'transition' Commands used to display transitions, default
'\n\n\\bigskip\\hrule\\bigskip\n\n'. Override if you want to display transitions
differently.
New in version 1.2.
Changed in version 1.6: Remove unneeded {} after \\hrule.
'printindex' “printindex” call, the last thing in the file, default '\\printindex'. Override
if you want to generate the index differently or append some content after the index. For
example '\\footnotesize\\raggedright\\printindex' is advisable when the index is
full of long entries.
'fvset' Customization of fancyvrb LaTeX package. Sphinx does by default 'fvset':
'\\fvset{fontsize=\\small}', to adjust for the large character width of the monospace
font, used in code-blocks. You may need to modify this if you use custom fonts.
New in version 1.8.
Changed in version 2.0: Due to new default font choice for 'xelatex' and 'lualatex'
(FreeFont), Sphinx does \\fvset{fontsize=\\small} also with these engines (and not
\\fvset{fontsize=auto}).
• Keys that are set by other options and therefore should not be overridden are:
'docclass' 'classoptions' 'title' 'release' 'author' 'makeindex'
latex_elements = {
'sphinxsetup': 'key1=value1, key2=value2, ...',
}
It defaults to empty. If non-empty, it will be passed as argument to the \sphinxsetup macro inside the
document preamble, like this:
\usepackage{sphinx}
\sphinxsetup{key1=value1, key2=value2,...}
Hint: It is possible to insert further uses of the \sphinxsetup LaTeX macro directly into the body of the
document, via the help of the raw directive. Here is how this present chapter is styled in the PDF output:
.. raw:: latex
\begingroup
\sphinxsetup{%
verbatimwithframe=false,
(continues on next page)
.. raw:: latex
\endgroup
at its end.
The colors used in the above are provided by the svgnames option of the “xcolor” package:
latex_elements = {
'passoptionstopackages': r'\PassOptionsToPackage{svgnames}{xcolor}',
}
LaTeX boolean keys require lowercase true or false values. Spaces around the commas and equal signs
are ignored, spaces inside LaTeX macros may be significant.
hmargin, vmargin The dimensions of the horizontal (resp. vertical) margins, passed as hmargin (resp.
vmargin) option to the geometry package. The default is 1in, which is equivalent to {1in,1in}.
Example:
Japanese documents currently accept only the one-dimension format for these parameters. The
geometry package is then passed suitable options to get the text width set to an exact multiple of
the zenkaku width, and the text height set to an integer multiple of the baselineskip, with the closest
fit for the margins.
Hint: For Japanese 'manual' docclass with pointsize 11pt or 12pt, use the nomag extra document
class option (cf. 'extraclassoptions' key of latex_elements) or so-called TeX “true” units:
verbatimwrapslines default true. Tells whether long lines in code-block’s contents should wrap.
literalblockcappos default t for “top”. Decides the caption position. Alternative is b (“bottom”).
New in version 1.7.
verbatimhintsturnover default true. If true, code-blocks display “continued on next page”, “con-
tinued from previous page” hints in case of pagebreaks.
New in version 1.6.3.
Changed in version 1.7: the default changed from false to true.
verbatimcontinuedalign, verbatimcontinuesalign default r. Horizontal position relative to the
framed contents: either l (left aligned), r (right aligned) or c (centered).
New in version 1.7.
parsedliteralwraps default true. Tells whether long lines in parsed-literal232 ’s contents should
wrap.
New in version 1.5.2: set this option value to false to recover former behaviour.
inlineliteralwraps default true. Allows linebreaks inside inline literals: but extra potential break-
points (additionally to those allowed by LaTeX at spaces or for hyphenation) are currently inserted
only after the characters . , ; ? ! /. Due to TeX internals, white space in the line will be
stretched (or shrunk) in order to accomodate the linebreak.
New in version 1.5: set this option value to false to recover former behaviour.
verbatimvisiblespace default \textcolor{red}{\textvisiblespace}. When a long code line
is split, the last space character from the source code line right before the linebreak location is typeset
using this.
verbatimcontinued A LaTeX macro inserted at start of continuation code lines. Its (complicated. . . )
default typesets a small red hook pointing to the right:
\makebox[2\fontcharwd\font`\x][r]{\textcolor{red}{\tiny$\hookrightarrow$}}
Changed in version 1.5: The breaking of long code lines was added at 1.4.2. The default definition of
the continuation symbol was changed at 1.5 to accomodate various font sizes (e.g. code-blocks can
be in footnotes).
TitleColor default {rgb}{0.126,0.263,0.361}. The colour for titles (as configured via use of
package “titlesec”.)
Warning: Colours set via 'sphinxsetup' must obey the syntax of the argument of the color/
xcolor packages \definecolor command.
Note: Starting with this colour key, and for all others coming next, the actual names declared to “color”
or “xcolor” are prefixed with “sphinx”.
verbatimsep default \fboxsep. The separation between code lines and the frame.
verbatimborder default \fboxrule. The width of the frame around code-blocks.
shadowsep default 5pt. The separation between contents and frame for contents233 and topic234 boxes.
shadowsize default 4pt. The width of the lateral “shadow” to the right.
shadowrule default \fboxrule. The width of the frame around topic235 boxes.
noteBorderColor, hintBorderColor, importantBorderColor, tipBorderColor default
{rgb}{0,0,0} (black). The colour for the two horizontal rules used by Sphinx in LaTeX for
styling a note236 type admonition.
noteborder, hintborder, importantborder, tipborder default 0.5pt. The width of the two hor-
izontal rules.
warningBorderColor, cautionBorderColor, attentionB..C.., dangerB..C.., errorB..C..
default {rgb}{0,0,0} (black). The colour for the admonition frame.
warningBgColor, cautionBgColor, attentionBgColor, dangerBgColor, errorBgColor
default {rgb}{1,1,1} (white). The background colours for the respective admonitions.
warningborder, cautionborder, attentionborder, dangerborder, errorborder default 1pt.
The width of the frame.
AtStartFootnote default \mbox{ }. LaTeX macros inserted at the start of the footnote text at bottom
of page, after the footnote number.
BeforeFootnote default \leavevmode\unskip. LaTeX macros inserted before the footnote mark. The
default removes possible space before it (else, TeX could insert a linebreak there).
New in version 1.5.
HeaderFamily default \sffamily\bfseries. Sets the font used by headings.
Here are some macros from the package file sphinx.sty and class files sphinxhowto.cls,
sphinxmanual.cls, which have public names thus allowing redefinitions. Check the respective files
for the defaults.
16.4.1 Macros
– \sphinxtitleref,
– \sphinxmenuselection,
– \sphinxaccelerator,
– \sphinxcrossref,
– \sphinxtermref,
– \sphinxoptional.
New in version 1.4.5: Use of \sphinx prefixed macro names to limit possibilities of conflict with
LaTeX packages.
• more text styling:
– \sphinxstyleindexentry,
– \sphinxstyleindexextra,
– \sphinxstyleindexpageref,
– \sphinxstyletopictitle,
– \sphinxstylesidebartitle,
– \sphinxstyleothertitle,
– \sphinxstylesidebarsubtitle,
– \sphinxstyletheadfamily,
– \sphinxstyleemphasis,
– \sphinxstyleliteralemphasis,
– \sphinxstylestrong,
– \sphinxstyleliteralstrong,
– \sphinxstyleabbreviation,
– \sphinxstyleliteralintitle,
– \sphinxstylecodecontinued,
– \sphinxstylecodecontinues.
New in version 1.5: these macros were formerly hard-coded as non customizable \texttt, \emph,
etc. . .
New in version 1.6: \sphinxstyletheadfamily which defaults to \sffamily and allows mul-
tiple paragraphs in header cells of tables.
New in version 1.6.3: \sphinxstylecodecontinued and \sphinxstylecodecontinues.
• \sphinxtableofcontents: it is a wrapper (defined differently in sphinxhowto.
cls and in sphinxmanual.cls) of standard \tableofcontents. The macro
\sphinxtableofcontentshook is executed during its expansion right before
\tableofcontents itself.
Changed in version 1.5: formerly, the meaning of \tableofcontents was modified by Sphinx.
Changed in version 2.0: hard-coded redefinitions of \l@section and \l@subsection
formerly done during loading of 'manual' docclass are now executed later via
\sphinxtableofcontentshook. This macro is also executed by the 'howto' docclass,
but defaults to empty with it.
16.4.2 Environments
• a figure237 may have an optional legend with arbitrary body elements: they are rendered in a
sphinxlegend environment. The default definition issues \small, and ends with \par.
New in version 1.5.6: formerly, the \small was hardcoded in LaTeX writer and the ending \par
was lacking.
• environments associated with admonitions:
– sphinxnote,
– sphinxhint,
– sphinximportant,
– sphinxtip,
– sphinxwarning,
– sphinxcaution,
– sphinxattention,
– sphinxdanger,
– sphinxerror.
They may be \renewenvironment ‘d individually, and must then be defined with one argument
(it is the heading of the notice, for example Warning: for warning238 directive, if English is the
document language). Their default definitions use either the sphinxheavybox (for the last 5 ones) or
the sphinxlightbox environments, configured to use the parameters (colours, border thickness) specific
to each type, which can be set via 'sphinxsetup' string.
Changed in version 1.5: use of public environment names, separate customizability of the pa-
rameters, such as noteBorderColor, noteborder, warningBgColor, warningBorderColor,
warningborder, . . .
• the contents239 directive (with :local: option) and the topic240 directive are implemented by envi-
ronment sphinxShadowBox.
New in version 1.4.2: former code refactored into an environment allowing page breaks.
Changed in version 1.5: options shadowsep, shadowsize, shadowrule.
237 http://docutils.sourceforge.net/docs/ref/rst/directives.html#figure
238 http://docutils.sourceforge.net/docs/ref/rst/directives.html#warning
239 http://docutils.sourceforge.net/docs/ref/rst/directives.html#contents
240 http://docutils.sourceforge.net/docs/ref/rst/directives.html#topic
• the literal blocks (via :: or code-block), are implemented using sphinxVerbatim environment
which is a wrapper of Verbatim environment from package fancyvrb.sty. It adds the handling
of the top caption and the wrapping of long lines, and a frame which allows pagebreaks. Inside
tables the used environment is sphinxVerbatimintable (it does not draw a frame, but allows a
caption).
Changed in version 1.5: Verbatim keeps exact same meaning as in fancyvrb.sty (also under the
name OriginalVerbatim); sphinxVerbatimintable is used inside tables.
New in version 1.5: options verbatimwithframe, verbatimwrapslines, verbatimsep,
verbatimborder.
New in version 1.6.6: support for :emphasize-lines: option
New in version 1.6.6: easier customizability of the formatting via exposed to user LaTeX macros such
as \sphinxVerbatimHighlightLine.
• the bibliography uses sphinxthebibliography and the Python Module index as well as the gen-
eral index both use sphinxtheindex; these environments are wrappers of the thebibliography
and respectively theindex environments as provided by the document class (or packages).
Changed in version 1.5: formerly, the original environments were modified by Sphinx.
16.4.3 Miscellany
• the section, subsection, . . . headings are set using titlesec’s \titleformat command.
• for the 'manual' docclass, the chapter headings can be customized using fncychap’s commands
\ChNameVar, \ChNumVar, \ChTitleVar. File sphinx.sty has custom re-definitions in case of
fncychap option Bjarne.
Changed in version 1.5: formerly, use of fncychap with other styles than Bjarne was dysfunctional.
Hint: As an experimental feature, Sphinx can use user-defined template file for LaTeX source if you have
a file named _templates/latex.tex_t in your project.
New in version 1.5: currently all template variables are unstable and undocumented.
Additional files longtable.tex_t, tabulary.tex_t and tabular.tex_t can be added to
_templates/ to configure some aspects of table rendering (such as the caption position).
New in version 1.6: currently all template variables are unstable and undocumented.
SEVENTEEN
Since many projects will need special features in their documentation, Sphinx is designed to be extensible
on several levels.
This is what you can do in an extension: First, you can add new builders to support new output formats or
actions on the parsed documents. Then, it is possible to register custom reStructuredText roles and direc-
tives, extending the markup. And finally, there are so-called “hook points” at strategic places throughout
the build process, where an extension can register a hook and run specialized code.
An extension is simply a Python module. When an extension is loaded, Sphinx imports this module and
executes its setup() function, which in turn notifies Sphinx of everything the extension offers – see the
extension tutorial for examples.
The configuration file itself can be treated as an extension if it contains a setup() function. All other
extensions to load must be listed in the extensions configuration value.
setup(
# ...
entry_points={
'sphinx.builders': [
'mybuilder = my.extension.module',
],
}
)
Note that it is still necessary to register the builder using add_builder() in the extension’s setup()
function.
241 https://setuptools.readthedocs.io/en/latest/setuptools.html#dynamic-discovery-of-services-and-plugins
221
Sphinx Documentation, Release 3.0.0+/0fb832baa
There are several key objects whose API you will use while writing an extension. These are:
Application The application object (usually called app) is an instance of Sphinx. It controls most high-
level functionality, such as the setup of extensions, event dispatching and producing output (log-
ging).
If you have the environment object, the application is available as env.app.
Environment The build environment object (usually called env) is an instance of BuildEnvironment.
It is responsible for parsing the source documents, stores all metadata about the document collection
and is serialized to disk after each build.
Its API provides methods to do with access to metadata, resolving references, etc. It can also be used
by extensions to cache information that should persist for incremental rebuilds.
If you have the application or builder object, the environment is available as app.env or builder.
env.
Builder The builder object (usually called builder) is an instance of a specific subclass of Builder.
Each builder class knows how to convert the parsed documents into an output format, or otherwise
process them (e.g. check external links).
If you have the application object, the builder is available as app.builder.
Config The config object (usually called config) provides the values of configuration values set in conf.
py as attributes. It is an instance of Config.
The config is available as app.config or env.config.
To see an example of use of these objects, refer to Extension tutorials.
One thing that is vital in order to understand extension mechanisms is the way in which a Sphinx project
is built: this works in several phases.
Phase 0: Initialization
In this phase, almost nothing of interest to us happens. The source directory is searched
for source files, and extensions are initialized. Should a stored build environment exist, it is
loaded, otherwise a new one is created.
Phase 1: Reading
In Phase 1, all source files (and on subsequent builds, those that are new or changed) are read
and parsed. This is the phase where directives and roles are encountered by docutils, and the
corresponding code is executed. The output of this phase is a doctree for each source file; that
is a tree of docutils nodes. For document elements that aren’t fully known until all existing
files are read, temporary nodes are created.
There are nodes provided by docutils, which are documented in the docutils documentation242 .
Additional nodes are provided by Sphinx and documented here.
During reading, the build environment is updated with all meta- and cross reference data of
the read documents, such as labels, the names of headings, described Python objects and index
entries. This will later be used to replace the temporary nodes.
242 http://docutils.sourceforge.net/docs/ref/doctree.html
The parsed doctrees are stored on the disk, because it is not possible to hold all of them in
memory.
Phase 2: Consistency checks
Some checking is done to ensure no surprises in the built documents.
Phase 3: Resolving
Now that the metadata and cross-reference data of all existing documents is known, all tempo-
rary nodes are replaced by nodes that can be converted into output using components called
transforms. For example, links are created for object references that exist, and simple literal
nodes are created for those that don’t.
Phase 4: Writing
This phase converts the resolved doctrees to the desired output format, such as HTML or
LaTeX. This happens via a so-called docutils writer that visits the individual nodes of each
doctree and produces some output in the process.
Note: Some builders deviate from this general build plan, for example, the builder that checks external
links does not need anything more than the parsed doctrees and therefore does not have phases 2–4.
Each Sphinx extension is a Python module with at least a setup() function. This function is called at
initialization time with one argument, the application object representing the Sphinx process.
class sphinx.application.Sphinx
This application object has the public API described in the following.
Extension setup
Sphinx.set_translator(name, translator_class)
Register or override a Docutils translator class.
This is used to register a custom output translator or to replace a builtin translator. This allows
extensions to use custom translator and define custom nodes for the translator (see add_node()).
New in version 1.3.
Changed in version 1.8: Add override keyword.
Sphinx.add_node(node, **kwds)
Register a Docutils node class.
This is necessary for Docutils internals. It may also be used in the future to validate nodes in the
parsed documents.
Node visitor functions for the Sphinx HTML, LaTeX, text and manpage writers can be given as
keyword arguments: the keyword should be one or more of 'html', 'latex', 'text', 'man',
'texinfo' or any other supported translators, the value a 2-tuple of (visit, depart) methods.
depart can be None if the visit function raises docutils.nodes.SkipNode. Example:
Obviously, translators for which you don’t specify visitor methods will choke on the node when
encountered in a document to translate.
Changed in version 0.5: Added the support for keyword arguments giving visit functions.
Sphinx.add_enumerable_node(node, figtype, title_getter=None, **kwds)
Register a Docutils node class as a numfig target.
Sphinx numbers the node automatically. And then the users can refer it using numref.
figtype is a type of enumerable nodes. Each figtypes have individual numbering sequences. As a
system figtypes, figure, table and code-block are defined. It is able to add custom nodes to
these default figtypes. It is also able to define new custom figtype if new figtype is given.
title_getter is a getter function to obtain the title of node. It takes an instance of the enumerable node,
and it must return its title as string. The title is used to the default title of references for ref. By
default, Sphinx searches docutils.nodes.caption or docutils.nodes.title from the node
as a title.
Other keyword arguments are used for node visitor functions. See the Sphinx.add_node() for
details.
New in version 1.4.
Sphinx.add_directive(name, func, content, arguments, **options)
Sphinx.add_directive(name, directiveclass)
Register a Docutils directive.
name must be the prospective directive name. cls is a directive class which inherits docutils.
parsers.rst.Directive. For more details, see the Docutils docs243 .
For example, the (already existing) literalinclude directive would be added like this:
243 http://docutils.sourceforge.net/docs/howto/rst-directives.html
class LiteralIncludeDirective(Directive):
has_content = True
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = True
option_spec = {
'class': directives.class_option,
'name': directives.unchanged,
}
def run(self):
...
add_directive('literalinclude', LiteralIncludeDirective)
Changed in version 0.6: Docutils 0.5-style directive classes are now supported.
Deprecated since version 1.8: Docutils 0.4-style (function based) directives support is deprecated.
Changed in version 1.8: Add override keyword.
Sphinx.add_role(name, role)
Register a Docutils role.
name must be the role name that occurs in the source, role the role function. Refer to the Docutils
documentation244 for more information.
Changed in version 1.8: Add override keyword.
Sphinx.add_generic_role(name, nodeclass)
Register a generic Docutils role.
Register a Docutils role that does nothing but wrap its contents in the node given by nodeclass.
New in version 0.6.
Changed in version 1.8: Add override keyword.
Sphinx.add_domain(domain)
Register a domain.
Make the given domain (which must be a class; more precisely, a subclass of Domain) known to
Sphinx.
New in version 1.0.
Changed in version 1.8: Add override keyword.
Sphinx.add_directive_to_domain(domain, name, func, content, arguments, **options)
Sphinx.add_directive_to_domain(domain, name, directiveclass)
Register a Docutils directive in a domain.
Like add_directive(), but the directive is added to the domain named domain.
New in version 1.0.
Changed in version 1.8: Add override keyword.
244 http://docutils.sourceforge.net/docs/howto/rst-roles.html
.. rst:directive:: function
Document a function.
<...>
For the directive, an index entry will be generated as if you had prepended
The reference node will be of class literal (so it will be rendered in a proportional font, as
appropriate for code) unless you give the ref_nodeclass argument, which must be a docutils node
class. Most useful are docutils.nodes.emphasis or docutils.nodes.strong – you can also
use docutils.nodes.generated if you want no further text decoration. If the text should be
treated as literal (e.g. no smart quote replacement), but not have typewriter styling, use sphinx.
addnodes.literal_emphasis or sphinx.addnodes.literal_strong.
For the role content, you have the same syntactical possibilities as for standard Sphinx roles (see
Cross-referencing syntax).
Changed in version 1.8: Add override keyword.
Sphinx.add_crossref_type(directivename, rolename, indextemplate=”, ref_nodeclass=None, obj-
name=”)
Register a new crossref object type.
This method is very similar to add_object_type() except that the directive it generates must be
empty, and will produce no output.
That means that you can add semantic targets to your sources, and refer to them using custom roles
instead of generic ones (like ref). Example call:
Example usage:
(Of course, the element following the topic directive needn’t be a section.)
Changed in version 1.8: Add override keyword.
Sphinx.add_transform(transform)
Register a Docutils transform to be applied after parsing.
Add the standard docutils Transform subclass transform to the list of transforms that are applied
after Sphinx parses a reST document.
Sphinx.add_js_file(filename, **kwargs)
Register a JavaScript file to include in the HTML output.
Add filename to the list of JavaScript files that the default HTML template will include. The filename
must be relative to the HTML static path , or a full URI with scheme. The keyword arguments are
also accepted for attributes of <script> tag.
Example:
app.add_js_file('example.js')
# => <script src="_static/example.js"></script>
app.add_js_file('example.js', async="async")
# => <script src="_static/example.js" async="async"></script>
app.add_css_file('custom.css')
# => <link rel="stylesheet" href="_static/custom.css" type="text/css" />
app.add_css_file('print.css', media='print')
# => <link rel="stylesheet" href="_static/print.css"
# type="text/css" media="print" />
app.add_latex_package('mypackage')
# => \usepackage{mypackage}
app.add_latex_package('mypackage', 'foo,bar')
# => \usepackage[foo,bar]{mypackage}
246 https://mdn.io/Web/CSS/Alternative_style_sheets
Sphinx.add_html_theme(name, theme_path)
Register a HTML Theme.
The name is a name of theme, and path is a full path to the theme (refs: Distribute your theme as a
Python package).
New in version 1.6.
Sphinx.add_html_math_renderer(name, inline_renderers, block_renderers)
Register a math renderer for HTML.
The name is a name of math renderer. Both inline_renderers and block_renderers are used as visitor
functions for the HTML writer: the former for inline math node (nodes.math), the latter for block
math node (nodes.math_block). Regarding visitor functions, see add_node() for details.
New in version 1.8.
Sphinx.add_message_catalog(catalog, locale_dir)
Register a message catalog.
The catalog is a name of catalog, and locale_dir is a base path of message catalog. For more details,
see sphinx.locale.get_translation().
New in version 1.8.
Sphinx.is_parallel_allowed(typ)
Check parallel processing is allowed or not.
typ is a type of processing; 'read' or 'write'.
exception sphinx.application.ExtensionError
All these methods raise this exception if something went wrong with the extension API.
Emitting events
class sphinx.application.Sphinx
emit(event, *arguments)
Emit event and pass arguments to the callback functions.
Return the return values of all callbacks as a list. Do not emit core Sphinx events in extensions!
emit_firstresult(event, *arguments)
Emit event and pass arguments to the callback functions.
Return the result of the first callback that doesn’t return None.
New in version 0.5.
Sphinx.outdir
Directory for storing built document.
These events are known to the core. The arguments shown are given to the registered event handlers.
Use Sphinx.connect() in an extension’s setup function (note that conf.py can also have a setup
function) to connect handlers to the events. Example:
def setup(app):
app.connect('source-read', source_read_handler)
builder-inited(app)
Emitted when the builder object has been created. It is available as app.builder.
config-inited(app, config)
Emitted when the config object has been initialized.
New in version 1.8.
env-get-outdated(app, env, added, changed, removed)
Emitted when the environment determines which source files have changed and should be re-read.
added, changed and removed are sets of docnames that the environment has determined. You can
return a list of docnames to re-read in addition to these.
New in version 1.1.
env-purge-doc(app, env, docname)
Emitted when all traces of a source file should be cleaned from the environment, that is, if the source
file is removed or before it is freshly read. This is for extensions that keep their own caches in
attributes of the environment.
For example, there is a cache of all modules on the environment. When a source file has been
changed, the cache’s entries for the file are cleared, since the module declarations could have been
removed from the file.
New in version 0.5.
env-before-read-docs(app, env, docnames)
Emitted after the environment has determined the list of all added and changed files and just before
it reads them. It allows extension authors to reorder the list of docnames (inplace) before processing,
or add more docnames that Sphinx did not consider changed (but never add any docnames that are
not in env.found_docs).
You can also remove document names; do this with caution since it will make Sphinx treat changed
files as unchanged.
New in version 1.3.
source-read(app, docname, source)
Emitted when a source file has been read. The source argument is a list whose single element is
the contents of the source file. You can process the contents and replace this item to implement
source-level transformations.
For example, if you want to use $ signs to delimit inline math, like in LaTeX, you can use a regular
expression to replace $...$ by :math:`...`.
New in version 0.5.
doctree-read(app, doctree)
Emitted when a doctree has been parsed and read by the environment, and is about to be pickled.
The doctree can be modified in-place.
missing-reference(app, env, node, contnode)
Emitted when a cross-reference to a Python module or object cannot be resolved. If the event handler
can resolve the reference, it should return a new docutils node to be inserted in the document tree
in place of the node node. Usually this node is a reference node containing contnode as a child.
Parameters
• env – The build environment (app.builder.env).
• node – The pending_xref node to be resolved. Its attributes reftype,
reftarget, modname and classname attributes determine the type and target
of the reference.
• contnode – The node that carries the text and formatting inside the future refer-
ence and should be a child of the returned reference node.
New in version 0.5.
doctree-resolved(app, doctree, docname)
Emitted when a doctree has been “resolved” by the environment, that is, all references have been
resolved and TOCs have been inserted. The doctree can be modified in place.
Here is the place to replace custom nodes that don’t have visitor methods in the writers, so that they
don’t cause errors when the writers encounter them.
env-merge-info(app, env, docnames, other)
This event is only emitted when parallel reading of documents is enabled. It is emitted once for
every subprocess that has read some documents.
You must handle this event in an extension that stores data in the environment in a custom location.
Otherwise the environment in the main process will not be aware of the information stored in the
subprocess.
other is the environment object from the subprocess, env is the environment from the main process.
docnames is a set of document names that have been read in the subprocess.
For a sample of how to deal with this event, look at the standard sphinx.ext.todo extension. The
implementation is often similar to that of env-purge-doc, only that information is not removed,
but added to the main environment from the other environment.
New in version 1.3.
env-updated(app, env)
Emitted when the update() method of the build environment has completed, that is, the environ-
ment and all doctrees are now up-to-date.
You can return an iterable of docnames from the handler. These documents will then be considered
updated, and will be (re-)written during the writing phase.
New in version 0.5.
Changed in version 1.3: The handlers’ return value is now used.
env-check-consistency(app, env)
Emitted when Consistency checks phase. You can check consistency of metadata for whole of docu-
ments.
New in version 1.6: As a experimental event
html-collect-pages(app)
Emitted when the HTML builder is starting to write non-document pages. You can add
pages to write by returning an iterable from this event consisting of (pagename, context,
templatename).
New in version 1.0.
html-page-context(app, pagename, templatename, context, doctree)
Emitted when the HTML builder has created a context dictionary to render a template with – this
can be used to add custom elements to the context.
The pagename argument is the canonical name of the page being rendered, that is, without .html
suffix and using slashes as path separators. The templatename is the name of the template to render,
this will be 'page.html' for all pages from reST documents.
The context argument is a dictionary of values that are given to the template engine to render the
page and can be modified to include custom values. Keys must be strings.
The doctree argument will be a doctree when the page is created from a reST documents; it will be
None when the page is created from an HTML template alone.
You can return a string from the handler, it will then replace 'page.html' as the HTML template
for this page.
New in version 0.4.
Changed in version 1.3: The return value can now specify a template name.
build-finished(app, exception)
Emitted when a build has finished, before Sphinx exits, usually used for cleanup. This event is
emitted even when the build process raised an exception, given as the exception argument. The
exception is reraised in the application after the event handlers have run. If the build process raised
no exception, exception will be None. This allows to customize cleanup actions depending on the
exception status.
New in version 0.5.
class sphinx.application.TemplateBridge
This class defines the interface for a “template bridge”, that is, a class that renders templates given a
template name and a context.
init(builder, theme=None, dirs=None)
Called by the builder to initialize the template system.
builder is the builder object; you’ll probably want to look at the value of builder.config.
templates_path.
theme is a sphinx.theming.Theme object or None; in the latter case, dirs can be list of fixed
directories to look for templates.
newest_template_mtime()
Called by the builder to determine if output files are outdated because of template changes.
Return the mtime of the newest template file that was changed. The default implementation
returns 0.
render(template, context)
Called by the builder to render a template given as a filename with a specified context (a Python
dictionary).
render_string(template, context)
Called by the builder to render a template given as a string with a specified context (a Python
dictionary).
Exceptions
exception sphinx.errors.SphinxError
Base class for Sphinx errors.
This is the base class for “nice” exceptions. When such an exception is raised, Sphinx will abort the
build and present the exception category and message to the user.
Extensions are encouraged to derive from this exception for their custom errors.
Exceptions not derived from SphinxError are treated as unexpected and shown to the user with a
part of the traceback (and the full traceback saved in a temporary file).
category
Description of the exception “category”, used in converting the exception to a string (“category:
message”). Should be set accordingly in subclasses.
exception sphinx.errors.ConfigError
Configuration error.
exception sphinx.errors.ExtensionError(message, orig_exc=None)
Extension error.
exception sphinx.errors.ThemeError
Theme error.
exception sphinx.errors.VersionRequirementError
Incompatible Sphinx version error.
discover(exclude_paths=[])
Find all document files in the source directory and put them in docnames.
doc2path(docname, basedir=True)
Return the filename for the document name.
If basedir is True, return as an absolute path. Else, return as a relative path to the source
directory.
path2doc(filename)
Return the docname for the filename if the file is document.
filename should be absolute or relative to the source directory.
restore(other)
Take over a result of last build.
docnames = None
The name of documents belongs to this project.
source_suffix = None
source_suffix. Same as source_suffix.
srcdir = None
Source directory.
class sphinx.environment.BuildEnvironment
Attributes
app
Reference to the Sphinx (application) object.
config
Reference to the Config object.
project
Target project. See Project.
srcdir
Source directory.
doctreedir
Directory for storing pickled doctrees.
events
An EventManager object.
found_docs
A set of all existing docnames.
metadata
Dictionary mapping docnames to “metadata” (see File-wide metadata).
titles
Dictionary mapping docnames to the docutils node for their main title.
docname
Returns the docname of the document currently being parsed.
Utility methods
class sphinx.builders.Builder
This is the base class for all builders.
These attributes should be set on builder classes:
name = ''
The builder’s name, for the -b command line option.
format = ''
The builder’s output format, or ‘’ if no document output is produced.
epilog = ''
The message emitted upon successful build completion. This can be a printf-style template
string with the following keys: outdir, project
supported_image_types = []
The list of MIME types of image formats supported by the builder. Image files are searched in
the order in which they appear here.
supported_remote_images = False
The builder supports remote images or not.
supported_data_uri_images = False
The builder supports data URIs or not.
default_translator_class = None
default translator class for the builder. This can be overridden by app.set_translator().
These methods are predefined and will be called from the application:
class sphinx.environment.collectors.EnvironmentCollector
An EnvironmentCollector is a specific data collector from each document.
It gathers data and stores BuildEnvironment as a database. Examples of specific data would be
images, download files, section titles, metadatas, index entries and toctrees, etc.
clear_doc(app, env, docname)
Remove specified data of a document.
This method is called on the removal of the document.
This section describes the API for adding ReST markup elements (roles and directives).
Roles
Directives
ViewLists
Many directives will contain more markup that must be parsed. To do this, use one of the following APIs
from the Directive.run() method:
• self.state.nested_parse
• sphinx.util.nodes.nested_parse_with_titles() – this allows titles in the parsed content.
Both APIs parse the content into a given node. They are used like this:
node = docutils.nodes.paragraph()
# either
nested_parse_with_titles(self.state, self.result, node)
# or
self.state.nested_parse(self.result, 0, node)
If you don’t need the wrapping node, you can use any concrete node type and return node.children
from the Directive.
See also:
Creating directives247 HOWTO of the Docutils documentation
class sphinx.domains.Domain(env)
A Domain is meant to be a group of “object” description directives for objects of a similar nature,
and corresponding roles to create references to them. Examples would be Python modules, classes,
functions etc., elements of a templating language, Sphinx roles and directives, etc.
Each domain has a separate storage for information about existing objects and how to reference
them in self.data, which must be a dictionary. It also must implement several functions that expose
the object information in a uniform way to parts of Sphinx that allow the user to reference or search
for objects in a domain-agnostic way.
About self.data: since all object and cross-referencing information is stored on a BuildEnvironment
instance, the domain.data object is also stored in the env.domaindata dict under the key domain.name.
Before the build process starts, every active domain is instantiated and given the environment object;
the domaindata dict must then either be nonexistent or a dictionary whose ‘version’ key is equal to the
domain class’ data_version attribute. Otherwise, OSError is raised and the pickled environment
is discarded.
add_object_type(name, objtype)
Add an object type.
check_consistency()
Do consistency checks (experimental).
clear_doc(docname)
Remove traces of a document in the domain-specific inventories.
directive(name)
Return a directive adapter class that always gives the registered directive its full name (‘do-
main:name’) as self.name.
247 http://docutils.sourceforge.net/docs/howto/rst-directives.html
get_enumerable_node_type(node)
Get type of enumerable nodes (experimental).
get_full_qualified_name(node)
Return full qualified name for given node.
get_objects()
Return an iterable of “object descriptions”.
Object descriptions are tuples with six items:
name Fully qualified name.
dispname Name to display when searching/linking.
type Object type, a key in self.object_types.
docname The document where it is to be found.
anchor The anchor name for the object.
priority How “important” the object is (determines placement in search results). One of:
1 Default priority (placed before full-text matches).
0 Object is important (placed before default-priority objects).
2 Object is unimportant (placed after full-text matches).
-1 Object should not show up in search at all.
get_type_name(type, primary=False)
Return full name for given ObjType.
merge_domaindata(docnames, otherdata)
Merge in data regarding docnames from a different domaindata inventory (coming from a sub-
process in parallel builds).
process_doc(env, docname, document)
Process a document after it is read by the environment.
process_field_xref(pnode)
Process a pending xref created in a doc field. For example, attach information about the current
scope.
resolve_any_xref(env, fromdocname, builder, target, node, contnode)
Resolve the pending_xref node with the given target.
The reference comes from an “any” or similar role, which means that we don’t know the type.
Otherwise, the arguments are the same as for resolve_xref().
The method must return a list (potentially empty) of tuples ('domain:role', newnode),
where 'domain:role' is the name of a role that could have created the same reference, e.g.
'py:func'. newnode is what resolve_xref() would return.
New in version 1.3.
resolve_xref(env, fromdocname, builder, typ, target, node, contnode)
Resolve the pending_xref node with the given typ and target.
This method should return a new node, to replace the xref node, containing the contnode which
is the markup content of the cross-reference.
If no resolution can be found, None can be returned; the xref node will then given to the
missing-reference event, and if that yields no resolution, replaced by contnode.
The method can also raise sphinx.environment.NoUri to suppress the
missing-reference event being emitted.
role(name)
Return a role adapter function that always gives the registered role its full name (‘do-
main:name’) as the first argument.
dangling_warnings = {}
role name -> a warning message if reference is missing
data = None
data value
data_version = 0
data version, bump this when the format of self.data changes
directives = {}
directive name -> directive class
enumerable_nodes = {}
node_class -> (enum_node_type, title_getter)
indices = []
a list of Index subclasses
initial_data = {}
data value for a fresh environment
label = ''
domain label: longer, more descriptive (used in messages)
name = ''
domain name: should be short, but unique
object_types = {}
type (usually directive) name -> ObjType instance
roles = {}
role name -> role callable
class sphinx.domains.ObjType(lname, *roles, **attrs)
An ObjType is the description for a type of object that a domain can document. In the object_types
attribute of Domain subclasses, object type names are mapped to instances of this class.
Constructor arguments:
• lname: localized name of the type (do not include domain name)
• roles: all the roles that can refer to an object of this type
• attrs: object attributes – currently only “searchprio” is known, which defines the object’s priority
in the full-text search index, see Domain.get_objects().
class sphinx.domains.Index(domain)
An Index is the description for a domain-specific index. To add an index to a domain, subclass
Index, overriding the three name attributes:
• name is an identifier used for generating file names.
• localname is the section title for the index.
• shortname is a short name for the index, for use in the relation bar in HTML output. Can be
empty to disable entries in the relation bar.
and providing a generate() method. Then, add the index class to your domain’s indices list.
Extensions can add indices to existing domains using add_index_to_domain().
generate(docnames=None)
Get entries for the index.
You should indicate file types your parser supports. This will allow users to configure their settings
appropriately.
class sphinx.parsers.Parser
A base class of source parsers. The additional parsers should inherit this class instead of docutils.
parsers.Parser. Compared with docutils.parsers.Parser, this class improves accessibility
to Sphinx APIs.
248 http://docutils.sourceforge.net/docs/dev/hacking.html#parsing-the-document
Special nodes
sphinx.util.logging.getLogger(name)
Get logger wrapped by sphinx.util.logging.SphinxLoggerAdapter.
Sphinx logger always uses sphinx.* namespace to be independent from settings of root logger. It
ensures logging is consistent even if a third-party extension or imported application resets logger
settings.
Example usage:
class sphinx.util.logging.SphinxLoggerAdapter(logging.LoggerAdapter)
LoggerAdapter allowing type and subtype keywords.
error(msg, *args, **kwargs)
critical(msg, *args, **kwargs)
warning(msg, *args, **kwargs)
Logs a message on this logger with the specified level. Basically, the arguments are as with
python’s logging module.
In addition, Sphinx logger supports following keyword arguments:
type, *subtype* Categories of warning logs. It is used to suppress warnings by
suppress_warnings setting.
location Where the warning happened. It is used to include the path and line number in each
log. It allows docname, tuple of docname and line number and nodes:
logger = sphinx.util.logging.getLogger(__name__)
logger.warning('Warning happened!', location='index')
logger.warning('Warning happened!', location=('chapter1/index',
,→10))
color The color of logs. By default, error level logs are colored as "darkred", critical level
ones is not colored, and warning level ones are colored as "red".
log(level, msg, *args, **kwargs)
info(msg, *args, **kwargs)
verbose(msg, *args, **kwargs)
debug(msg, *args, **kwargs)
Logs a message to this logger with the specified level. Basically, the arguments are as with
python’s logging module.
In addition, Sphinx logger supports following keyword arguments:
nonl If true, the logger does not fold lines at the end of the log message. The default is False.
location Where the message emitted. For more detail, see SphinxLoggerAdapter.
warning().
color The color of logs. By default, info and verbose level logs are not colored, and debug level
ones are colored as "darkgray".
sphinx.util.logging.pending_logging()
Contextmanager to pend logging all logs temporary.
For example:
sphinx.util.logging.pending_warnings()
Contextmanager to pend logging warnings temporary.
Similar to pending_logging().
sphinx.util.logging.prefixed_warnings()
Prepend prefix to all records for a while.
For example:
sphinx.locale.get_translation(catalog, namespace=’general’)
Get a translation function based on the catalog and namespace.
The extension can use this API to translate the messages on the extension:
import os
from sphinx.locale import get_translation
def setup(app):
package_dir = path.abspath(path.dirname(__file__))
locale_dir = os.path.join(package_dir, 'locales')
app.add_message_catalog(MESSAGE_CATALOG_NAME, locale_dir)
Listing 1: src/__init__.py
from sphinx.locale import get_translation
MESSAGE_CATALOG_NAME = 'myextension'
_ = get_translation(MESSAGE_CATALOG_NAME)
Listing 2: src/__init__.py
def setup(app):
package_dir = path.abspath(path.dirname(__file__))
locale_dir = os.path.join(package_dir, 'locales')
app.add_message_catalog(MESSAGE_CATALOG_NAME, locale_dir)
1. Generate message catalog template *.pot file, usually in locale/ source directory, for example
via Babel249 :
2. Create message catalogs (*.po) for each language which your extension will provide localization,
for example via Babel250 :
5. Ensure that message catalog files are distributed when your package will be installed, by adding
equivalent line in your extension MANIFEST.in:
Listing 3: MANIFEST.in
recursive-include src *.pot *.po *.mo
When the messages on your extension has been changed, you need to also update message catalog tem-
plate and message catalogs, for example via Babel252 :
17.5.12 Utilities
These base classes are useful to allow your extensions to obtain Sphinx components (e.g. Config,
BuildEnvironment and so on) easily.
Note: The subclasses of them might not work with bare docutils because they are strongly coupled with
Sphinx.
249 http://babel.pocoo.org/
250 http://babel.pocoo.org/
251 http://babel.pocoo.org/
252 http://babel.pocoo.org/
Note: The subclasses of this class might not work with docutils. This class is strongly coupled with
Sphinx.
Note: The subclasses of this class might not work with docutils. This class is strongly coupled with
Sphinx.
property config
Reference to the Config object.
content = None
A list of strings, the directive content for customization
property env
Reference to the BuildEnvironment object.
inliner = None
The docutils.parsers.rst.states.Inliner object.
lineno = None
The line number where the interpreted text begins.
name = None
The role name actually used in the document.
options = None
A dictionary of directive options for customization
rawtext = None
A string containing the entire interpreted text input.
text = None
The interpreted text content.
class sphinx.util.docutils.ReferenceRole
A base class for reference roles.
The reference roles can accpet link title <target> style as a text for the role. The parsed result;
link title and target will be stored to self.title and self.target.
has_explicit_title = None
A boolean indicates the role has explicit title or not.
target = None
The link target for the interpreted text.
title = None
The link title for the interpreted text.
class sphinx.transforms.post_transforms.images.ImageConverter(*args, **kwargs)
A base class for image converters.
An image converter is kind of Docutils transform module. It is used to convert image files which
does not supported by builder to appropriate format for that builder.
For example, LaTeX builder supports PDF, PNG and JPEG as image formats. However it does
not support SVG images. For such case, to use image converters allows to embed these unsupported
images into the document. One of image converters; sphinx.ext.imgconverter can convert a SVG image
to PNG format using Imagemagick internally.
There are three steps to make your custom image converter:
1. Make a subclass of ImageConverter class
2. Override conversion_rules, is_available() and convert()
3. Register your image converter to Sphinx using Sphinx.add_post_transform()
convert(_from, _to)
Convert a image file to expected format.
_from is a path for source image file, and _to is a path for destination file.
is_available()
Return the image converter is available or not.
conversion_rules = []
A conversion rules the image converter supports. It is represented as a list of pair of source
image format (mimetype) and destination one:
conversion_rules = [
('image/svg+xml', 'image/png'),
('image/gif', 'image/png'),
('application/pdf', 'image/png'),
]
Utility components
class sphinx.events.EventManager(app=None)
Event manager for Sphinx.
add(name)
Register a custom Sphinx event.
connect(name, callback)
Connect a handler to specific event.
disconnect(listener_id)
Disconnect a handler.
emit(name, *args)
Emit a Sphinx event.
emit_firstresult(name, *args)
Emit a Sphinx event and returns first result.
This returns the result of the first handler that doesn’t return None.
On developing Sphinx, we are always careful to the compatibility of our APIs. But, sometimes, the change
of interface are needed for some reasons. In such cases, we’ve marked them as deprecated. And they are
kept during the two major versions (for more details, please see Deprecation policy).
The following is a list of deprecated interfaces.
Note: On deprecating on public APIs (internal functions and classes), we also follow the policy as much
as possible.
253 https://pypi.org/project/sphinxcontrib-websupport/
EIGHTEEN
EXTENSION TUTORIALS
The objective of this tutorial is to create a very basic extension that adds a new directive. This directive
will output a paragraph containing “hello world”.
Only basic information is provided in this tutorial. For more information, refer to the other tutorials that
go into more details.
Warning: For this extension, you will need some basic understanding of docutils254 and Python.
18.1.1 Overview
18.1.2 Prerequisites
We will not be distributing this plugin via PyPI255 and will instead include it as part of an existing project.
This means you will need to use an existing project or create a new one using sphinx-quickstart.
We assume you are using separate source (source) and build (build) folders. Your extension file could
be in any folder of your project. In our case, let’s do the following:
1. Create an _ext folder in source
2. Create a new Python file in the _ext folder called helloworld.py
Here is an example of the folder structure you might obtain:
source
_ext
helloworld.py
_static
conf.py
(continues on next page)
254 http://docutils.sourceforge.net/
255 https://pypi.org/
265
Sphinx Documentation, Release 3.0.0+/0fb832baa
5 class HelloWorld(Directive):
6
7 def run(self):
8 paragraph_node = nodes.paragraph(text='Hello World!')
9 return [paragraph_node]
10
11
12 def setup(app):
13 app.add_directive("helloworld", HelloWorld)
14
15 return {
16 'version': '0.1',
17 'parallel_read_safe': True,
18 'parallel_write_safe': True,
19 }
Some essential things are happening in this example, and you will see them for all directives.
1 class HelloWorld(Directive):
2
3 def run(self):
4 paragraph_node = nodes.paragraph(text='Hello World!')
5 return [paragraph_node]
This class extends the docutils256 ’ Directive class. All extensions that create directives should extend
this class.
See also:
The docutils documentation on creating directives257
This class contains a run method. This method is a requirement and it is part of every directive. It
contains the main logic of the directive and it returns a list of docutils nodes to be processed by Sphinx.
256 http://docutils.sourceforge.net/
257 http://docutils.sourceforge.net/docs/howto/rst-directives.html
These nodes are docutils’ way of representing the content of a document. There are many types of nodes
available: text, paragraph, reference, table, etc.
See also:
The docutils documentation on nodes258
The nodes.paragraph class creates a new paragraph node. A paragraph node typically contains some
text that we can set during instantiation using the text parameter.
This function is a requirement. We use it to plug our new directive into Sphinx.
1 def setup(app):
2 app.add_directive("helloworld", HelloWorld)
3
4 return {
5 'version': '0.1',
6 'parallel_read_safe': True,
7 'parallel_write_safe': True,
8 }
The simplest thing you can do it call the add_directive() method, which is what we’ve done here. For
this particular call, the first argument is the name of the directive itself as used in a reST file. In this case,
we would use helloworld. For example:
.. helloworld::
We also return the extension metadata that indicates the version of our extension, along with the fact that it
is safe to use the extension for both parallel reading and writing.
The extension has to be declared in your conf.py file to make Sphinx aware of it. There are two steps
necessary here:
1. Add the _ext directory to the Python path259 using sys.path.append. This should be placed at
the top of the file.
2. Update or create the extensions list and add the extension file name to the list
For example:
import os
import sys
sys.path.append(os.path.abspath("./_ext"))
extensions = ['helloworld']
258 http://docutils.sourceforge.net/docs/ref/doctree.html
259 https://docs.python.org/3/using/cmdline.html#envvar-PYTHONPATH
Tip: We’re not distributing this extension as a Python package260 , we need to modify the Python path261
so Sphinx can find our extension. This is why we need the call to sys.path.append.
.. helloworld::
Hello World!
This is the very basic principle of an extension that creates a new directive.
For a more advanced example, refer to Developing a “TODO” extension.
The objective of this tutorial is to create a more comprehensive extension than that created in Developing
a “Hello world” extension. Whereas that guide just covered writing a custom directive, this guide adds
multiple directives, along with custom nodes, additional config values and custom event handlers. To this
end, we will cover a todo extension that adds capabilities to include todo entries in the documentation,
and to collect these in a central place. This is similar the sphinxext.todo extension distributed with
Sphinx.
18.2.1 Overview
Note: To understand the design of this extension, refer to Important objects and Build Phases.
• New document tree nodes to represent these directives, conventionally also called todo and
todolist. We wouldn’t need new nodes if the new directives only produced some content repre-
sentable by existing nodes.
• A new config value todo_include_todos (config value names should start with the extension
name, in order to stay unique) that controls whether todo entries make it into the output.
• New event handlers: one for the doctree-resolved event, to replace the todo and todolist nodes,
and one for env-purge-doc (the reason for that will be covered later).
18.2.2 Prerequisites
As with Developing a “Hello world” extension, we will not be distributing this plugin via PyPI so once again
we need a Sphinx project to call this from. You can use an existing project or create a new one using
sphinx-quickstart.
We assume you are using separate source (source) and build (build) folders. Your extension file could
be in any folder of your project. In our case, let’s do the following:
1. Create an _ext folder in source
2. Create a new Python file in the _ext folder called todo.py
Here is an example of the folder structure you might obtain:
source
_ext
todo.py
_static
conf.py
somefolder
index.rst
somefile.rst
someotherfile.rst
Open todo.py and paste the following code in it, all of which we will explain in detail shortly:
11
15
19
23
24 class TodolistDirective(Directive):
25
26 def run(self):
27 return [todolist('')]
28
29
30 class TodoDirective(SphinxDirective):
31
35 def run(self):
36 targetid = 'todo-%d' % self.env.new_serialno('todo')
37 targetnode = nodes.target('', '', ids=[targetid])
38
39 todo_node = todo('\n'.join(self.content))
40 todo_node += nodes.title(_('Todo'), _('Todo'))
41 self.state.nested_parse(self.content, self.content_offset, todo_node)
42
46 self.env.todo_all_todos.append({
47 'docname': self.env.docname,
48 'lineno': self.lineno,
49 'todo': todo_node.deepcopy(),
50 'target': targetnode,
51 })
52
55
63
78 content = []
79
85 (filename, todo_info['lineno']))
86 para += nodes.Text(description, description)
87
88 # Create a reference
89 newnode = nodes.reference('', '')
90 innernode = nodes.emphasis(_('here'), _('here'))
91 newnode['refdocname'] = todo_info['docname']
92 newnode['refuri'] = app.builder.get_relative_uri(
93 fromdocname, todo_info['docname'])
94 newnode['refuri'] += '#' + todo_info['target']['refid']
95 newnode.append(innernode)
96 para += newnode
97 para += nodes.Text('.)', '.)')
98
103 node.replace_self(content)
104
105
109 app.add_node(todolist)
110 app.add_node(todo,
111 html=(visit_todo_node, depart_todo_node),
112 latex=(visit_todo_node, depart_todo_node),
113 text=(visit_todo_node, depart_todo_node))
114
This is far more extensive extension than the one detailed in Developing a “Hello world” extension, however,
we will will look at each piece step-by-step to explain what’s happening.
12
Node classes usually don’t have to do anything except inherit from the standard docutils classes defined in
docutils.nodes. todo inherits from Admonition because it should be handled like a note or warning,
todolist is just a “general” node.
Note: Many extensions will not have to create their own node classes and work fine with the nodes
already provided by docutils262 and Sphinx.
1 class TodolistDirective(Directive):
2
3 def run(self):
4 return [todolist('')]
262 http://docutils.sourceforge.net/docs/ref/doctree.html
263 http://docutils.sourceforge.net/docs/ref/rst/directives.html
It’s very simple, creating and returning an instance of our todolist node class. The
TodolistDirective directive itself has neither content nor arguments that need to be handled. That
brings us to the TodoDirective directive:
1 class TodoDirective(SphinxDirective):
2
6 def run(self):
7 targetid = 'todo-%d' % self.env.new_serialno('todo')
8 targetnode = nodes.target('', '', ids=[targetid])
9
10 todo_node = todo('\n'.join(self.content))
11 todo_node += nodes.title(_('Todo'), _('Todo'))
12 self.state.nested_parse(self.content, self.content_offset, todo_node)
13
17 self.env.todo_all_todos.append({
18 'docname': self.env.docname,
19 'lineno': self.lineno,
20 'todo': todo_node.deepcopy(),
21 'target': targetnode,
22 })
23
Several important things are covered here. First, as you can see, we’re now subclassing the
SphinxDirective helper class instead of the usual Directive class. This gives us access to the build
environment instance using the self.env property. Without this, we’d have to use the rather convoluted
self.state.document.settings.env. Then, to act as a link target (from TodolistDirective),
the TodoDirective directive needs to return a target node in addition to the todo node. The target ID
(in HTML, this will be the anchor name) is generated by using env.new_serialno which returns a new
unique integer on each call and therefore leads to unique target names. The target node is instantiated
without any text (the first two arguments).
On creating admonition node, the content body of the directive are parsed using self.state.
nested_parse. The first argument gives the content body, and the second one gives content offset.
The third argument gives the parent node of parsed result, in our case the todo node. Following this,
the todo node is added to the environment. This is needed to be able to create a list of all todo entries
throughout the documentation, in the place where the author puts a todolist directive. For this case,
the environment attribute todo_all_todos is used (again, the name should be unique, so it is prefixed
by the extension name). It does not exist when a new environment is created, so the directive must check
and create it if necessary. Various information about the todo entry’s location are stored along with a copy
of the node.
In the last line, the nodes that should be put into the doctree are returned: the target node and the
admonition node.
The node structure that the directive returns looks like this:
+--------------------+
| target node |
(continues on next page)
Event handlers are one of Sphinx’s most powerful features, providing a way to do hook into any part of
the documentation process. There are many events provided by Sphinx itself, as detailed in the API guide,
and we’re going to use a subset of them here.
Let’s look at the event handlers used in the above example. First, the one for the env-purge-doc event:
Since we store information from source files in the environment, which is persistent, it may become out
of date when the source file changes. Therefore, before each source file is read, the environment’s records
of it are cleared, and the env-purge-doc event gives extensions a chance to do the same. Here we clear
out all todos whose docname matches the given one from the todo_all_todos list. If there are todos
left in the document, they will be added again during parsing.
The other handler belongs to the doctree-resolved event:
15 content = []
16
25 # Create a reference
26 newnode = nodes.reference('', '')
27 innernode = nodes.emphasis(_('here'), _('here'))
28 newnode['refdocname'] = todo_info['docname']
29 newnode['refuri'] = app.builder.get_relative_uri(
30 fromdocname, todo_info['docname'])
31 newnode['refuri'] += '#' + todo_info['target']['refid']
32 newnode.append(innernode)
33 para += newnode
34 para += nodes.Text('.)', '.)')
35
40 node.replace_self(content)
The doctree-resolved event is emitted at the end of phase 3 (resolving) and allows custom resolving to
be done. The handler we have written for this event is a bit more involved. If the todo_include_todos
config value (which we’ll describe shortly) is false, all todo and todolist nodes are removed from the
documents. If not, todo nodes just stay where and how they are. todolist nodes are replaced by a
list of todo entries, complete with backlinks to the location where they come from. The list items are
composed of the nodes from the todo entry and docutils nodes created on the fly: a paragraph for each
entry, containing text that gives the location, and a link (reference node containing an italic node) with
the backreference. The reference URI is built by sphinx.builders.Builder.get_relative_uri`()
which creates a suitable URI depending on the used builder, and appending the todo node’s (the target’s)
ID as the anchor name.
As noted previously, the setup function is a requirement and is used to plug directives into Sphinx.
However, we also use it to hook up the other parts of our extension. Let’s look at our setup function:
1 def setup(app):
2 app.add_config_value('todo_include_todos', False, 'html')
3
4 app.add_node(todolist)
5 app.add_node(todo,
6 html=(visit_todo_node, depart_todo_node),
7 latex=(visit_todo_node, depart_todo_node),
8 text=(visit_todo_node, depart_todo_node))
9
10 app.add_directive('todo', TodoDirective)
11 app.add_directive('todolist', TodolistDirective)
(continues on next page)
15 return {
16 'version': '0.1',
17 'parallel_read_safe': True,
18 'parallel_write_safe': True,
19 }
The calls in this function refer to the classes and functions we added earlier. What the individual calls do
is the following:
• add_config_value() lets Sphinx know that it should recognize the new config value
todo_include_todos, whose default value should be False (this also tells Sphinx that it is a
boolean value).
If the third argument was 'html', HTML documents would be full rebuild if the config value
changed its value. This is needed for config values that influence reading (build phase 1 (reading)).
• add_node() adds a new node class to the build system. It also can specify visitor functions for each
supported output format. These visitor functions are needed when the new nodes stay until phase 4
(writing). Since the todolist node is always replaced in phase 3 (resolving), it doesn’t need any.
• add_directive() adds a new directive, given by name and class.
• Finally, connect() adds an event handler to the event whose name is given by the first argument.
The event handler function is called with several arguments which are documented with the event.
With this, our extension is complete.
As before, we need to enable the extension by declaring it in our conf.py file. There are two steps
necessary here:
1. Add the _ext directory to the Python path264 using sys.path.append. This should be placed at
the top of the file.
2. Update or create the extensions list and add the extension file name to the list
In addition, we may wish to set the todo_include_todos config value. As noted above, this defaults to
False but we can set it explicitly.
For example:
import os
import sys
sys.path.append(os.path.abspath("./_ext"))
extensions = ['todo']
todo_include_todos = False
You can now use the extension throughout your project. For example:
264 https://docs.python.org/3/using/cmdline.html#envvar-PYTHONPATH
Listing 1: index.rst
Hello, world
============
.. toctree::
somefile.rst
someotherfile.rst
.. todolist::
Listing 2: somefile.rst
foo
===
Listing 3: someotherfile.rst
bar
===
Because we have configured todo_include_todos to False, we won’t actually see anything rendered
for the todo and todolist directives. However, if we toggle this to true, we will see the output described
previously.
For more information, refer to the docutils265 documentation and Developing extensions for Sphinx.
The objective of this tutorial is to illustrate roles, directives and domains. Once complete, we will be able
to use this extension to describe a recipe and reference that recipe from elsewhere in our documentation.
Note: This tutorial is based on a guide first published on opensource.com266 and is provided here with
the original author’s permission.
265 http://docutils.sourceforge.net/docs/
266 https://opensource.com/article/18/11/building-custom-workflows-sphinx
18.3.1 Overview
18.3.2 Prerequisites
We need the same setup as in the previous extensions. This time, we will be putting out extension in a file
called recipe.py.
Here is an example of the folder structure you might obtain:
source
_ext
recipe.py
conf.py
index.rst
Open recipe.py and paste the following code in it, all of which we will explain in detail shortly:
12
13 class RecipeDirective(ObjectDescription):
14 """A custom directive that describes a recipe."""
15
16 has_content = True
17 required_arguments = 1
18 option_spec = {
19 'contains': directives.unchanged_required,
(continues on next page)
32 recipes = self.env.get_domain('recipe')
33 recipes.add_recipe(sig, ingredients)
34
35
36 class IngredientIndex(Index):
37 """A custom index that creates an ingredient matrix."""
38
39 name = 'ingredient'
40 localname = 'Ingredient Index'
41 shortname = 'Ingredient'
42
73 class RecipeIndex(Index):
74 """A custom index that creates an recipe matrix."""
75
76 name = 'recipe'
77 localname = 'Recipe Index'
78 shortname = 'Recipe'
79
87 # generate the expected output, shown below, from the above using the
88 # first letter of the recipe as a key to group thing
89 #
90 # name, subtype, docname, anchor, extra, qualifier, description
91 for name, dispname, typ, docname, anchor, _ in recipes:
92 content[dispname[0].lower()].append(
93 (dispname, 0, docname, anchor, docname, '', typ))
94
100
153
157 return {
158 'version': '0.1',
159 'parallel_read_safe': True,
160 'parallel_write_safe': True,
161 }
Let’s look at each piece of this extension step-by-step to explain what’s going on.
16 recipes = self.env.get_domain('recipe')
17 recipes.add_recipe(sig, ingredients)
18
19
20 class IngredientIndex(Index):
21 """A custom index that creates an ingredient matrix."""
Unlike Developing a “Hello world” extension and Developing a “TODO” extension, this directive doesn’t
derive from docutils.parsers.rst.Directive and doesn’t define a run method. Instead,
it derives from sphinx.directives.ObjectDescription and defines handle_signature and
add_target_and_index methods. This is because ObjectDescription is a special-purpose direc-
tive that’s intended for describing things like classes, functions, or, in our case, recipes. More specifically,
handle_signature implements parsing the signature of the directive and passes on the object’s name
and type to its superclass, while add_taget_and_index adds a target (to link to) and an entry to the
index for this node.
We also see that this directive defines has_content, required_arguments and option_spec. Unlike
the TodoDirective directive added in the previous tutorial, this directive takes a single argument, the
recipe name, and an option, contains, in addition to the nested reStructuredText in the body.
33
34 class RecipeIndex(Index):
35 """A custom index that creates an recipe matrix."""
36
37 name = 'recipe'
38 localname = 'Recipe Index'
39 shortname = 'Recipe'
40
48 # generate the expected output, shown below, from the above using the
49 # first letter of the recipe as a key to group thing
50 #
51 # name, subtype, docname, anchor, extra, qualifier, description
52 for name, dispname, typ, docname, anchor, _ in recipes:
53 content[dispname[0].lower()].append(
54 (dispname, 0, docname, anchor, docname, '', typ))
55
61
62 class RecipeDomain(Domain):
63
Both IngredientIndex and RecipeIndex are derived from Index. They implement custom logic to
generate a tuple of values that define the index. Note that RecipeIndex is a simple index that has only
one entry. Extending it to cover more object types is not yet part of the code.
Both indices use the method Index.generate() to do their work. This method combines the infor-
mation from our domain, sorts it, and returns it in a list structure that will be accepted by Sphinx. This
might look complicated but all it really is is a list of tuples like ('tomato', 'TomatoSoup', 'test',
'rec-TomatoSoup',...). Refer to the domain API guide for more information on this API.
The domain
A Sphinx domain is a specialized container that ties together roles, directives, and indices, among other
things. Let’s look at the domain we’re creating here.
1 roles = {
2 'ref': XRefRole()
3 }
4 directives = {
5 'recipe': RecipeDirective,
6 }
7 indices = {
8 RecipeIndex,
9 IngredientIndex
10 }
11 initial_data = {
12 'recipes': [], # object list
13 'recipe_ingredients': {}, # name -> object
14 }
15
19 def get_objects(self):
20 for obj in self.data['recipes']:
21 yield(obj)
22
29 if len(match) > 0:
30 todocname = match[0][0]
31 targ = match[0][1]
32
44 self.data['recipe_ingredients'][name] = ingredients
45 # name, dispname, type, docname, anchor, priority
46 self.data['recipes'].append(
(continues on next page)
49
50 def setup(app):
51 app.add_domain(RecipeDomain)
There are some interesting things to note about this recipe domain and domains in general. Firstly,
we actually register our directives, roles and indices here, via the directives, roles and indices
attributes, rather than via calls later on in setup. We can also note that we aren’t actually defining
a custom role and are instead reusing the sphinx.roles.XRefRole role and defining the sphinx.
domains.Domain.resolve_xref method. This method takes two arguments, typ and target, which
refer to the cross-reference type and its target name. We’ll use target to resolve our destination from
our domain’s recipes because we currently have only one type of node.
Moving on, we can see that we’ve defined initial_data. The values defined in initial_data will
be copied to env.domaindata[domain_name] as the initial data of the domain, and domain instances
can access it via self.data. We see that we have defined two items in initial_data: recipes and
recipe2ingredient. These contain a list of all objects defined (i.e. all recipes) and a hash that maps a
canonical ingredient name to the list of objects. The way we name objects is common across our extension
and is defined in the get_full_qualified_name method. For each object created, the canonical name
is recipe.<recipename>, where <recipename> is the name the documentation writer gives the object
(a recipe). This enables the extension to use different object types that share the same name. Having a
canonical name and central place for our objects is a huge advantage. Both our indices and our cross-
referencing code use this feature.
As always, the setup function is a requirement and is used to hook the various parts of our extension into
Sphinx. Let’s look at the setup function for this extension.
1 'version': '0.1',
2 'parallel_read_safe': True,
3 'parallel_write_safe': True,
4 }
This looks a little different to what we’re used to seeing. There are no calls to add_directive() or
even add_role(). Instead, we have a single call to add_domain() followed by some initialization of
the standard domain. This is because we had already registered our directives, roles and indexes as part of
the directive itself.
You can now use the extension throughout your project. For example:
Listing 4: index.rst
Joe's Recipes
=============
tomato-soup
Listing 5: tomato-soup.rst
The recipe contains `tomato` and `cilantro`.
.. recipe:recipe:: TomatoSoup
:contains: tomato cilantro salt pepper
The important things to note are the use of the :recipe:ref: role to cross-reference the recipe actually
defined elsewhere (using the :recipe:recipe: directive.
For more information, refer to the docutils267 documentation and Developing extensions for Sphinx.
267 http://docutils.sourceforge.net/docs/
NINETEEN
SPHINX FAQ
This is a list of Frequently Asked Questions about Sphinx. Feel free to suggest new entries!
19.1 How do I. . .
. . . create PDF files without LaTeX? rinohtype268 provides a PDF builder that can be used as a drop-in
replacement for the LaTeX builder.
. . . get section numbers? They are automatic in LaTeX output; for HTML, give a :numbered: option to
the toctree directive where you want to start numbering.
. . . customize the look of the built HTML files? Use themes, see HTML.
. . . add global substitutions or includes? Add them in the rst_prolog or rst_epilog config value.
. . . display the whole TOC tree in the sidebar? Use the toctree callable in a custom layout template,
probably in the sidebartoc block.
. . . write my own extension? See the Extension tutorials.
. . . convert from my existing docs using MoinMoin markup? The easiest way is to convert to xhtml,
then convert xhtml to reST269 . You’ll still need to mark up classes and such, but the headings and
code examples come through cleanly.
For many more extensions and other contributed stuff, see the sphinx-contrib270 repository.
Read the Docs Read the Docs271 is a documentation hosting service based around Sphinx. They will host
sphinx documentation, along with supporting a number of other features including version support,
PDF generation, and more. The Getting Started272 guide is a good place to start.
Epydoc There’s a third-party extension providing an api role273 which refers to Epydoc’s API docs for a
given identifier.
Doxygen Michael Jones is developing a reST/Sphinx bridge to doxygen called breathe274 .
268 https://github.com/brechtm/rinohtype
269 http://docutils.sourceforge.net/sandbox/xhtml2rest/xhtml2rest.py
270 https://bitbucket.org/birkenfeld/sphinx-contrib/
271 https://readthedocs.org
272 https://docs.readthedocs.io/en/stable/intro/getting-started-with-sphinx.html
273 https://git.savannah.gnu.org/cgit/kenozooid.git/tree/doc/extapi.py
274 https://github.com/michaeljones/breathe/tree/master
287
Sphinx Documentation, Release 3.0.0+/0fb832baa
SCons Glenn Hutchings has written a SCons build script to build Sphinx documentation; it is hosted
here: https://bitbucket.org/zondo/sphinx-scons
PyPI Jannis Leidel wrote a setuptools command275 that automatically uploads Sphinx documentation to
the PyPI package documentation area at https://pythonhosted.org/.
GitHub Pages Directories starting with underscores are ignored by default which breaks static files in
Sphinx. GitHub’s preprocessor can be disabled276 to support Sphinx HTML output properly.
MediaWiki See https://bitbucket.org/kevindunn/sphinx-wiki/wiki/Home, a project by Kevin Dunn.
Google Analytics You can use a custom layout.html template, like this:
{% extends "!layout.html" %}
{% block footer %}
{{ super() }}
<div class="footer">This page uses <a href="https://analytics.google.com/
,→">
ga.setAttribute('async', 'true');
document.documentElement.firstChild.appendChild(ga);
})();
</script>
</div>
{% endblock %}
Google Search To replace Sphinx’s built-in search function with Google Search, proceed as follows:
1. Go to https://cse.google.com/cse/all to create the Google Search code snippet.
2. Copy the code snippet and paste it into _templates/searchbox.html in your Sphinx
project:
<div>
<h3>{{ _('Quick search') }}</h3>
<script>
(function() {
var cx = '......';
(continues on next page)
275 https://pypi.org/project/Sphinx-PyPI-upload/
276 https://github.com/blog/572-bypassing-jekyll-on-github-pages
The following list gives some hints for the creation of epub files:
• Split the text into several files. The longer the individual HTML files are, the longer it takes the
ebook reader to render them. In extreme cases, the rendering can take up to one minute.
• Try to minimize the markup. This also pays in rendering time.
• For some readers you can use embedded or external fonts using the CSS @font-face directive.
This is extremely useful for code listings which are often cut at the right margin. The default Courier
font (or variant) is quite wide and you can only display up to 60 characters on a line. If you replace
it with a narrower font, you can get more characters on a line. You may even use FontForge277 and
create narrow variants of some free font. In my case I get up to 70 characters on a line.
You may have to experiment a little until you get reasonable results.
• Test the created epubs. You can use several alternatives. The ones I am aware of are Epubcheck278 ,
Calibre279 , FBreader280 (although it does not render the CSS), and Bookworm281 . For Bookworm,
you can download the source from https://code.google.com/archive/p/threepress and run your
own local server.
• Large floating divs are not displayed properly. If they cover more than one page, the div is only
shown on the first page. In that case you can copy the epub.css from the sphinx/themes/epub/
static/ directory to your local _static/ directory and remove the float settings.
• Files that are inserted outside of the toctree directive must be manually included. This some-
times applies to appendixes, e.g. the glossary or the indices. You can add them with the
epub_post_files option.
• The handling of the epub cover page differs from the reStructuredText procedure which automat-
ically resolves image paths and puts the images into the _images directory. For the epub cover
page put the image in the html_static_path directory and reference it with its full path in the
epub_cover config option.
• kindlegen282 command can convert from epub3 resulting file to .mobi file for Kindle. You can get
yourdoc.mobi under _build/epub after the following command:
277 https://fontforge.github.io/
278 https://github.com/IDPF/epubcheck
279 https://calibre-ebook.com/
280 https://fbreader.org/
281 https://www.oreilly.com/bookworm/index.html
282 https://www.amazon.com/gp/feature.html?docId=1000765211
$ make epub
$ kindlegen _build/epub/yourdoc.epub
The kindlegen command doesn’t accept documents that have section titles surrounding toctree
directive:
Section Title
=============
.. toctree::
subdocument
kindlegen assumes all documents order in line, but the resulting document has complicated order
for kindlegen:
There are two main programs for reading Info files, info and GNU Emacs. The info program has less
features but is available in most Unix environments and can be quickly accessed from the terminal. Emacs
provides better font and color display and supports extensive customization (of course).
One noticeable problem you may encounter with the generated Info files is how references are displayed.
If you read the source of an Info file, a reference to this section would look like:
In the stand-alone reader, info, references are displayed just as they appear in the source. Emacs, on the
other-hand, will by default replace *note: with see and hide the target-id. For example:
Displaying Links
The exact behavior of how Emacs displays references is dependent on the variable
Info-hide-note-references. If set to the value of hide, Emacs will hide both the *note:
part and the target-id. This is generally the best way to view Sphinx-based documents since they often
make frequent use of links and do not take this limitation into account. However, changing this variable
affects how all Info documents are displayed and most do take this behavior into account.
If you want Emacs to display Info files produced by Sphinx using the value hide for
Info-hide-note-references and the default value for all other Info files, try adding the following
Emacs Lisp code to your start-up file, ~/.emacs.d/init.el.
19.4.2 Notes
The following notes may be helpful if you want to create Texinfo files:
• Each section corresponds to a different node in the Info file.
• Colons (:) cannot be properly escaped in menu entries and xrefs. They will be replaced with
semicolons (;).
• Links to external Info files can be created using the somewhat official URI scheme info. For exam-
ple:
info:Texinfo#makeinfo_options
• Inline markup
The standard formatting for *strong* and _emphasis_ can result in ambiguous output when used
to markup parameter names and other values. Since this is a fairly common practice, the default
formatting has been changed so that emphasis and strong are now displayed like `literal's.
The standard formatting can be re-enabled by adding the following to your conf.py:
TWENTY
GLOSSARY
builder A class (inheriting from Builder) that takes parsed documents and performs an action on them.
Normally, builders translate the documents to an output format, but it is also possible to use the
builder builders that e.g. check for broken links in the documentation, or build coverage information.
See Builders for an overview over Sphinx’s built-in builders.
configuration directory The directory containing conf.py. By default, this is the same as the source
directory, but can be set differently with the -c command-line option.
directive A reStructuredText markup element that allows marking a block of content with special mean-
ing. Directives are supplied not only by docutils, but Sphinx and custom extensions can add their
own. The basic directive syntax looks like this:
293
Sphinx Documentation, Release 3.0.0+/0fb832baa
object The basic building block of Sphinx documentation. Every “object directive” (e.g. function or
object) creates such a block; and most objects can be cross-referenced to.
RemoveInSphinxXXXWarning The feature which is warned will be removed in Sphinx-XXX version. It
usually caused from Sphinx extensions which is using deprecated. See also Deprecation Warnings.
role A reStructuredText markup element that allows marking a piece of text. Like directives, roles are
extensible. The basic syntax looks like this: :rolename:`content`. See Inline markup for details.
source directory The directory which, including its subdirectories, contains all source files for one Sphinx
project.
reStructuredText An easy-to-read, what-you-see-is-what-you-get plaintext markup syntax and parser sys-
tem.
TWENTYONE
Abstract
This document describes the development process of Sphinx, a documentation system used by de-
velopers to document systems used by other developers to develop other systems that may also be
documented using Sphinx.
The Sphinx source code is managed using Git and is hosted on GitHub.
git clone git://github.com/sphinx-doc/sphinx
Community
295
Sphinx Documentation, Release 3.0.0+/0fb832baa
If you have encountered a problem with Sphinx or have an idea for a new feature, please submit it to the
issue tracker283 on GitHub or discuss it on the sphinx-dev284 mailing list.
For bug reports, please include the output produced during the build process and also the log file Sphinx
creates after it encounters an unhandled exception. The location of this file should be shown towards the
end of the error message.
Including or providing a link to the source files involved may help us fix the issue. If possible, try to create
a minimal project that produces the error and post that instead.
The recommended way for new contributors to submit code to Sphinx is to fork the repository on GitHub
and then submit a pull request after committing the changes. The pull request will then need to be
approved by one of the core developers before it is merged into the main repository.
1. Check for open issues or open a fresh issue to start a discussion around a feature idea or a bug.
2. If you feel uncomfortable or uncertain about an issue or your changes, feel free to email the sphinx-
dev mailing list.
3. Fork the repository285 on GitHub to start making your changes to the master branch for next
MAJOR version, or X.Y branch for next MINOR version (see Branch Model).
4. Write a test which shows that the bug was fixed or that the feature works as expected.
5. Send a pull request and bug the maintainer until it gets merged and published. Make sure to add
yourself to AUTHORS286 and the change to CHANGES287 .
283 https://github.com/sphinx-doc/sphinx/issues
284 sphinx-dev@googlegroups.com
285 https://github.com/sphinx-doc/sphinx
286 https://github.com/sphinx-doc/sphinx/blob/master/AUTHORS
287 https://github.com/sphinx-doc/sphinx/blob/master/CHANGES
288 https://github.com/sphinx-doc/sphinx
For incompatible or other substantial changes that should wait until the next MAJOR release, use
the master branch.
For urgent release, a new PATCH branch must be branched from the newest release tag (see Branch
Model for detail).
5. Setup a virtual environment.
This is not necessary for unit testing, thanks to tox, but it is necessary if you wish to run
sphinx-build locally or run unit tests without the help of tox.
virtualenv ~/.venv
. ~/.venv/bin/activate
pip install -e .
tox -av
tox -e py36
• To run unit tests for a specific Python version and turn on deprecation warnings on so they’re
shown in the test output:
tox -e mypy
tox -e flake8
• Arguments to pytest can be passed via tox, e.g. in order to run a particular test:
tox -e docs
• To run JavaScript tests with Karma289 , execute the following commands (requires Node.js290 ):
289 https://karma-runner.github.io
290 https://nodejs.org
npm install
npm run test
New unit tests should be included in the tests directory where necessary:
• For bug fixes, first add a test that fails without your changes and passes after they are applied.
• Tests that need a sphinx-build run should be integrated in one of the existing test modules if
possible. New tests that to @with_app and then build_all for a few assertions are not good
since the test suite should not take more than a minute to run.
9. Please add a bullet point to CHANGES if the fix or feature is not trivial (small doc updates, typo fixes).
Then commit:
git commit -m '#42: Add useful new feature that does this.'
GitHub recognizes certain phrases that can be used to automatically update the issue tracker.
For example:
11. Submit a pull request from your branch to the respective branch (master or X.Y).
12. Wait for a core developer to review your changes.
The core developers of Sphinx have write access to the main repository. They can commit changes,
accept/reject pull requests, and manage items on the issue tracker.
You do not need to be a core developer or have write access to be involved in the development of Sphinx.
You can submit patches or create pull requests from forked repositories and have a core developer add
the changes for you.
The following are some general guidelines for core developers:
• Questionable or extensive changes should be submitted as a pull request instead of being committed
directly to the main repository. The pull request should be reviewed by another core developer
before it is merged.
• Trivial changes can be committed directly but be sure to keep the repository in a good working state
and that all tests pass before pushing your changes.
• When committing code written by someone else, please attribute the original author in the commit
message and any relevant CHANGES entry.
The parts of messages in Sphinx that go into builds are translated into several locales. The translations are
kept as gettext .po files translated from the master template sphinx/locale/sphinx.pot.
Sphinx uses Babel291 to extract messages and maintain the catalog files. It is integrated in setup.py:
• Use python setup.py extract_messages to update the .pot template.
• Use python setup.py update_catalog to update all existing language catalogs in sphinx/
locale/*/LC_MESSAGES with the current messages in the template file.
• Use python setup.py compile_catalog to compile the .po files to binary .mo files and .js
files.
When an updated .po file is submitted, run compile_catalog to commit both the source and the compiled
catalogs.
When a new locale is submitted, add a new directory with the ISO 639-1 language identifier and
put sphinx.po in there. Don’t forget to update the possible values for language in doc/usage/
configuration.rst.
The Sphinx core messages can also be translated on Transifex292 . There exists a client tool named tx in the
Python package “transifex_client”, which can be used to pull translations in .po format from Transifex.
To do this, go to sphinx/locale and then run tx pull -f -l LANG where LANG is an existing
language identifier. It is good practice to run python setup.py update_catalog afterwards to make
sure the .po file has the canonical Babel formatting.
• Try to use the same code style as used in the rest of the project. See the Pocoo Styleguide293 for more
information.
• For non-trivial changes, please update the CHANGES file. If your changes alter existing behavior,
please document this.
• New features should be documented. Include examples and use cases where appropriate. If possible,
include a sample that is displayed in the generated output.
• When adding a new configuration variable, be sure to document it and update sphinx/cmd/
quickstart.py if it’s important enough.
• Add appropriate unit tests.
• Delete the build cache before building documents if you make changes in the code by running the
command make clean or using the sphinx-build -E option.
• Use the sphinx-build -P option to run pdb on exceptions.
• Use node.pformat() and node.asdom().toxml() to generate a printable representation of the
document structure.
• Set the configuration variable keep_warnings to True so warnings will be displayed in the gener-
ated output.
291 http://babel.pocoo.org/en/latest/
292 https://www.transifex.com/
293 http://flask.pocoo.org/docs/styleguide/
• Set the configuration variable nitpicky to True so that Sphinx will complain about references
without a known target.
• Set the debugging options in the Docutils configuration file294 .
• JavaScript stemming algorithms in sphinx/search/*.py (except en.py) are generated by this
modified snowballcode generator295 . Generated JSX296 files are in this repository297 . You can get the
resulting JavaScript files using the following command:
npm install
node_modules/.bin/grunt build # -> dest/*.global.js
Sphinx project uses following branches for developing that conforms to Semantic Versioning 2.0.0 (refs:
https://semver.org/ ).
master Development for MAJOR version. All changes including incompatible behaviors and public API
updates are allowed.
X.Y Where X.Y is the MAJOR.MINOR release. Used to maintain current MINOR release. All changes are
allowed if the change preserves backwards-compatibility of API and features.
Only the most recent MAJOR.MINOR branch is currently retained. When a new MAJOR version is
released, the old MAJOR.MINOR branch will be deleted and replaced by an equivalent tag.
X.Y.Z Where X.Y.Z is the MAJOR.MINOR.PATCH release. Only backwards-compatible bug fixes are
allowed. In Sphinx project, PATCH version is used for urgent bug fix.
MAJOR.MINOR.PATCH branch will be branched from the v prefixed release tag (ex. make 2.3.1 that
branched from v2.3.0) when a urgent release is needed. When new PATCH version is released, the
branch will be deleted and replaced by an equivalent tag (ex. v2.3.1).
pytest -Wall
Thus, when adding a RemovedInSphinxXXWarning you need to eliminate or silence any warnings
generated when running the tests.
294 http://docutils.sourceforge.net/docs/user/config.html
295 https://github.com/shibukawa/snowball
296 https://jsx.github.io/
297 https://github.com/shibukawa/snowball-stemmer.jsx
MAJOR and MINOR releases may deprecate certain features from previous releases. If a feature is depre-
cated in a release A.x, it will continue to work in all A.x.x versions (for all versions of x). It will continue
to work in all B.x.x versions but raise deprecation warnings. Deprecated features will be removed at the
C.0.0. It means the deprecated feature will work during 2 MAJOR releases at least.
So, for example, if we decided to start the deprecation of a function in Sphinx 2.x:
• Sphinx 2.x will contain a backwards-compatible replica of the function which will raise a
RemovedInSphinx40Warning.
• Sphinx 3.x will still contain the backwards-compatible replica.
• Sphinx 4.0 will remove the feature outright.
The warnings are displayed by default. You can turn off display of these warnings with:
• PYTHONWARNINGS= make html (Linux/Mac)
• export PYTHONWARNINGS= and do make html (Linux/Mac)
• set PYTHONWARNINGS= and do make html (Windows)
Sphinx has been tested with pytest runner. Sphinx developers write unit tests using pytest notation.
Utility functions and pytest fixtures for testing are provided in sphinx.testing. If you are a developer
of Sphinx extensions, you can write unit tests with using pytest. At this time, sphinx.testing will help
your test implementation.
How to use pytest fixtures that are provided by sphinx.testing? You can require 'sphinx.testing.
fixtures' in your test modules or conftest.py files like this:
pytest_plugins = 'sphinx.testing.fixtures'
If you want to know more detailed usage, please refer to tests/conftest.py and other test_*.py
files under tests directory.
Note: Prior to Sphinx - 1.5.2, Sphinx was running the test with nose.
TWENTYTWO
CHANGES IN SPHINX
22.1.1 Dependencies
22.1.3 Deprecated
22.1.6 Testing
22.2.1 Dependencies
22.2.3 Deprecated
303
Sphinx Documentation, Release 3.0.0+/0fb832baa
• py domain: duplicated warning does not point the location of source code
• #1125: html theme: scrollbar is hard to see on classic theme and macOS
• #5502: linkcheck: Consider HTTP 503 response as not an error
• #6439: Make generated download links reproducible
• #6486: UnboundLocalError is raised if broken extension installed
22.2.6 Testing
22.3.1 Dependencies
22.3.3 Deprecated
22.3.6 Testing
• #6442: LaTeX: admonitions of note type can get separated from immediately preceding section title
by pagebreak
• #6448: autodoc: crashed when autodocumenting classes with __slots__ = None
• #6451: autodoc: generates docs for “optional import”ed modules as variables
• #6452: autosummary: crashed when generating document of properties
• #6455: napoleon: docstrings for properties are not processed
• #6436: napoleon: “Unknown target name” error if variable name ends with underscore
• #6440: apidoc: missing blank lines between modules
22.5.2 Deprecated
• sphinx.builders.latex.LaTeXBuilder.apply_transforms()
• sphinx.builders._epub_base.EpubBuilder.esc()
• sphinx.directives.Acks
• sphinx.directives.Author
• sphinx.directives.Centered
• sphinx.directives.Class
• sphinx.directives.CodeBlock
• sphinx.directives.Figure
• sphinx.directives.HList
• sphinx.directives.Highlight
• sphinx.directives.Include
• sphinx.directives.Index
• sphinx.directives.LiteralInclude
• sphinx.directives.Meta
• sphinx.directives.Only
• sphinx.directives.SeeAlso
• sphinx.directives.TabularColumns
• sphinx.directives.TocTree
• sphinx.directives.VersionChange
• sphinx.domains.python.PyClassmember
• sphinx.domains.python.PyModulelevel
• sphinx.domains.std.StandardDomain._resolve_citation_xref()
• sphinx.domains.std.StandardDomain.note_citations()
• sphinx.domains.std.StandardDomain.note_citation_refs()
• sphinx.domains.std.StandardDomain.note_labels()
• sphinx.environment.NoUri
• sphinx.ext.apidoc.format_directive()
• sphinx.ext.apidoc.format_heading()
• sphinx.ext.apidoc.makename()
• sphinx.ext.autodoc.importer.MockFinder
• sphinx.ext.autodoc.importer.MockLoader
• sphinx.ext.autodoc.importer.mock()
• sphinx.ext.autosummary.autolink_role()
• sphinx.ext.imgmath.DOC_BODY
• sphinx.ext.imgmath.DOC_BODY_PREVIEW
• sphinx.ext.imgmath.DOC_HEAD
• sphinx.transforms.CitationReferences
• sphinx.transforms.SmartQuotesSkipper
• sphinx.util.docfields.DocFieldTransformer.preprocess_fieldtypes()
• sphinx.util.node.find_source_node()
• sphinx.util.i18n.find_catalog()
• sphinx.util.i18n.find_catalog_files()
• sphinx.util.i18n.find_catalog_source_files()
For more details, see deprecation APIs list.
• #6230: Inappropriate node_id has been generated by glossary directive if term is consisted by non-
ASCII characters
• #6213: ifconfig: contents after headings are not shown
• commented term in glossary directive is wrongly recognized
• #6299: rst domain: rst:directive directive generates waste space
• #6379: py domain: Module index (py-modindex.html) has duplicate titles
• #6331: man: invalid output when doctest follows rubric
• #6351: “Hyperlink target is not referenced” message is shown even if referenced
• #6165: autodoc: tab_width setting of docutils has been ignored
• #6347: autodoc: crashes with a plain Tuple on Python 3.6 and 3.5
• #6311: autosummary: autosummary table gets confused by complex type hints
• #6350: autosummary: confused by an argument having some kind of default value
• Generated Makefiles lack a final EOL (refs: #6232)
• #6375: extlinks: Cannot escape angle brackets in link caption
• #6378: linkcheck: Send commonly used User-Agent
• #6387: html search: failed to search document with haiku and scrolls themes
• #6408: html search: Fix the ranking of search results
• #6406: Wrong year is returned for SOURCE_DATE_EPOCH
22.7.1 Dependencies
2.0.0b1
• LaTeX builder now depends on TeX Live 2015 or above.
• LaTeX builder (with 'pdflatex' latex_engine) will process Unicode Greek letters in text (not
in math mark-up) via the text font and will not escape them to math mark-up. See the discus-
sion of the 'fontenc' key of latex_elements; such (optional) support for Greek adds, for ex-
ample on Ubuntu xenial, the texlive-lang-greek and (if default font set-up is not modified)
cm-super(-minimal) as additional Sphinx LaTeX requirements.
• LaTeX builder with latex_engine set to 'xelatex' or to 'lualatex' requires (by default) the
FreeFont fonts, which in Ubuntu xenial are provided by package fonts-freefont-otf, and e.g.
in Fedora 29 via package texlive-gnu-freefont.
• requests 2.5.0 or above
• The six package is no longer a dependency
• The sphinxcontrib-websupport package is no longer a dependency
• Some packages are separated to sub packages:
– sphinxcontrib.applehelp
– sphinxcontrib.devhelp
– sphinxcontrib.htmlhelp
– sphinxcontrib.jsmath
– sphinxcontrib.serializinghtml
– sphinxcontrib.qthelp
2.0.0b1
• Drop python 2.7 and 3.4 support
• Drop docutils 0.11 support
• Drop features and APIs deprecated in 1.7.x
• The default setting for master_doc is changed to 'index' which has been longly used as default
of sphinx-quickstart.
• LaTeX: Move message resources to sphinxmessage.sty
• LaTeX: Stop using \captions<lang> macro for some labels
• LaTeX: for 'xelatex' and 'lualatex', use the FreeFont OpenType fonts as default choice (refs:
#5645)
• LaTeX: 'xelatex' and 'lualatex' now use \small in code-blocks (due to FreeMono character
width) like 'pdflatex' already did (due to Courier character width). You may need to adjust this
via latex_elements 'fvset' key, in case of usage of some other OpenType fonts (refs: #5768)
• LaTeX: Greek letters in text are not escaped to math mode mark-up, and they will use the text font not
the math font. The LGR font encoding must be added to the 'fontenc' key of latex_elements
for this to work (only if it is needed by the document, of course).
• LaTeX: setting the language to 'en' triggered Sonny option of fncychap, now it is Bjarne to
match case of no language specified. (refs: #5772)
• #5770: doctest: Follow highlight_language on highlighting doctest block. As a result, they are
highlighted as python3 by default.
• The order of argument for HTMLTranslator, HTML5Translator and ManualPageTranslator
are changed
• LaTeX: hard-coded redefinitions of \l@section and \l@subsection formerly done dur-
ing loading of 'manual' docclass get executed later, at time of \sphinxtableofcontents.
This means that custom user definitions from LaTeX preamble now get overwritten. Use
\sphinxtableofcontentshook to insert custom user definitions. See Macros.
• quickstart: Simplify generated conf.py
• #4148: quickstart: some questions are removed. They are still able to specify via command line
options
• websupport: unbundled from sphinx core. Please use sphinxcontrib-websupport
• C++, the visibility of base classes is now always rendered as present in the input. That is, private
is now shown, where it was ellided before.
• LaTeX: graphics inclusion of oversized images rescales to not exceed the text width and height, even
if width and/or height option were used. (refs: #5956)
22.7.3 Deprecated
2.0.0b1
• Support for evaluating Python 2 syntax is deprecated. This includes configuration files which should
be converted to Python 3.
• The arguments of EpubBuilder.build_mimetype(), EpubBuilder.build_container(),
EpubBuilder.bulid_content(), EpubBuilder.build_toc() and EpubBuilder.
build_epub()
• The arguments of Epub3Builder.build_navigation_doc()
• The config variables
– html_experimental_html5_writer
• The encoding argument of autodoc.Documenter.get_doc(), autodoc.
DocstringSignatureMixin.get_doc(), autodoc.DocstringSignatureMixin.
_find_signature(), and autodoc.ClassDocumenter.get_doc() are deprecated.
• The importer argument of sphinx.ext.autodoc.importer._MockModule
• The nodetype argument of sphinx.search.WordCollector. is_meta_keywords()
• The suffix argument of env.doc2path() is deprecated.
• The string style base argument of env.doc2path() is deprecated.
• The fallback to allow omitting the filename argument from an overridden IndexBuilder.
feed() method is deprecated.
• sphinx.addnodes.abbreviation
• sphinx.application.Sphinx._setting_up_extension
• sphinx.builders.epub3.Epub3Builder.validate_config_value()
• sphinx.builders.html.SingleFileHTMLBuilder
• sphinx.builders.htmlhelp.HTMLHelpBuilder.open_file()
• sphinx.cmd.quickstart.term_decode()
• sphinx.cmd.quickstart.TERM_ENCODING
• sphinx.config.check_unicode()
• sphinx.config.string_classes
• sphinx.domains.cpp.DefinitionError.description
• sphinx.domains.cpp.NoOldIdError.description
• sphinx.domains.cpp.UnsupportedMultiCharacterCharLiteral.decoded
• sphinx.ext.autodoc.importer._MockImporter
• sphinx.ext.autosummary.Autosummary.warn()
• sphinx.ext.autosummary.Autosummary.genopt
• sphinx.ext.autosummary.Autosummary.warnings
• sphinx.ext.autosummary.Autosummary.result
• sphinx.ext.doctest.doctest_encode()
• sphinx.io.SphinxBaseFileInput
• sphinx.io.SphinxFileInput.supported
• sphinx.io.SphinxRSTFileInput
• sphinx.registry.SphinxComponentRegistry.add_source_input()
• sphinx.roles.abbr_role()
• sphinx.roles.emph_literal_role()
• sphinx.roles.menusel_role()
• sphinx.roles.index_role()
• sphinx.roles.indexmarkup_role()
• sphinx.testing.util.remove_unicode_literal()
• sphinx.util.attrdict
• sphinx.util.force_decode()
• sphinx.util.get_matching_docs()
• sphinx.util.inspect.Parameter
• sphinx.util.jsonimpl
• sphinx.util.osutil.EEXIST
• sphinx.util.osutil.EINVAL
• sphinx.util.osutil.ENOENT
• sphinx.util.osutil.EPIPE
• sphinx.util.osutil.walk()
• sphinx.util.PeekableIterator
• sphinx.util.pycompat.NoneType
• sphinx.util.pycompat.TextIOWrapper
• sphinx.util.pycompat.UnicodeMixin
• sphinx.util.pycompat.htmlescape
• sphinx.util.pycompat.indent
• sphinx.util.pycompat.sys_encoding
• sphinx.util.pycompat.terminal_safe()
• sphinx.util.pycompat.u
• sphinx.writers.latex.ExtBabel
• sphinx.writers.latex.LaTeXTranslator._make_visit_admonition()
• sphinx.writers.latex.LaTeXTranslator.babel_defmacro()
• sphinx.writers.latex.LaTeXTranslator.collect_footnotes()
• sphinx.writers.latex.LaTeXTranslator.generate_numfig_format()
• sphinx.writers.texinfo.TexinfoTranslator._make_visit_admonition()
• sphinx.writers.text.TextTranslator._make_depart_admonition()
• template variables for LaTeX template
– logo
– numfig_format
– pageautorefname
– translatablestrings
For more details, see deprecation APIs list.
2.0.0b1
• #1618: The search results preview of generated HTML documentation is reader-friendlier: instead
of showing the snippets as raw reStructuredText markup, Sphinx now renders the corresponding
HTML. This means the Sphinx extension Sphinx: pretty search results298 is no longer necessary. Note
that changes to the search function of your custom or 3rd-party HTML template might overwrite
this improvement.
• #4182: autodoc: Support suppress_warnings
• #5533: autodoc: autodoc_default_options supports member-order
• #5394: autodoc: Display readable names in type annotations for mocked objects
• #5459: autodoc: autodoc_default_options accepts True as a value
• #1148: autodoc: Add autodecorator directive for decorators
• #5635: autosummary: Add autosummary_mock_imports to mock external libraries on importing
targets
• #4018: htmlhelp: Add htmlhelp_file_suffix and htmlhelp_link_suffix
• #5559: text: Support complex tables (colspan and rowspan)
• LaTeX: support rendering (not in math, yet) of Greek and Cyrillic Unicode letters in non-Cyrillic
document even with 'pdflatex' as latex_engine (refs: #5645)
• #5660: The versionadded, versionchanged and deprecated directives are now generated with
their own specific CSS classes (added, changed and deprecated, respectively) in addition to the
generic versionmodified class.
• #5841: apidoc: Add –extensions option to sphinx-apidoc
• #4981: C++, added an alias directive for inserting lists of declarations, that references existing decla-
rations (e.g., for making a synopsis).
• C++: add cpp:struct to complement cpp:class.
• #1341 the HTML search considers words that contain a search term of length three or longer a match.
• #4611: epub: Show warning for duplicated ToC entries
• #1851: Allow to omit an argument for code-block directive. If omitted, it follows highlight or
highlight_language
• #4587: html: Add html4_writer to use old HTML4 writer
• #6016: HTML search: A placeholder for the search summary prevents search result links from
changing their position when the search terminates. This makes navigating search results easier.
298 https://github.com/sphinx-contrib/sphinx-pretty-searchresults
2.0.0b1
• #1682: LaTeX: writer should not translate Greek unicode, but use textgreek package
• #5247: LaTeX: PDF does not build with default font config for Russian language and 'xelatex' or
'lualatex' as latex_engine (refs: #5251)
• #5248: LaTeX: Greek letters in section titles disappear from PDF bookmarks
• #5249: LaTeX: Unicode Greek letters in math directive break PDF build (fix requires extra set-up, see
latex_elements 'textgreek' key and/or latex_engine setting)
• #5772: LaTeX: should the Bjarne style of fncychap be used for English also if passed as language
option?
• #5179: LaTeX: (lualatex only) escaping of > by \textgreater{} is not enough as
\textgreater{}\textgreater{} applies TeX-ligature
• LaTeX: project name is not escaped if latex_documents omitted
• LaTeX: authors are not shown if latex_documents omitted
• HTML: Invalid HTML5 file is generated for a glossary having multiple terms for one description
(refs: #4611)
• QtHelp: OS dependent path separator is used in .qhp file
• HTML search: search always returns nothing when multiple search terms are used and one term is
shorter than three characters
2.0.0b2
• #6096: html: Anchor links are not added to figures
• #3620: html: Defer searchindex.js rather than loading it via ajax
• #6113: html: Table cells and list items have large margins
• #5508: linenothreshold option for highlight directive was ignored
• texinfo: make install-info causes syntax error
• texinfo: make install-info fails on macOS
• #3079: texinfo: image files are not copied on make install-info
• #5391: A cross reference in heading is rendered as literal
• #5946: C++, fix cpp:alias problems in LaTeX (and singlehtml)
• #6147: classes attribute of citation_reference node is lost
• AssertionError is raised when custom citation_reference node having classes attribute refers
missing citation (refs: #6147)
• #2155: Support code directive
• C++, fix parsing of braced initializers.
• #6172: AttributeError is raised for old styled index nodes
• #4872: inheritance_diagram: correctly describe behavior of parts option in docs, allow negative
values.
• #6178: i18n: Captions missing in translations for hidden TOCs
2.0.0 final
• #6196: py domain: unexpected prefix is generated
22.7.6 Testing
2.0.0b1
• Stop to use SPHINX_TEST_TEMPDIR envvar
2.0.0b2
• Add a helper function: sphinx.testing.restructuredtext.parse()
• LaTeX: Remove extraneous space after author names on PDF title page (refs: #6004)
• #6026: LaTeX: A cross reference to definition list does not work
• #6046: LaTeX: TypeError is raised when invalid latex_elements given
• #6067: LaTeX: images having a target are concatenated to next line
• #6067: LaTeX: images having a target are not aligned even if specified
• #6149: LaTeX: :index: role in titles causes Use of \@icentercr doesn't match its
definition error on latexpdf build
• #6019: imgconverter: Including multipage PDF fails
• #6047: autodoc: autofunction emits a warning for method objects
• #6028: graphviz: Ensure the graphviz filenames are reproducible
• #6068: doctest: skipif option may remove the code block from documentation
• #6136: :name: option for math directive causes a crash
• #6139: intersphinx: ValueError on failure reporting
• #6135: changes: Fix UnboundLocalError when any module found
• #3859: manpage: code-block captions are not displayed correctly
• #5755: C++, fix duplicate declaration error on function templates with constraints in the return type.
• C++, parse unary right fold expressions and binary fold expressions.
• pycode could not handle egg files on windows
• #5928: KeyError: ‘DOCUTILSCONFIG’ when running build
• #5936: LaTeX: PDF build broken by inclusion of image taller than page height in an admonition
• #5231: “make html” does not read and build “po” files in “locale” dir
• #5954: :scale: image option may break PDF build if image in an admonition
• #5966: mathjax has not been loaded on incremental build
• #5960: LaTeX: modified PDF layout since September 2018 TeXLive update of parskip.sty
• #5948: LaTeX: duplicated labels are generated for sections
• #5958: versionadded directive causes crash with Python 3.5.0
• #5995: autodoc: autodoc_mock_imports conflict with metaclass on Python 3.7
• #5871: texinfo: a section title . is not allowed
• LaTeX: it is possible to insert custom material to appear on back of title page, see discussion of
'maketitle' key of latex_elements ('manual' docclass only)
• htmlhelp: broken .hhk file generated when title contains a double quote
• LaTeX \pagestyle commands have been moved to the LaTeX template. No changes in PDF, except
possibly if \sphinxtableofcontents, which contained them, had been customized in conf.py.
(refs: #5455)
22.13.1 Dependencies
1.8.0b1
• LaTeX: latex_use_xindy, if True (default for xelatex/lualatex), instructs make latexpdf
to use xindy for general index. Make sure your LaTeX distribution includes it. (refs: #5134)
• LaTeX: latexmk is required for make latexpdf on Windows
1.8.0b2
• #5282: html theme: refer pygments_style settings of HTML themes preferentially
• The URL of download files are changed
• #5127: quickstart: Makefile and make.bat are not overwritten if exists
1.8.0b1
• #5156: the sphinx.ext.graphviz: extension runs `dot in the directory of the document
being built instead of in the root directory of the documentation.
• #4460: extensions which stores any data to environment should return the version of its env data
structure as metadata. In detail, please see Extension metadata.
• Sphinx expects source parser modules to have supported file formats as Parser.supported at-
tribute
• The default value of epub_author and epub_publisher are changed from 'unknown' to the
value of author. This is same as a conf.py file sphinx-build generates.
22.13.3 Deprecated
1.8.0b2
• sphinx.io.SphinxI18nReader.set_lineno_for_reporter() is deprecated
• sphinx.io.SphinxI18nReader.line is deprecated
• sphinx.util.i18n.find_catalog_source_file() has changed; the gettext_compact argu-
ment has been deprecated
• #5403: sphinx.util.images.guess_mimetype() has changed; the content argument has been
deprecated
1.8.0b1
• source_parsers is deprecated
• autodoc_default_flags is deprecated
• quickstart: --epub option becomes default, so it is deprecated
• Drop function based directive support. For now, Sphinx only supports class based directives (see
Directive)
• sphinx.util.docutils.directive_helper() is deprecated
• sphinx.cmdline is deprecated
• sphinx.make_mode is deprecated
• sphinx.locale.l_() is deprecated
• #2157: helper function warn() for HTML themes is deprecated
• app.override_domain() is deprecated
• app.add_stylesheet() is deprecated
• app.add_javascript() is deprecated
• app.import_object() is deprecated
• app.add_source_parser() has changed; the suffix argument has been deprecated
• sphinx.versioning.prepare() is deprecated
• Config.__init__() has changed; the dirname, filename and tags argument has been deprecated
• Config.check_types() is deprecated
• Config.check_unicode() is deprecated
• sphinx.application.CONFIG_FILENAME is deprecated
• highlightlang directive is deprecated
• BuildEnvironment.load() is deprecated
• BuildEnvironment.loads() is deprecated
• BuildEnvironment.frompickle() is deprecated
• env.read_doc() is deprecated
• env.update() is deprecated
• env._read_serial() is deprecated
• env._read_parallel() is deprecated
• env.write_doctree() is deprecated
• env._nitpick_ignore is deprecated
• env.versionchanges is deprecated
• env.dump() is deprecated
• env.dumps() is deprecated
• env.topickle() is deprecated
• env.note_versionchange() is deprecated
• sphinx.writers.latex.Table.caption_footnotetexts is deprecated
• sphinx.writers.latex.Table.header_footnotetexts is deprecated
• sphinx.writers.latex.LaTeXTranslator.footnotestack is deprecated
• sphinx.writers.latex.LaTeXTranslator.in_container_literal_block is deprecated
• sphinx.writers.latex.LaTeXTranslator.next_section_ids is deprecated
• sphinx.writers.latex.LaTeXTranslator.next_hyperlink_ids is deprecated
• sphinx.writers.latex.LaTeXTranslator.restrict_footnote() is deprecated
• sphinx.writers.latex.LaTeXTranslator.unrestrict_footnote() is deprecated
• sphinx.writers.latex.LaTeXTranslator.push_hyperlink_ids() is deprecated
• sphinx.writers.latex.LaTeXTranslator.pop_hyperlink_ids() is deprecated
• sphinx.writers.latex.LaTeXTranslator.check_latex_elements() is deprecated
• sphinx.writers.latex.LaTeXTranslator.bibitems is deprecated
• sphinx.writers.latex.LaTeXTranslator.hlsettingstack is deprecated
• sphinx.writers.latex.ExtBabel.get_shorthandoff() is deprecated
• sphinx.writers.html.HTMLTranslator.highlightlang is deprecated
• sphinx.writers.html.HTMLTranslator.highlightlang_base is deprecated
• sphinx.writers.html.HTMLTranslator.highlightlangopts is deprecated
• sphinx.writers.html.HTMLTranslator.highlightlinenothreshold is deprecated
• sphinx.writers.html5.HTMLTranslator.highlightlang is deprecated
• sphinx.writers.html5.HTMLTranslator.highlightlang_base is deprecated
• sphinx.writers.html5.HTMLTranslator.highlightlangopts is deprecated
• sphinx.writers.html5.HTMLTranslator.highlightlinenothreshold is deprecated
• sphinx.ext.mathbase extension is deprecated
• sphinx.ext.mathbase.math node is deprecated
• sphinx.ext.mathbase.displaymath node is deprecated
• sphinx.ext.mathbase.eqref node is deprecated
• sphinx.ext.mathbase.is_in_section_title() is deprecated
• sphinx.ext.mathbase.MathDomain is deprecated
• sphinx.ext.mathbase.MathDirective is deprecated
• sphinx.ext.mathbase.math_role is deprecated
• sphinx.ext.mathbase.setup_math() is deprecated
• sphinx.directives.other.VersionChanges is deprecated
• sphinx.highlighting.PygmentsBridge.unhighlight() is deprecated
• sphinx.ext.mathbase.get_node_equation_number() is deprecated
• sphinx.ext.mathbase.wrap_displaymath() is deprecated
• The trim_doctest_flags argument of sphinx.highlighting.PygmentsBridge is depre-
cated
For more details, see deprecation APIs list299
299 http://www.sphinx-doc.org/en/master/extdev/index.html#deprecated-apis
1.8.0b2
• #5388: Ensure frozen object descriptions are reproducible
• #5362: apidoc: Add --tocfile option to change the filename of ToC
1.8.0b1
• Add config-inited event
• Add sphinx.config.Any to represent the config value accepts any type of value
• source_suffix allows a mapping fileext to file types
• Add author as a configuration value
• #2852: imgconverter: Support to convert GIF to PNG
• sphinx-build command supports i18n console output
• Add app.add_message_catalog() and sphinx.locale.get_translations() to support
translation for 3rd party extensions
• helper function warning() for HTML themes is added
• Add Domain.enumerable_nodes to manage own enumerable nodes for domains (experimental)
• Add a new keyword argument override to Application APIs
• LaTeX: new key 'fvset' for latex_elements. For XeLaTeX/LuaLaTeX its default sets fanvyvrb
to use normal, not small, fontsize in code-blocks (refs: #4793)
• Add html_css_files and epub_css_files for adding CSS files from configuration
• Add html_js_files for adding JS files from configuration
• #4834: Ensure set object descriptions are reproducible.
• #4828: Allow to override numfig_format partially. Full definition is not needed.
• Improve warning messages during including (refs: #4818)
• LaTeX: separate customizability of guilabel and menuselection (refs: #4830)
• Add Config.read() classmethod to create a new config object from configuration file
• #4866: Wrap graphviz diagrams in <div> tag
• viewcode: Add viewcode-find-source and viewcode-follow-imported to load source code
without loading
• #4785: napoleon: Add strings to translation file for localisation
• #4927: Display a warning when invalid values are passed to linenothreshold option of highlight
directive
• C++:
– Add a cpp:texpr role as a sibling to cpp:expr.
– Add support for unions.
– #3593, #2683: add support for anonymous entities using names staring with @.
– #5147: add support for (most) character literals.
– Cross-referencing entities inside primary templates is supported, and now properly docu-
mented.
– #1552: add new cross-referencing format for cpp:any and cpp:func roles, for referencing
specific function overloads.
1.8.0b2
• html: search box overrides to other elements if scrolled
• i18n: warnings for translation catalogs have wrong line numbers (refs: #5321)
• #5325: latex: cross references has been broken by multiply labeled objects
• C++, fixes for symbol addition and lookup. Lookup should no longer break in partial builds. See
also #5337.
• #5348: download reference to remote file is not displayed
• #5282: html theme: pygments_style of theme was overridden by conf.py by default
• #4379: toctree shows confusing warning when document is excluded
• #2401: autodoc: :members: causes :special-members: not to be shown
• autodoc: ImportError is replaced by AttributeError for deeper module
• #2720, #4034: Incorrect links with :download:, duplicate names, and parallel builds
• #5290: autodoc: failed to analyze source code in egg package
• #5399: Sphinx crashes if unknown po file exists
1.8.0b1
1.8.0b1
• sphinx.ext.pngmath extension
22.13.7 Documentation
1.8.0b1
• #5083: Fix wrong make.bat option for internationalization.
• #5115: napoleon: add admonitions added by #4613 to the docs.
• #5198: document not in toctree warning when including files only for parallel builds
• LaTeX: reduce “Token not allowed in a PDF string” hyperref warnings in latex console output (refs:
#5236)
• LaTeX: suppress “remreset Warning: The remreset package is obsolete” in latex console output with
recent LaTeX (refs: #5237)
• #5234: PDF output: usage of PAPER environment variable is broken since Sphinx 1.5
• LaTeX: fix the latex_engine documentation regarding Latin Modern font with XeLaTeX/LuaLateX
(refs: #5251)
• #5280: autodoc: Fix wrong type annotations for complex typing
• autodoc: Optional types are wrongly rendered
• #5291: autodoc crashed by ForwardRef types
• #5211: autodoc: No docs generated for functools.partial functions
• #5306: autodoc: getargspec() raises NameError for invalid typehints
• #5298: imgmath: math_number_all causes equations to have two numbers in html
• #5294: sphinx-quickstart blank prompts in PowerShell
• #4667: C++, fix assertion on missing references in global scope when using intersphinx. Thanks to
Alan M. Carroll.
• #5019: autodoc: crashed by Form Feed Character
• #5032: autodoc: loses the first staticmethod parameter for old styled classes
• #5036: quickstart: Typing Ctrl-U clears the whole of line
• #5066: html: “relations” sidebar is not shown by default
• #5091: latex: curly braces in index entries are not handled correctly
• #5070: epub: Wrong internal href fragment links
• #5104: apidoc: Interface of sphinx.apidoc:main() has changed
• #4272: PDF builds of French projects have issues with XeTeX
• #5076: napoleon raises RuntimeError with python 3.7
• #5125: sphinx-build: Interface of sphinx:main() has changed
• sphinx-build: sphinx.cmd.build.main() refers sys.argv instead of given argument
• #5146: autosummary: warning is emitted when the first line of docstring ends with literal notation
• autosummary: warnings of autosummary indicates wrong location (refs: #5146)
• #5143: autodoc: crashed on inspecting dict like object which does not support sorting
• #5139: autodoc: Enum argument missing if it shares value with another
• #4946: py domain: rtype field could not handle “None” as a type
• #5176: LaTeX: indexing of terms containing @, !, or " fails
• #5161: html: crashes if copying static files are failed
• #5167: autodoc: Fix formatting type annotations for tuples with more than two arguments
• #3329: i18n: crashed by auto-symbol footnote references
• #5158: autosummary: module summary has been broken when it starts with heading
• #4717: latex: Compilation for German docs failed with LuaLaTeX and XeLaTeX
• #4459: duplicated labels detector does not work well in parallel build
• #4878: Crashed with extension which returns invalid metadata
• #4520: apidoc: folders with an empty __init__.py are no longer excluded from TOC
22.22.1 Deprecated
22.23.1 Dependencies
1.7.0b1
• Add packaging package
1.7.0b1
• #3668: The arguments has changed of main functions for each command
• #3893: Unknown html_theme_options throw warnings instead of errors
• #3927: Python parameter/variable types should match classes, not all objects
300 http://www.sphinx-doc.org/en/master/extdev/index.html#deprecated-apis
• #3962: sphinx-apidoc now recognizes given directory as an implicit namespace package when
--implicit-namespaces option given, not subdirectories of given directory.
• #3929: apidoc: Move sphinx.apidoc to sphinx.ext.apidoc
• #4226: apidoc: Generate new style makefile (make-mode)
• #4274: sphinx-build returns 2 as an exit code on argument error
• #4389: output directory will be created after loading extensions
• autodoc does not generate warnings messages to the generated document even if keep_warnings
is True. They are only emitted to stderr.
• shebang line is removed from generated conf.py
• #2557: autodoc: autodoc_mock_imports only mocks specified modules with their descendants.
It does not mock their ancestors. If you want to mock them, please specify the name of ancestors
explicitly.
• #3620: html theme: move DOCUMENTATION_OPTIONS to independent JavaScript file (refs: #4295)
• #4246: Limit width of text body for all themes. Configurable via theme options body_min_width
and body_max_width.
• #4771: apidoc: The exclude_patterns arguments are ignored if they are placed just after com-
mand line options
1.7.0b2
• #4467: html theme: Rename csss block to css
22.23.3 Deprecated
1.7.0b1
• using a string value for html_sidebars is deprecated and only list values will be accepted at 2.0.
• format_annotation() and formatargspec() is deprecated. Please use sphinx.util.
inspect.Signature instead.
• sphinx.ext.autodoc.AutodocReporter is replaced by sphinx.util.docutils.
switch_source_input() and now deprecated. It will be removed in Sphinx-2.0.
• sphinx.ext.autodoc.add_documenter() and AutoDirective._register is now depre-
cated. Please use app.add_autodocumenter() instead.
• AutoDirective._special_attrgetters is now deprecated. Please use app.
add_autodoc_attrgetter() instead.
1.7.0b1
• C++, handle decltype(auto).
• #2406: C++, add proper parsing of expressions, including linking of identifiers.
• C++, add a cpp:expr role for inserting inline C++ expressions or types.
• C++, support explicit member instantiations with shorthand template prefix
• C++, make function parameters linkable, like template params.
• #3638: Allow to change a label of reference to equation using math_eqref_format
• Now suppress_warnings accepts following configurations:
1.7.0b1
• Configuration variables
– html_use_smartypants
– latex_keep_old_macro_names
– latex_elements[‘footer’]
• utility methods of sphinx.application.Sphinx class
– buildername (property)
– _display_chunk()
– old_status_iterator()
– status_iterator()
– _directive_helper()
• utility methods of sphinx.environment.BuildEnvironment class
– currmodule (property)
– currclass (property)
• epub2 builder
• prefix and colorfunc parameter for warn()
• sphinx.util.compat module
• sphinx.util.nodes.process_only_nodes()
• LaTeX environment notice, use sphinxadmonition instead
• LaTeX \sphinxstylethead, use \sphinxstyletheadfamily
• C++, support of function concepts. Thanks to mickk-on-cpp.
• Not used and previously not documented LaTeX macros \shortversion and \setshortversion
1.7.0b1
• #3882: Update the order of files for HTMLHelp and QTHelp
• #3962: sphinx-apidoc does not recognize implicit namespace packages correctly
• #4094: C++, allow empty template argument lists.
• C++, also hyperlink types in the name of declarations with qualified names.
• C++, do not add index entries for declarations inside concepts.
• C++, support the template disambiguator for dependent names.
• #4314: For PDF ‘howto’ documents, numbering of code-blocks differs from the one of figures and
tables
• #4330: PDF ‘howto’ documents have an incoherent default LaTeX tocdepth counter setting
• #4198: autosummary emits multiple ‘autodoc-process-docstring’ event. Thanks to Joel Nothman.
• #4081: Warnings and errors colored the same when building
• latex: Do not display ‘Release’ label if release is not set
1.7.0b2
• #4415: autodoc classifies inherited classmethods as regular methods
• #4415: autodoc classifies inherited staticmethods as regular methods
• #4472: DOCUMENTATION_OPTIONS is not defined
• #4491: autodoc: prefer _MockImporter over other importers in sys.meta_path
• #4490: autodoc: type annotation is broken with python 3.7.0a4+
• utils package is no longer installed
• #3952: apidoc: module header is too escaped
• #4275: Formats accepted by sphinx.util.i18n.format_date are limited
• #4493: recommonmark raises AttributeError if AutoStructify enabled
• #4209: intersphinx: In link title, “v” should be optional if target has no version
• #4230: slowdown in writing pages with sphinx 1.6
• #4522: epub: document is not rebuilt even if config changed
1.7.0b3
• #4019: inheritance_diagram AttributeError stopping make process
• #4531: autosummary: methods are not treated as attributes
• #4538: autodoc: sphinx.ext.autodoc.Options has been moved
• #4539: autodoc emits warnings for partialmethods
• #4223: doctest: failing tests reported in wrong file, at wrong line
• i18n: message catalogs are not compiled if specific filenames are given for sphinx-build as argu-
ments (refs: #4560)
• #4027: sphinx.ext.autosectionlabel now expects labels to be the same as they are in the raw source;
no smart quotes, nothig fancy.
• #4581: apidoc: Excluded modules still included
22.23.7 Testing
1.7.0b1
• Add support for docutils 0.14
• Add tests for the sphinx.ext.inheritance_diagram extension.
• #4085: Failed PDF build from image in parsed-literal using :align: option
• #4100: Remove debug print from autodoc extension
• #3987: Changing theme from alabaster causes HTML build to fail
• #4096: C++, don’t crash when using the wrong role type. Thanks to mitya57.
• #4070, #4111: crashes when the warning message contains format strings (again)
• #4108: Search word highlighting breaks SVG images
• #3692: Unable to build HTML if writing .buildinfo failed
• #4152: HTML writer crashes if a field list is placed on top of the document
• #4063: Sphinx crashes when labeling directive .. todolist::
• #4134: [doc] docutils.conf is not documented explicitly
• #4169: Chinese language doesn’t trigger Chinese search automatically
• #1020: ext.todo todolist not linking to the page in pdflatex
• #3965: New quickstart generates wrong SPHINXBUILD in Makefile
• #3739: :module: option is ignored at content of pyobjects
• #4149: Documentation: Help choosing latex_engine
• #4090: [doc] latex_additional_files with extra LaTeX macros should not use .tex extension
• Failed to convert reST parser error to warning (refs: #4132)
• latex: hint that code-block continues on next page (refs: #3764, #3792)
• #3824: production lists apply smart quotes transform since Sphinx 1.6.1
• latex: fix \sphinxbfcode swallows initial space of argument
• #3878: Quotes in auto-documented class attributes should be straight quotes in PDF output
• #3881: LaTeX figure floated to next page sometimes leaves extra vertical whitespace
• #3885: duplicated footnotes raises IndexError
• #3873: Failure of deprecation warning mechanism of sphinx.util.compat.Directive
• #3874: Bogus warnings for “citation not referenced” for cross-file citations
• #3860: Don’t download images when builders not supported images
• #3860: Remote image URIs without filename break builders not supported remote images
• #3833: command line messages are translated unintentionally with language setting.
• #3840: make checking epub_uid strict
• #3851, #3706: Fix about box drawing characters for PDF output
• #3900: autosummary could not find methods
• #3902: Emit error if latex_documents contains non-unicode string in py2
22.30.1 Dependencies
1.6b1
• (updated) latex output is tested with Ubuntu trusty’s texlive packages (Feb. 2014) and earlier tex
installations may not be fully compliant, particularly regarding Unicode engines xelatex and lualatex
• (added) latexmk is required for make latexpdf on GNU/Linux and Mac OS X (refs: #3082)
1.6b1
• #1061, #2336, #3235: Now generation of autosummary doesn’t contain imported members by default.
Thanks to Luc Saffre.
• LaTeX \includegraphics command isn’t overloaded: only \sphinxincludegraphics has the
custom code to fit image to available width if oversized.
• The subclasses of sphinx.domains.Index should override generate() method. The default
implementation raises NotImplementedError
• LaTeX positioned long tables horizontally centered, and short ones flushed left (no text flow around
table.) The position now defaults to center in both cases, and it will obey Docutils 0.13 :align:
option (refs #3415, #3377)
• option directive also allows all punctuations for the option name (refs: #3366)
• #3413: if literalinclude’s :start-after: is used, make :lines: relative (refs #3412)
• literalinclude directive does not allow the combination of :diff: option and other options
(refs: #3416)
• LuaLaTeX engine uses fontspec like XeLaTeX. It is advised latex_engine = 'lualatex' be
used only on up-to-date TeX installs (refs #3070, #3466)
• latex_keep_old_macro_names default value has been changed from True to False. This
means that some LaTeX macros for styling are by default defined only with \sphinx.. prefixed
names. (refs: #3429)
• Footer “Continued on next page” of LaTeX longtable’s now not framed (refs: #3497)
• #3529: The arguments of BuildEnvironment.__init__ is changed
• #3082: Use latexmk for pdf (and dvi) targets (Unix-like platforms only)
• #3558: Emit warnings if footnotes and citations are not referenced. The warnings can be suppressed
by suppress_warnings.
• latex made available (non documented) colour macros from a file distributed with pdftex engine
for Plain TeX. This is removed in order to provide better support for multiple TeX engines. Only
interface from color or xcolor packages should be used by extensions of Sphinx latex writer. (refs
#3550)
• Configuration variables
– epub3_contributor
– epub3_description
– epub3_page_progression_direction
– html_translator_class
– html_use_modindex
– latex_font_size
– latex_paper_size
– latex_preamble
– latex_use_modindex
– latex_use_parts
• termsep node
• defindex.html template
• LDML format support in today, today_fmt and html_last_updated_fmt
• :inline: option for the directives of sphinx.ext.graphviz extension
• sphinx.ext.pngmath extension
• sphinx.util.compat.make_admonition()
1.6b1
• #3136: Add :name: option to the directives in sphinx.ext.graphviz
• LATEXMKOPTS variable for the Makefile in $BUILDDIR/latex to pass options to latexmk when
executing make latexpdf (refs #3695, #3720)
• Add a new event env-check-consistency to check consistency to extensions
• Add Domain.check_consistency() to check consistency
1.6b1
• literalinclude directive expands tabs after dedent-ing (refs: #3416)
• #1574: Paragraphs in table cell doesn’t work in Latex output
• #3288: Table with merged headers not wrapping text
• #3491: Inconsistent vertical space around table and longtable in PDF
• #3506: Depart functions for all admonitions in HTML writer now properly pass node to
depart_admonition.
• #2693: Sphinx latex style file wrongly inhibits colours for section headings for la-
tex+dvi(ps,pdf,pdfmx)
• C++, properly look up any references.
• #3624: sphinx.ext.intersphinx couldn’t load inventories compressed with gzip
• #3551: PDF information dictionary is lacking author and title data
• #3351: intersphinx does not refers context like py:module, py:class and so on.
• Fail to load template file if the parent template is archived
1.6b2
• #3661: sphinx-build crashes on parallel build
• #3669: gettext builder fails with “ValueError: substring not found”
• #3660: Sphinx always depends on sphinxcontrib-websupport and its dependencies
• #3472: smart quotes getting wrong in latex (at least with list of strings via autoattribute) (refs: #3345,
#3666)
1.6b3
• #3588: No compact (p tag) html output in the i18n document build even when
html_compact_lists is True.
• The make latexpdf from 1.6b1 (for GNU/Linux and Mac OS, using latexmk) aborted ear-
lier in case of LaTeX errors than was the case with 1.5 series, due to hard-coded usage of
--halt-on-error option (refs #3695)
• #3683: sphinx.websupport module is not provided by default
• #3683: Failed to build document if builder.css_file.insert() is called
• #3714: viewcode extension not taking highlight_code='none' in account
• #3698: Moving :doc: to std domain broke backwards compatibility
• #3633: misdetect unreferenced citations
1.6 final
• LaTeX tables do not allow multiple paragraphs in a header cell
• LATEXOPTS is not passed over correctly to pdflatex since 1.6b3
• #3532: Figure or literal block captions in cells of short tables cause havoc in PDF output
• Fix: in PDF captions of tables are rendered differently whether table is of longtable class or not (refs
#3686)
• #3725: Todo looks different from note in LaTeX output
• #3479: stub-columns have no effect in LaTeX output
• #3738: Nonsensical code in theming.py
• #3746: PDF builds fail with latexmk 4.48 or earlier due to undefined options -pdfxe and -pdflua
22.30.6 Deprecated
1.6b1
• sphinx.util.compat.Directive class is now deprecated. Please use instead docutils.
parsers.rst.Directive
• sphinx.util.compat.docutils_version is now deprecated
• #2367: Sphinx.warn(), Sphinx.info() and other logging methods are now deprecated. Please
use sphinx.util.logging (Logging API) instead.
• #3318: notice is now deprecated as LaTeX environment name and will be removed at Sphinx 1.7.
Extension authors please use sphinxadmonition instead (as Sphinx does since 1.5.)
• Sphinx.status_iterator() and Sphinx.old_status_iterator() is now deprecated.
Please use sphinx.util:status_iterator() instead.
• Sphinx._directive_helper() is deprecated. Please use sphinx.util.docutils.
directive_helper() instead.
• BuildEnvironment.set_warnfunc() is now deprecated
• Following methods of BuildEnvironment is now deprecated.
– BuildEnvironment.note_toctree()
– BuildEnvironment.get_toc_for()
– BuildEnvironment.get_toctree_for()
– BuildEnvironment.create_index()
Please use sphinx.environment.adapters modules instead.
• latex package footnote is not loaded anymore by its bundled replacement
footnotehyper-sphinx. The redefined macros keep the same names as in the original
package.
• #3429: deprecate config setting latex_keep_old_macro_names. It will be removed at 1.7, and
already its default value has changed from True to False.
• #3221: epub2 builder is deprecated
• #3254: sphinx.websupport is now separated into independent package;
sphinxcontrib-websupport. sphinx.websupport will be removed in Sphinx-2.0.
• #3628: sphinx_themes entry_point is deprecated. Please use sphinx.html_themes instead.
1.6b2
• #3662: builder.css_files is deprecated. Please use add_stylesheet() API instead.
1.6 final
• LaTeX \sphinxstylethead is deprecated at 1.6 and will be removed at 1.7. Please move cus-
tomization into new macro \sphinxstyletheadfamily.
22.30.7 Testing
1.6 final
• #3458: Add sphinx.testing (experimental)
• #3470: Make genindex support all kinds of letters, not only Latin ones
• #3356: Page layout for Japanese 'manual' docclass has a shorter text area
• #3394: When 'pointsize' is not 10pt, Japanese 'manual' document gets wrong PDF page
dimensions
• #3399: quickstart: conf.py was not overwritten by template
• #3366: option directive does not allow punctuations
• #3410: return code in release breaks html search
• #3427: autodoc: memory addresses are not stripped on Windows
• #3428: xetex build tests fail due to fontspec v2.6 defining \strong
• #3349: Result of IndexBuilder.load() is broken
• #3450:   is appeared in EPUB docs
• #3418: Search button is misaligned in nature and pyramid theme
• #3421: Could not translate a caption of tables
• #3552: linkcheck raises UnboundLocalError
• #3214: Allow to suppress “unknown mimetype” warnings from epub builder using
suppress_warnings.
1.5a1
• latex, package fancybox is not any longer a dependency of sphinx.sty
• Use 'locales' as a default value of locale_dirs
• latex, package ifthen is not any longer a dependency of sphinx.sty
• latex, style file does not modify fancyvrb’s Verbatim (also available as OriginalVerbatim) but uses
sphinxVerbatim for name of custom wrapper.
• latex, package newfloat is not used (and not included) anymore (ref #2660; it was used since 1.3.4
and shipped with Sphinx since 1.4).
• latex, literal blocks in tables do not use OriginalVerbatim but sphinxVerbatimintable which handles
captions and wraps lines (ref #2704).
• latex, replace pt by TeX equivalent bp if found in width or height attribute of an image.
• latex, if width or height attribute of an image is given with no unit, use px rather than ignore it.
• latex: Separate stylesheets of pygments to independent .sty file
• #2454: The filename of sourcelink is now changed. The value of html_sourcelink_suffix will
be appended to the original filename (like index.rst.txt).
• sphinx.util.copy_static_entry() is now deprecated. Use sphinx.util.fileutil.
copy_asset() instead.
• sphinx.util.osutil.filecopy() skips copying if the file has not been changed (ref: #2510,
#2753)
• Internet Explorer 6-8, Opera 12.1x or Safari 5.1+ support is dropped because jQuery version is up-
dated from 1.11.0 to 3.1.0 (ref: #2634, #2773)
• QtHelpBuilder doesn’t generate search page (ref: #2352)
• QtHelpBuilder uses nonav theme instead of default one to improve readability.
• latex: To provide good default settings to Japanese documents, Sphinx uses jreport and jsbook
as docclass if language is ja.
• sphinx-quickstart now allows a project version is empty
• Fix :download: role on epub/qthelp builder. They ignore the role because they don’t support it.
• sphinx.ext.viewcode doesn’t work on epub building by default. viewcode_enable_epub
option
• sphinx.ext.viewcode disabled on singlehtml builder.
• Use make-mode of sphinx-quickstart by default. To disable this, use -M option
• Fix genindex.html, Sphinx’s document template, link address to itself to satisfy xhtml standard.
• Use epub3 builder by default. And the old epub builder is renamed to epub2.
• Fix epub and epub3 builders that contained links to genindex even if epub_use_index =
False.
• html_translator_class is now deprecated. Use Sphinx.set_translator() API instead.
• Drop python 2.6 and 3.3 support
• Drop epub3 builder’s epub3_page_progression_direction option (use
epub3_writing_mode).
• #2877: Rename latex_elements['footer'] to latex_elements['atendofbody']
1.5a2
• #2983: Rename epub3_description and epub3_contributor to epub_description and
epub_contributor.
• Remove themes/basic/defindex.html; no longer used
• Sphinx does not ship anymore (but still uses) LaTeX style file fncychap
• #2435: Slim down quickstarted conf.py
• The sphinx.sty latex package does not load itself “hyperref”, as this is done later in the preamble
of the latex output via 'hyperref' key.
• Sphinx does not ship anymore a custom modified LaTeX style file tabulary. The non-modified
package is used.
• #3057: By default, footnote marks in latex PDF output are not preceded by a space anymore,
\sphinxBeforeFootnote allows user customization if needed.
• LaTeX target requires that option hyperfootnotes of package hyperref be left unchanged to its
default (i.e. true) (refs: #3022)
1.5 final
• #2986: themes/basic/defindex.html is now deprecated
• Emit warnings that will be deprecated in Sphinx 1.6 by default. Users can change the behavior by
setting the environment variable PYTHONWARNINGS. Please refer Deprecation Warnings.
• #2454: new JavaScript variable SOURCELINK_SUFFIX is added
22.38.2 Deprecated
1.5a1
• #2951: Add --implicit-namespaces PEP-0420 support to apidoc.
• #1958: C++, add configuration variable ‘cpp_index_common_prefix’ for removing prefixes from the
index text of C++ objects.
• C++, added concept directive. Thanks to mickk-on-cpp.
• C++, added support for template introduction syntax. Thanks to mickk-on-cpp.
• #2725: latex builder: allow to use user-defined template file (experimental)
• apidoc now avoids invalidating cached files by not writing to files whose content doesn’t change.
This can lead to significant performance wins if apidoc is run frequently.
• #2851: sphinx.ext.math emits missing-reference event if equation not found
• #1210: eqref role now supports cross reference
• #2892: Added -a (--append-syspath) option to sphinx-apidoc
• #1604: epub3 builder: Obey font-related CSS when viewing in iBooks.
• #646: option directive support ‘.’ character as a part of options
• Add document about kindlegen and fix document structure for it.
• #2474: Add intersphinx_timeout option to sphinx.ext.intersphinx
• #2926: EPUB3 builder supports vertical mode (epub3_writing_mode option)
• #2695: build_sphinx subcommand for setuptools handles exceptions as same as sphinx-build
does
• #326: numref role can also refer sections
• #2916: numref role can also refer caption as an its linktext
1.5a2
• #3008: linkcheck builder ignores self-signed certificate URL
• #3020: new 'geometry' key to latex_elements whose default uses LaTeX style file geometry.
sty to set page layout
• #2843: Add :start-at: and :end-at: options to literalinclude directive
• #2527: Add :reversed: option to toctree directive
• Add -t and -d option to sphinx-quickstart to support templating generated sphinx project.
• #3028: Add {path} and {basename} to the format of figure_language_filename
• new 'hyperref' key in the latex_elements dictionary (ref #3030)
• #3022: Allow code-blocks in footnotes for LaTeX PDF output
1.5b1
• #2513: A better default settings for XeLaTeX
• #3096: 'maxlistdepth' key to work around LaTeX list limitations
• #3060: autodoc supports documentation for attributes of Enum class. Now autodoc render just the
value of Enum attributes instead of Enum attribute representation.
• Add --extensions to sphinx-quickstart to support enable arbitrary extensions from com-
mand line (ref: #2904)
• #3104, #3122: 'sphinxsetup' for key=value styling of Sphinx LaTeX
• #3071: Autodoc: Allow mocked module decorators to pass-through functions unchanged
• #2495: linkcheck: Allow skipping anchor checking using linkcheck_anchors_ignore
• #3083: let Unicode no-break space act like LaTeX ~ (fixed #3019)
• #3116: allow word wrap in PDF output for inline literals (ref #3110)
• #930: sphinx-apidoc allow wildcards for excluding paths. Thanks to Nick Coghlan.
• #3121: add inlineliteralwraps option to control if inline literal word-wraps in latex
1.5 final
• #3095: Add tls_verify and tls_cacerts to support self-signed HTTPS servers in linkcheck and
intersphinx
• #2215: make.bat generated by sphinx-quickstart can be called from another dir. Thanks to Timotheus
Kampik.
• #3185: Add new warning type misc.highlighting_failure
1.5a1
• #2707: (latex) the column width is badly computed for tabular
• #2799: Sphinx installs roles and directives automatically on importing sphinx module. Now Sphinx
installs them on running application.
• sphinx.ext.autodoc crashes if target code imports * from mock modules by
autodoc_mock_imports.
• #1953: Sphinx.add_node does not add handlers the translator installed by
html_translator_class
• #1797: text builder inserts blank line on top
• #2894: quickstart main() doesn’t use argv argument
• #2874: gettext builder could not extract all text under the only directives
• #2485: autosummary crashes with multiple source_suffix values
• #1734: Could not translate the caption of toctree directive
• Could not translate the content of meta directive (ref: #1734)
• #2550: external links are opened in help viewer
• #2687: Running Sphinx multiple times produces ‘already registered’ warnings
1.5a2
• #2810: Problems with pdflatex in an Italian document
• Use latex_elements.papersize to specify papersize of LaTeX in Makefile
• #2988: linkcheck: retry with GET request if denied HEAD request
• #2990: linkcheck raises “Can’t convert ‘bytes’ object to str implicitly” error if linkcheck_anchors
enabled
• #3004: Invalid link types “top” and “up” are used
• #3009: Bad rendering of parsed-literals in LaTeX since Sphinx 1.4.4
• #3000: option directive generates invalid HTML anchors
• #2984: Invalid HTML has been generated if html_split_index enabled
• #2986: themes/basic/defindex.html should be changed for html5 friendly
• #2987: Invalid HTML has been generated if multiple IDs are assigned to a list
• #2891: HTML search does not provide all the results
22.38.5 Testing
• #2936: Fix doc/Makefile that can’t build man because doc/man exists
• #3058: Using the same ‘caption’ attribute in multiple ‘toctree’ directives results in warning / error
• #3068: Allow the ‘=’ character in the -D option of sphinx-build.py
• #3074: add_source_parser() crashes in debug mode
• #3135: sphinx.ext.autodoc crashes with plain Callable
• #3150: Fix query word splitter in JavaScript. It behaves as same as Python’s regular expression.
• #3093: gettext build broken on substituted images.
• #3093: gettext build broken on image node under note directive.
• imgmath: crashes on showing error messages if image generation failed
• #3117: LaTeX writer crashes if admonition is placed before first section title
• #3164: Change search order of sphinx.ext.inheritance_diagram
• #2931: code-block directive with same :caption: causes warning of duplicate target. Now
code-block and literalinclude does not define hyperlink target using its caption automat-
ically.
• #2962: latex: missing label of longtable
• #2968: autodoc: show-inheritance option breaks docstrings
• #2867: linkcheck builder crashes with six-1.4. Now Sphinx depends on six-1.5 or later
• latex, inclusion of non-inline images from image directive resulted in non-coherent whitespaces
depending on original image width; new behaviour by necessity differs from earlier one in some
cases. (ref: #2672)
• latex, use of \includegraphics to refer to Sphinx custom variant is deprecated; in fu-
ture it will revert to original LaTeX macro, custom one already has alternative name
\sphinxincludegraphics.
• new config option latex_keep_old_macro_names, defaults to True. If False, lets macros (for text
styling) be defined only with \sphinx-prefixed names
• latex writer allows user customization of “shadowed” boxes (topics), via three length variables.
• woff-format web font files now supported by the epub builder.
• jsdump fix for python 3: fixes the HTML search on python > 3
• #2676: (latex) Error with verbatim text in captions since Sphinx 1.4.4
• #2629: memoir class crashes LaTeX. Fixed by latex_keep_old_macro_names=False (ref 2675)
• #2684: sphinx.ext.intersphinx crashes with six-1.4.1
• #2679: float package needed for 'figure_align': 'H' latex option
• #2671: image directive may lead to inconsistent spacing in pdf
• #2705: toctree generates empty bullet_list if :titlesonly: specified
• #2479: sphinx.ext.viewcode uses python2 highlighter by default
• #2700: HtmlHelp builder has hard coded index.html
• latex, since 1.4.4 inline literal text is followed by spurious space
• #2722: C++, fix id generation for var/member declarations to include namespaces.
• latex, images (from image directive) in lists or quoted blocks did not obey indentation (fixed together
with #2671)
• #2733: since Sphinx-1.4.4 make latexpdf generates lots of hyperref warnings
• #2731: sphinx.ext.autodoc does not access propertymethods which raises any exceptions
• #2666: C++, properly look up nested names involving constructors.
• #2579: Could not refer a label including both spaces and colons via sphinx.ext.intersphinx
• #2718: Sphinx crashes if the document file is not readable
• #2699: hyperlinks in help HTMLs are broken if html_file_suffix is set
• #2723: extra spaces in latex pdf output from multirow cell
• #2735: latexpdf Underfull \hbox (badness 10000) warnings from title page
• #2667: latex crashes if resized images appeared in section title
• #2763: (html) Provide default value for required alt attribute for image tags of SVG source, required
to validate and now consistent w/ other formats.
• #2530: got “Counter too large” error on building PDF if large numbered footnotes existed in admo-
nitions
• width option of figure directive does not work if align option specified at same time (ref: #2595)
• #2590: The inputenc package breaks compiling under lualatex and xelatex
• #2540: date on latex front page use different font
• Suppress “document isn’t included in any toctree” warning if the document is included (ref: #2603)
• #2614: Some tables in PDF output will end up shifted if user sets non zero parindent in preamble
• #2602: URL redirection breaks the hyperlinks generated by sphinx.ext.intersphinx
• #2613: Show warnings if merged extensions are loaded
• #2619: make sure amstext LaTeX package always loaded (ref: d657225, 488ee52, 9d82cad and #2615)
• #2593: latex crashes if any figures in the table
– image.data_uri
– image.nonlocal_uri
• #2453: LaTeX writer allows page breaks in topic contents; and their horizontal extent now fits in the
line width (with shadow in margin). Also warning-type admonitions allow page breaks and their
vertical spacing has been made more coherent with the one for hint-type notices (ref #2446).
• #2459: the framing of literal code-blocks in LaTeX output (and not only the code lines themselves)
obey the indentation in lists or quoted blocks.
• #2343: the long source lines in code-blocks are wrapped (without modifying the line numbering) in
LaTeX output (ref #1534, #2304).
• The default format of today_fmt and html_last_updated_fmt is back to strftime format again.
Locale Date Markup Language is also supported for backward compatibility until Sphinx-1.5.
22.47.2 Translations
• #1498: manpage writer: don’t make whole of item in definition list bold if it includes strong node.
• #582: Remove hint message from quick search box for html output.
• #2378: Sphinx now bundles newfloat.sty
• #1913: C++, fix assert bug for enumerators in next-to-global and global scope.
• C++, fix parsing of ‘signed char’ and ‘unsigned char’ as types.
• C++, add missing support for ‘friend’ functions.
• C++, add missing support for virtual base classes (thanks to Rapptz).
• C++, add support for final classes.
• C++, fix parsing of types prefixed with ‘enum’.
• #2023: Dutch search support uses Danish stemming info.
• C++, add support for user-defined literals.
• #1804: Now html output wraps overflowed long-line-text in the sidebar. Thanks to Hassen ben
tanfous.
• #2183: Fix porterstemmer causes make json to fail.
• #1899: Ensure list is sent to OptParse.
• #2164: Fix wrong check for pdftex inside sphinx.sty (for graphicx package option).
• #2165, #2218: Remove faulty and non-need conditional from sphinx.sty.
• Fix broken LaTeX code is generated if unknown language is given
• #1944: Fix rst_prolog breaks file-wide metadata
• #2074: make gettext should use canonical relative paths for .pot. Thanks to anatoly techtonik.
• #2311: Fix sphinx.ext.inheritance_diagram raises AttributeError
• #2251: Line breaks in .rst files are transferred to .pot files in a wrong way.
• #794: Fix date formatting in latex output is not localized
• Remove image/gif from supported_image_types of LaTeX writer (#2272)
• Fix ValueError is raised if LANGUAGE is empty string
• Fix unpack warning is shown when the directives generated from Sphinx.add_crossref_type
is used
• The default highlight language is now default. This means that source code is highlighted as
Python 3 (which is mostly a superset of Python 2) if possible. To get the old behavior back, add
highlight_language = "python" to conf.py.
• #2329: Refresh environment forcedly if source directory has changed.
• #2331: Fix code-blocks are filled by block in dvi; remove xcdraw option from xcolor package
• Fix the confval type checker emits warnings if unicode is given to confvals which expects string
value
• #2360: Fix numref in LaTeX output is broken
• #2361: Fix additional paragraphs inside the “compound” directive are indented
• #2364: Fix KeyError ‘rootSymbol’ on Sphinx upgrade from older version.
• #2348: Move amsmath and amssymb to before fontpkg on LaTeX writer.
• #2368: Ignore emacs lock files like .#foo.rst by default.
• #2262: literal_block and its caption has been separated by pagebreak in LaTeX output.
• #2319: Fix table counter is overridden by code-block’s in LaTeX. Thanks to jfbu.
• Fix unpack warning if combined with 3rd party domain extensions.
• #1153: Fix figures in sidebar causes latex build error.
• #2358: Fix user-preamble could not override the tocdepth definition.
• #2358: Reduce tocdepth if part or chapter is used for top_sectionlevel
• #2351: Fix footnote spacing
• #2363: Fix toctree() in templates generates broken links in SingleHTMLBuilder.
• #2366: Fix empty hyperref is generated on toctree in HTML builder.
22.48.4 Documentation
• #1873, #1876, #2278: Add page_source_suffix html context variable. This should be introduced
with source_parsers feature. Thanks for Eric Holscher.
• Fix line numbers was not shown on warnings in LaTeX and texinfo builders
• Fix filenames were not shown on warnings of citations
• Fix line numbers was not shown on warnings in LaTeX and texinfo builders
• Fix line numbers was not shown on warnings of indices
• #2026: Fix LaTeX builder raises error if parsed-literal includes links
• #2243: Ignore strange docstring types for classes, do not crash
• #2247: Fix #2205 breaks make html for definition list with classifiers that contains regular-expression
like string
• #1565: Sphinx will now emit a warning that highlighting was skipped if the syntax is incorrect for
code-block, literalinclude and so on.
• #2211: Fix paragraphs in table cell doesn’t work in Latex output
• #2253: :pyobject: option of literalinclude directive can’t detect indented body block when
the block starts with blank or comment lines.
• Fix TOC is not shown when no :maxdepth: for toctrees (ref: #771)
• Fix warning message for :numref: if target is in orphaned doc (ref: #2244)
• #2134: Fix figure caption with reference causes latex build error
• #2094: Fix rubric with reference not working in Latex
• #2147: Fix literalinclude code in latex does not break in pages
• #1601, #2220: ‘any’ role breaks extended domains behavior. Affected extensions doesn’t sup-
port resolve_any_xref and resolve_xref returns problematic node instead of None. sphinxcontrib-
httpdomain is one of them.
• #2229: Fix no warning is given for unknown options
• #1976: Avoid “2.0” version of Babel because it doesn’t work with Windows environment.
• Add a “default.css” stylesheet (which imports “classic.css”) for compatibility
• #1788: graphviz extension raises exception when caption option is present.
• #1789: :pyobject: option of literalinclude directive includes following lines after class defi-
nitions
• #1790: literalinclude strips empty lines at the head and tail
• #1802: load plugin themes automatically when theme.conf use it as ‘inherit’. Thanks to Takayuki
Hirai.
• #1794: custom theme extended from alabaster or sphinx_rtd_theme can’t find base theme.
• #1834: compatibility for docutils-0.13: handle_io_errors keyword argument for docutils.io.FileInput
cause TypeError.
• #1823: ‘.’ as <module_path> for sphinx-apidoc cause an unfriendly error. Now ‘.’ is converted to
absolute path automatically.
• Fix a crash when setting up extensions which do not support metadata.
• #1784: Provide non-minified JS code in sphinx/search/non-minified-js/*.js
• #1822, #1892: Fix regression for #1061. autosummary can’t generate doc for imported members since
sphinx-1.3b3. Thanks to Eric Larson.
• #1793, #1819: “see also” misses a linebreak in text output. Thanks to Takayuki Hirai.
• #1780, #1866: “make text” shows “class” keyword twice. Thanks to Takayuki Hirai.
• #1871: Fix for LaTeX output of tables with one column and multirows.
• Work around the lack of the HTMLParserError exception in Python 3.5.
• #1949: Use safe_getattr in the coverage builder to avoid aborting with descriptors that have
custom behavior.
• #1915: Do not generate smart quotes in doc field type annotations.
• #1796: On py3, automated .mo building caused UnicodeDecodeError.
• #1923: Use babel features only if the babel latex element is nonempty.
• #1942: Fix a KeyError in websupport.
• #1903: Fix strange id generation for glossary terms.
• make text will crush if a definition list item has more than 1 classifiers as: term :
classifier1 : classifier2.
• #1855: make gettext generates broken po file for definition lists with classifier.
• #1869: Fix problems when dealing with files containing non-ASCII characters. Thanks to Marvin
Schmidt.
• #1798: Fix building LaTeX with references in titles.
• #1725: On py2 environment, doctest with using non-ASCII characters causes 'ascii' codec
can't decode byte exception.
• #1540: Fix RuntimeError with circular referenced toctree
• #1983: i18n translation feature breaks references which uses section name.
• #1990: Use caption of toctree to title of tableofcontents in LaTeX
• #1987: Fix ampersand is ignored in :menuselection: and :guilabel: on LaTeX builder
• #1994: More supporting non-standard parser (like recommonmark parser) for Translation and Web-
Support feature. Now node.rawsource is fall backed to node.astext() during docutils transforming.
• #1989: “make blahblah” on Windows indicate help messages for sphinx-build every time. It was
caused by wrong make.bat that generated by Sphinx-1.3.0/1.3.1.
• On Py2 environment, conf.py that is generated by sphinx-quickstart should have u prefixed config
value for ‘version’ and ‘release’.
• #2102: On Windows + Py3, using |today| and non-ASCII date format will raise UnicodeEncodeEr-
ror.
• #1974: UnboundLocalError: local variable ‘domain’ referenced before assignment when using any
role and sphinx.ext.intersphinx in same time.
• #2121: multiple words search doesn’t find pages when words across on the page title and the page
content.
• #1884, #1885: plug-in html themes cannot inherit another plug-in theme. Thanks to Suzumizaki.
• #1818: sphinx.ext.todo directive generates broken html class attribute as ‘admonition-‘ when
language is specified with non-ASCII linguistic area like ‘ru’ or ‘ja’. To fix this, now todo directive
can use :class: option.
• #2140: Fix footnotes in table has broken in LaTeX
• #2127: MecabBinder for html searching feature doesn’t work with Python 3. Thanks to Tomoko
Uchida.
• #1769: allows generating quickstart files/dirs for destination dir that doesn’t overwrite existent
files/dirs. Thanks to WAKAYAMA shirou.
• #1773: sphinx-quickstart doesn’t accept non-ASCII character as a option argument.
• #1766: the message “least Python 2.6 to run” is at best misleading.
• #1772: cross reference in docstrings like :param .write: breaks building.
• #1770, #1774: literalinclude with empty file occurs exception. Thanks to Takayuki Hirai.
• #1777: Sphinx 1.3 can’t load extra theme. Thanks to tell-k.
• #1776: source_suffix = ['.rst'] cause unfriendly error on prior version.
• #1771: automated .mo building doesn’t work properly.
• #1783: Autodoc: Python2 Allow unicode string in __all__. Thanks to Jens Hedegaard Nielsen.
• #1781: Setting html_domain_indices to a list raises a type check warnings.
• Roles ref, term and menusel now don’t generate emphasis305 nodes anymore. If you want to keep
italic style, adapt your stylesheet.
• Role numref uses %s as special character to indicate position of figure numbers instead # symbol.
• Add convenience directives and roles to the C++ domain: directive cpp:var as alias for
cpp:member, role :cpp:var as alias for :cpp:member, and role any for cross-reference to any
C++ declaraction. #1577, #1744
• The source_suffix config value can now be a list of multiple suffixes.
• Add the ability to specify source parsers by source suffix with the source_parsers config value.
• #1675: A new builder, AppleHelpBuilder, has been added that builds Apple Help Books.
• 1.3b3 change breaks a previous gettext output that contains duplicated msgid such as “foo bar” and
“version changes in 1.3: foo bar”.
• #1745: latex builder cause maximum recursion depth exceeded when a footnote has a footnote mark
itself.
• #1748: SyntaxError in sphinx/ext/ifconfig.py with Python 2.6.
• #1658, #1750: No link created (and warning given) if option does not begin with -, / or +. Thanks to
Takayuki Hirai.
305 http://docutils.sourceforge.net/docs/ref/rst/roles.html#emphasis
22.55.4 Documentation
– ‘raw’
– ‘image’
• #1227: Add html_scaled_image_link config option to conf.py, to control scaled image link.
• LaTeX writer now generates correct markup for cells spanning multiple rows.
• #1674: Do not crash if a module’s __all__ is not a list of strings.
• #1629: Use VerbatimBorderColor to add frame to code-block in LaTeX
• On windows, make-mode didn’t work on Win32 platform if sphinx was invoked as python
sphinx-build.py.
• #1687: linkcheck now treats 401 Unauthorized responses as “working”.
• #1690: toctrees with glob option now can also contain entries for single documents with explicit
title.
• #1591: html search results for C++ elements now has correct interpage links.
• bizstyle theme: nested long title pages make long breadcrumb that breaks page layout.
• bizstyle theme: all breadcrumb items become ‘Top’ on some mobile browser (iPhone5s safari).
• #1722: restore toctree() template function behavior that was changed at 1.3b1.
• #1732: i18n: localized table caption raises exception.
• #1718: :numref: does not work with capital letters in the label
• #1630: resolve CSS conflicts, div.container css target for literal block wrapper now renamed to
div.literal-block-wrapper.
• sphinx.util.pycompat has been restored in its backwards-compatibility; slated for removal in
Sphinx 1.4.
• #1719: LaTeX writer does not respect numref_format option in captions
• update bundled ez_setup.py for setuptools-7.0 that requires Python 2.6 or later.
• Added the any role that can be used to find a cross-reference of any type in any domain. Cus-
tom domains should implement the new Domain.resolve_any_xref method to make this work
properly.
• Exception logs now contain the last 10 messages emitted by Sphinx.
• Added support for extension versions (a string returned by setup(), these can be shown in the
traceback log files). Version requirements for extensions can be specified in projects using the new
needs_extensions config value.
• Changing the default role within a document with the default-role306 directive is now supported.
• PR#214: Added stemming support for 14 languages, so that the built-in document search can now
handle these. Thanks to Shibukawa Yoshiki.
• PR#296, PR#303, #76: numfig feature: Assign numbers to figures, tables and code-blocks. This
feature is configured with numfig, numfig_secnum_depth and numfig_format. Also numref
role is available. Thanks to Takeshi Komiya.
• PR#202: Allow “.” and “~” prefixed references in :param: doc fields for Python.
• PR#184: Add autodoc_mock_imports, allowing to mock imports of external modules that need
not be present when autodocumenting.
• #925: Allow list-typed config values to be provided on the command line, like -D key=val1,val2.
• #668: Allow line numbering of code-block and literalinclude directives to start at an arbitrary
line number, with a new lineno-start option.
• PR#172, PR#266: The code-block and literalinclude directives now can have a caption
option that shows a filename before the code in the output. Thanks to Nasimul Haque, Takeshi
Komiya.
• Prompt for the document language in sphinx-quickstart.
• PR#217: Added config values to suppress UUID and location information in generated gettext cata-
logs.
• PR#236, #1456: apidoc: Add a -M option to put module documentation before submodule documen-
tation. Thanks to Wes Turner and Luc Saffre.
• #1434: Provide non-minified JS files for jquery.js and underscore.js to clarify the source of the mini-
fied files.
• PR#252, #1291: Windows color console support. Thanks to meu31.
• PR#255: When generating latex references, also insert latex target/anchor for the ids defined on the
node. Thanks to Olivier Heurtier.
• PR#229: Allow registration of other translators. Thanks to Russell Sim.
• Add app.set_translator() API to register or override a Docutils translator class like
html_translator_class.
• PR#267, #1134: add ‘diff’ parameter to literalinclude. Thanks to Richard Wall and WAKAYAMA
shirou.
• PR#272: Added ‘bizstyle’ theme. Thanks to Shoji KUMAGAI.
• Automatically compile *.mo files from *.po files when gettext_auto_build is True (default)
and *.po is newer than *.mo file.
• #623: sphinx.ext.viewcode supports imported function/class aliases.
• PR#275: sphinx.ext.intersphinx supports multiple target for the inventory. Thanks to Brigitta
Sipocz.
306 http://docutils.sourceforge.net/docs/ref/rst/directives.html#default-role
• PR#261: Added the env-before-read-docs event that can be connected to modify the order of
documents before they are read by the environment.
• #1284: Program options documented with option can now start with +.
• PR#291: The caption of code-block is recognized as a title of ref target. Thanks to Takeshi Komiya.
• PR#298: Add new API: add_latex_package(). Thanks to Takeshi Komiya.
• #1344: add gettext_enables to enable extracting ‘index’ to gettext catalog output / applying
translation catalog to generated documentation.
• PR#301, #1583: Allow the line numbering of the directive literalinclude to match that of the
included file, using a new lineno-match option. Thanks to Jeppe Pihl.
• PR#299: add various options to sphinx-quickstart. Quiet mode option --quiet will skips wizard
mode. Thanks to WAKAYAMA shirou.
• #1623: Return types specified with :rtype: are now turned into links if possible.
– Updated documentation with elaborate description of what declarations are supported and
how the namespace declarations influence declaration and cross-reference lookup.
– Index names may be different now. Elements are indexed by their fully qualified name. It
should be rather easy to change this behaviour and potentially index by namespaces/classes as
well.
• PR#258, #939: Add dedent option for code-block and literalinclude. Thanks to Zafar Sid-
diqui.
• PR#268: Fix numbering section does not work at singlehtml mode. It still ad-hoc fix because there is
a issue that section IDs are conflicted. Thanks to Takeshi Komiya.
• PR#273, #1536: Fix RuntimeError with numbered circular toctree. Thanks to Takeshi Komiya.
• PR#274: Set its URL as a default title value if URL appears in toctree. Thanks to Takeshi Komiya.
• PR#276, #1381: rfc and pep roles support custom link text. Thanks to Takeshi Komiya.
• PR#277, #1513: highlights for function pointers in argument list of c:function. Thanks to Takeshi
Komiya.
• PR#278: Fix section entries were shown twice if toctree has been put under only directive. Thanks
to Takeshi Komiya.
• #1547: pgen2 tokenizer doesn’t recognize ... literal (Ellipsis for py3).
• PR#294: On LaTeX builder, wrap float environment on writing literal_block to avoid separation of
caption and body. Thanks to Takeshi Komiya.
• PR#295, #1520: make.bat latexpdf mechanism to cd back to the current directory. Thanks to
Peter Suter.
• PR#297, #1571: Add imgpath property to all builders. It make easier to develop builder extensions.
Thanks to Takeshi Komiya.
• #1584: Point to master doc in HTML “top” link.
• #1585: Autosummary of modules broken in Sphinx-1.2.3.
• #1610: Sphinx cause AttributeError when MeCab search option is enabled and python-mecab is not
installed.
• #1674: Do not crash if a module’s __all__ is not a list of strings.
• #1673: Fix crashes with nitpick_ignore and :doc: references.
• #1686: ifconfig directive doesn’t care about default config values.
• #1642: Fix only one search result appearing in Chrome.
22.58.4 Documentation
• #1518: sphinx-apidoc command now has a --version option to show version information and
exit
• New locales: Hebrew, European Portuguese, Vietnamese.
• #636: Keep straight single quotes in literal blocks in the LaTeX build.
• #1419: Generated i18n sphinx.js files are missing message catalog entries from ‘.js_t’ and ‘.html’. The
issue was introduced from Sphinx-1.1
• #1363: Fix i18n: missing python domain’s cross-references with currentmodule directive or current-
class directive.
• #1444: autosummary does not create the description from attributes docstring.
• #1457: In python3 environment, make linkcheck cause “Can’t convert ‘bytes’ object to str implicitly”
error when link target url has a hash part. Thanks to Jorge_C.
• #1467: Exception on Python3 if nonexistent method is specified by automethod
• #1441: autosummary can’t handle nested classes correctly.
• #1499: With non-callable setup in a conf.py, now sphinx-build emits a user-friendly error message.
• #1502: In autodoc, fix display of parameter defaults containing backslashes.
• #1226: autodoc, autosummary: importing setup.py by automodule will invoke setup process and
execute sys.exit(). Now sphinx avoids SystemExit exception and emits warnings without unex-
pected termination.
• #1503: py:function directive generate incorrectly signature when specifying a default parameter with
an empty list []. Thanks to Geert Jansen.
• #1508: Non-ASCII filename raise exception on make singlehtml, latex, man, texinfo and changes.
• #1531: On Python3 environment, docutils.conf with ‘source_link=true’ in the general section cause
type error.
• PR#270, #1533: Non-ASCII docstring cause UnicodeDecodeError when uses with inheritance-
diagram directive. Thanks to WAKAYAMA shirou.
• PR#281, PR#282, #1509: TODO extension not compatible with websupport. Thanks to Takeshi
Komiya.
• #1477: gettext does not extract nodes.line in a table or list.
• #1544: make text generates wrong table when it has empty table cells.
• #1522: Footnotes from table get displayed twice in LaTeX. This problem has been appeared from
Sphinx-1.2.1 by #949.
• #508: Sphinx every time exit with zero when is invoked from setup.py command. ex. python
setup.py build_sphinx -b doctest return zero even if doctest failed.
• PR#211: When checking for existence of the html_logo file, check the full relative path and not the
basename.
• PR#212: Fix traceback with autodoc and __init__ methods without docstring.
• PR#213: Fix a missing import in the setup command.
• #1357: Option names documented by option are now again allowed to not start with a dash or
slash, and referencing them will work correctly.
• #1358: Fix handling of image paths outside of the source directory when using the “wildcard” style
reference.
• #1374: Fix for autosummary generating overly-long summaries if first line doesn’t end with a period.
• #1383: Fix Python 2.5 compatibility of sphinx-apidoc.
• #1391: Actually prevent using “pngmath” and “mathjax” extensions at the same time in sphinx-
quickstart.
• #1386: Fix bug preventing more than one theme being added by the entry point mechanism.
• #1370: Ignore “toctree” nodes in text writer, instead of raising.
• #1364: Fix ‘make gettext’ fails when the ‘.. todolist::’ directive is present.
• #1367: Fix a change of PR#96 that break sphinx.util.docfields.Field.make_field interface/behavior for
item argument usage.
22.60.2 Documentation
• #1335: Fix autosummary template overloading with exclamation prefix like {% extends "!
autosummary/class.rst" %} cause infinite recursive function call. This was caused by PR#181.
• #1337: Fix autodoc with autoclass_content="both" uses useless object.__init__ docstring
when class does not have __init__. This was caused by a change for #1138.
• #1340: Can’t search alphabetical words on the HTML quick search generated with language=’ja’.
• #1319: Do not crash if the html_logo file does not exist.
• #603: Do not use the HTML-ized title for building the search index (that resulted in “literal” being
found on every page with a literal in the title).
• #751: Allow production lists longer than a page in LaTeX by using longtable.
• #764: Always look for stopwords lowercased in JS search.
• #814: autodoc: Guard against strange type objects that don’t have __bases__.
• #932: autodoc: Do not crash if __doc__ is not a string.
• #933: Do not crash if an option value is malformed (contains spaces but no option name).
• #908: On Python 3, handle error messages from LaTeX correctly in the pngmath extension.
• #943: In autosummary, recognize “first sentences” to pull from the docstring if they contain upper-
case letters.
• #923: Take the entire LaTeX document into account when caching pngmath-generated images. This
rebuilds them correctly when pngmath_latex_preamble changes.
• #901: Emit a warning when using docutils’ new “math” markup without a Sphinx math extension
active.
• #845: In code blocks, when the selected lexer fails, display line numbers nevertheless if configured.
• #929: Support parsed-literal blocks in LaTeX output correctly.
22.61.2 Documentation
• The Sphinx error log files will now include a list of the loaded extensions for help in debugging.
• PR#154: Remove “sphinx” prefix from LaTeX class name except ‘sphinxmanual’ and ‘sphinxhowto’.
Now you can use your custom document class without ‘sphinx’ prefix. Thanks to Erik B.
• #1265: Fix i18n: crash when translating a section name that is pointed to from a named target.
• A wrong condition broke the search feature on first page that is usually index.rst. This issue was
introduced in 1.2b1.
• #703: When Sphinx can’t decode filenames with non-ASCII characters, Sphinx now catches Uni-
codeError and will continue if possible instead of raising the exception.
• apidoc now ignores “_private” modules by default, and has an option -P to include them.
• apidoc now has an option to not generate headings for packages and modules, for the case that the
module docstring already includes a reST heading.
• PR#161: apidoc can now write each module to a standalone page instead of combining all modules
in a package on one page.
• Builders: rebuild i18n target document when catalog updated.
• Support docutils.conf ‘writers’ and ‘html4css1 writer’ section in the HTML writer. The latex, man-
page and texinfo writers also support their respective ‘writers’ sections.
• The new html_extra_path config value allows to specify directories with files that should be
copied directly to the HTML output directory.
• Autodoc directives for module data and attributes now support an annotation option, so that the
default display of the data/attribute value can be overridden.
• PR#136: Autodoc directives now support an imported-members option to include members im-
ported from different modules.
• New locales: Macedonian, Sinhala, Indonesian.
• Theme package collection by using setuptools plugin mechanism.
• PR#144, #1182: Force timezone offset to LocalTimeZone on POT-Creation-Date that was generated
by gettext builder. Thanks to masklinn and Jakub Wilk.
• #1173: Adjust setup.py dependencies because Jinja2 2.7 discontinued compatibility with Python <
3.3 and Python < 2.6. Thanks to Alexander Dupuy.
• #1185: Don’t crash when a Python module has a wrong or no encoding declared, and non-ASCII
characters are included.
• #1188: sphinx-quickstart raises UnicodeEncodeError if “Project version” includes non-ASCII charac-
ters.
• #1189: “Title underline is too short” WARNING is given when using fullwidth characters to “Project
name” on quickstart.
• #1190: Output TeX/texinfo/man filename has no basename (only extension) when using non-ASCII
characters in the “Project name” on quickstart.
• #1192: Fix escaping problem for hyperlinks in the manpage writer.
• #1193: Fix i18n: multiple link references in the same line return the same link.
• #1176: Fix i18n: footnote reference number missing for auto numbered named footnote and auto
symbol footnote.
• PR#146,#1172: Fix ZeroDivisionError in parallel builds. Thanks to tychoish.
• #1204: Fix wrong generation of links to local intersphinx targets.
• #1206: Fix i18n: gettext did not translate admonition directive’s title.
• #1232: Sphinx generated broken ePub files on Windows.
• #1259: Guard the debug output call when emitting events; to prevent the repr() implementation of
arbitrary objects causing build failures.
• #1142: Fix NFC/NFD normalizing problem of rst filename on Mac OS X.
• #1234: Ignoring the string consists only of white-space characters.
• Markup
– The toctree directive and the toctree() template function now have an includehidden
option that includes hidden toctree entries (bugs #790 and #1047). A bug in the maxdepth
option for the toctree() template function has been fixed (bug #1046).
– PR#99: Strip down seealso directives to normal admonitions. This removes their unusual CSS
classes (admonition-see-also), inconsistent LaTeX admonition title (“See Also” instead of “See
also”), and spurious indentation in the text builder.
• HTML builder
– #783: Create a link to full size image if it is scaled with width or height.
– #1067: Improve the ordering of the JavaScript search results: matches in titles come before
matches in full text, and object results are better categorized. Also implement a pluggable
search scorer.
– #1053: The “rightsidebar” and “collapsiblesidebar” HTML theme options now work together.
– Update to jQuery 1.7.1 and Underscore.js 1.3.1.
• Texinfo builder
– An “Index” node is no longer added when there are no entries.
– “deffn” categories are no longer capitalized if they contain capital letters.
– desc_annotation nodes are now rendered.
– strong and emphasis nodes are now formatted like literals. The reason for this is because
the standard Texinfo markup (*strong* and _emphasis_) resulted in confusing output due
to the common usage of using these constructs for documenting parameter names.
– Field lists formatting has been tweaked to better display “Info field lists”.
– system_message and problematic nodes are now formatted in a similar fashion as done
by the text builder.
– “en-dash” and “em-dash” conversion of hyphens is no longer performed in option directive
signatures.
– @ref is now used instead of @pxref for cross-references which prevents the word “see” from
being added before the link (does not affect the Info output).
– The @finalout command has been added for better TeX output.
– transition nodes are now formatted using underscores (“_”) instead of asterisks (“*”).
– The default value for the paragraphindent has been changed from 2 to 0 meaning that
paragraphs are no longer indented by default.
– #1110: A new configuration value texinfo_no_detailmenu has been added for controlling
whether a @detailmenu is added in the “Top” node’s menu.
– Detailed menus are no longer created except for the “Top” node.
– Fixed an issue where duplicate domain indices would result in invalid output.
• LaTeX builder:
– PR#115: Add 'transition' item in latex_elements for customizing how transitions are
displayed. Thanks to Jeff Klukas.
– PR#114: The LaTeX writer now includes the “cmap” package by default. The 'cmappkg' item
in latex_elements can be used to control this. Thanks to Dmitry Shachnev.
– The 'fontpkg' item in latex_elements now defaults to '' when the language uses the
Cyrillic script. Suggested by Dmitry Shachnev.
– The latex_documents, texinfo_documents, and man_pages configuration values will be
set to default values based on the master_doc if not explicitly set in conf.py. Previously, if
these values were not set, no output would be generated by their respective builders.
• Internationalization:
– Add i18n capabilities for custom templates. For example: The Sphinx reference documentation
in doc directory provides a sphinx.pot file with message strings from doc/_templates/*.
html when using make gettext.
– PR#61,#703: Add support for non-ASCII filename handling.
• Other builders:
– Added the Docutils-native XML and pseudo-XML builders. See XMLBuilder and
PseudoXMLBuilder.
– PR#45: The linkcheck builder now checks #anchors for existence.
– PR#123, #1106: Add epub_use_index configuration value. If provided, it will be used instead
of html_use_index for epub builder.
– PR#126: Add epub_tocscope configuration value. The setting controls the generation of the
epub toc. The user can now also include hidden toc entries.
– PR#112: Add epub_show_urls configuration value.
• Extensions:
– PR#52: special_members flag to autodoc now behaves like members.
– PR#47: Added sphinx.ext.linkcode extension.
– PR#25: In inheritance diagrams, the first line of the class docstring is now the tooltip for the
class.
• Command-line interfaces:
– PR#75: Added --follow-links option to sphinx-apidoc.
– #869: sphinx-build now has the option -T for printing the full traceback after an unhandled
exception.
– sphinx-build now supports the standard --help and --version options.
– sphinx-build now provides more specific error messages when called with invalid options or
arguments.
– sphinx-build now has a verbose option -v which can be repeated for greater effect. A single
occurrence provides a slightly more verbose output than normal. Two or more occurrences of
this option provides more detailed output which may be useful for debugging.
• Locales:
– PR#74: Fix some Russian translation.
– PR#54: Added Norwegian bokmaal translation.
– PR#35: Added Slovak translation.
– PR#28: Added Hungarian translation.
– #1113: Add Hebrew locale.
– #1097: Add Basque locale.
– #1037: Fix typos in Polish translation. Thanks to Jakub Wilk.
– #1012: Update Estonian translation.
• Optimizations:
– Speed up building the search index by caching the results of the word stemming routines. Saves
about 20 seconds when building the Python documentation.
– PR#108: Add experimental support for parallel building with a new sphinx-build -j op-
tion.
22.65.3 Documentation
• PR#88: Added the “Sphinx Developer’s Guide” (doc/devguide.rst) which outlines the basic
development process of the Sphinx project.
• Added a detailed “Installing Sphinx” document (doc/install.rst).
• PR#124: Fix paragraphs in versionmodified are ignored when it has no dangling paragraphs. Fix
wrong html output (nested <p> tag). Fix versionmodified is not translatable. Thanks to Nozomu
Kaneko.
• PR#111: Respect add_autodoc_attrgetter() even when inherited-members is set. Thanks to A. Jesse
Jiryu Davis.
• PR#97: Fix footnote handling in translated documents.
• Fix text writer not handling visit_legend for figure directive contents.
• Fix text builder not respecting wide/fullwidth characters: title underline width, table layout width
and text wrap width.
• Fix leading space in LaTeX table header cells.
• #1132: Fix LaTeX table output for multi-row cells in the first column.
• #1128: Fix Unicode errors when trying to format time strings with a non-standard locale.
• #1127: Fix traceback when autodoc tries to tokenize a non-Python file.
• #1126: Fix double-hyphen to en-dash conversion in wrong places such as command-line option
names in LaTeX.
• #1123: Allow whitespaces in filenames given to literalinclude.
• #1120: Added improvements about i18n for themes “basic”, “haiku” and “scrolls” that Sphinx built-
in. Thanks to Leonardo J. Caballero G.
• #1118: Updated Spanish translation. Thanks to Leonardo J. Caballero G.
• #1117: Handle .pyx files in sphinx-apidoc.
• #1112: Avoid duplicate download files when referenced from documents in different ways (abso-
lute/relative).
• #1111: Fix failure to find uppercase words in search when html_search_language is ‘ja’. Thanks
to Tomo Saito.
• #1108: The text writer now correctly numbers enumerated lists with non-default start values (based
on patch by Ewan Edwards).
• #1102: Support multi-context “with” statements in autodoc.
• #1090: Fix gettext not extracting glossary terms.
• #1074: Add environment version info to the generated search index to avoid compatibility issues
with old builds.
• #1070: Avoid un-pickling issues when running Python 3 and the saved environment was created
under Python 2.
• #1069: Fixed error caused when autodoc would try to format signatures of “partial” functions with-
out keyword arguments (patch by Artur Gaspar).
• #1062: sphinx.ext.autodoc use __init__ method signature for class signature.
• PR#40: Fix safe_repr function to decode bytestrings with non-ASCII characters correctly.
• PR#37: Allow configuring sphinx-apidoc via SPHINX_APIDOC_OPTIONS.
• PR#34: Restore Python 2.4 compatibility.
• PR#36: Make the “bibliography to TOC” fix in LaTeX output specific to the document class.
• #695: When the highlight language “python” is specified explicitly, do not try to parse the code to
recognize non-Python snippets.
• #859: Fix exception under certain circumstances when not finding appropriate objects to link to.
• #860: Do not crash when encountering invalid doctest examples, just emit a warning.
• #864: Fix crash with some settings of modindex_common_prefix.
• #862: Fix handling of -D and -A options on Python 3.
• #851: Recognize and warn about circular toctrees, instead of running into recursion errors.
22.67 Release 1.1.2 (Nov 1, 2011) – 1.1.1 is a silly version number any-
way!
• The py:module directive doesn’t output its platform option value anymore. (It was the only thing
that the directive did output, and therefore quite inconsistent.)
• Removed support for old dependency versions; requirements are now:
– Pygments >= 1.2
– Docutils >= 0.7
– Jinja2 >= 2.3
22.67. Release 1.1.2 (Nov 1, 2011) – 1.1.1 is a silly version number anyway! 383
Sphinx Documentation, Release 3.0.0+/0fb832baa
• #696, #666: Fix C++ array definitions and template arguments that are not type names.
• #633: Allow footnotes in section headers in LaTeX output.
• #616: Allow keywords to be linked via intersphinx.
• #613: Allow Unicode characters in production list token names.
• #720: Add dummy visitors for graphviz nodes for text and man.
• #704: Fix image file duplication bug.
• #677: Fix parsing of multiple signatures in C++ domain.
• #637: Ignore Emacs lock files when looking for source files.
• #544: Allow .pyw extension for importable modules in autodoc.
• #700: Use $(MAKE) in quickstart-generated Makefiles.
• #734: Make sidebar search box width consistent in browsers.
• #644: Fix spacing of centered figures in HTML output.
• #767: Safely encode SphinxError messages when printing them to sys.stderr.
• #611: Fix LaTeX output error with a document with no sections but a link target.
• Correctly treat built-in method descriptors as methods in autodoc.
• #706: Stop monkeypatching the Python textwrap module.
• #657: viewcode now works correctly with source files that have non-ASCII encoding.
• #669: Respect the noindex flag option in py:module directives.
• #675: Fix IndexErrors when including nonexisting lines with literalinclude.
• #676: Respect custom function/method parameter separator strings.
• #682: Fix JS incompatibility with jQuery >= 1.5.
• #693: Fix double encoding done when writing HTMLHelp .hhk files.
• #647: Do not apply SmartyPants in parsed-literal blocks.
• C++ domain now supports array definitions.
• #557: Add CSS styles required by docutils 0.7 for aligned images and figures.
• In the Makefile generated by LaTeX output, do not delete pdf files on clean; they might be required
images.
• #535: Fix LaTeX output generated for line blocks.
• #524: Open intersphinx inventories in binary mode on Windows, since version 2 contains zlib-
compressed data.
• #513: Allow giving non-local URIs for JavaScript files, e.g. in the JSMath extension.
• #512: Fix traceback when intersphinx_mapping is empty.
• #495: Fix internal vs. external link distinction for links coming from a docutils table-of-contents.
• #494: Fix the maxdepth option for the toctree() template callable when used with
collapse=True.
• #507: Fix crash parsing Python argument lists containing brackets in string literals.
• #501: Fix regression when building LaTeX docs with figures that don’t have captions.
• #510: Fix inheritance diagrams for classes that are not picklable.
• #497: Introduce separate background color for the sidebar collapse button, making it easier to see.
• #502, #503, #496: Fix small layout bugs in several builtin themes.
• #490: Fix cross-references to objects of types added by the add_object_type() API function.
• Fix handling of doc field types for different directive types.
• Allow breaking long signatures, continuing with backlash-escaped newlines.
• Fix unwanted styling of C domain references (because of a namespace clash with Pygments styles).
• Allow references to PEPs and RFCs with explicit anchors.
• #471: Fix LaTeX references to figures.
• #482: When doing a non-exact search, match only the given type of object.
• #481: Apply non-exact search for Python reference targets with .name for modules too.
• #484: Fix crash when duplicating a parameter in an info field list.
• #487: Fix setting the default role to one provided by the oldcmarkup extension.
• #488: Fix crash when json-py is installed, which provides a json module but is incompatible to
simplejson.
• #480: Fix handling of target naming in intersphinx.
• #486: Fix removal of ! for all cross-reference roles.
• #470: Fix generated target names for reST domain objects; they are not in the same namespace.
• #266: Add Bengali language.
• #473: Fix a bug in parsing JavaScript object names.
• #474: Fix building with SingleHTMLBuilder when there is no toctree.
• Fix display names for objects linked to by intersphinx with explicit targets.
• Fix building with the JSON builder.
• Fix hyperrefs in object descriptions for LaTeX.
• Support for domains has been added. A domain is a collection of directives and roles that all describe
objects belonging together, e.g. elements of a programming language. A few builtin domains are
provided:
– Python
– C
– C++
– JavaScript
– reStructuredText
• The old markup for defining and linking to C directives is now deprecated. It will not work anymore
in future versions without activating the oldcmarkup extension; in Sphinx 1.0, it is activated by
default.
• Removed support for old dependency versions; requirements are now:
– docutils >= 0.5
– Jinja2 >= 2.2
• Removed deprecated elements:
– exclude_dirs config value
– sphinx.builder module
• General:
– Added a “nitpicky” mode that emits warnings for all missing references. It is activated by the
sphinx-build -n command-line switch or the nitpicky config value.
– Added latexpdf target in quickstart Makefile.
• Markup:
– The menuselection and guilabel roles now support ampersand accelerators.
– New more compact doc field syntax is now recognized: :param type name:
description.
– Added tab-width option to literalinclude directive.
– Added titlesonly option to toctree directive.
– Added the prepend and append options to the literalinclude directive.
– #284: All docinfo metadata is now put into the document metadata, not just the author.
– The ref role can now also reference tables by caption.
– The include308 directive now supports absolute paths, which are interpreted as relative to the
source directory.
– In the Python domain, references like :func:`.name` now look for matching names with any
prefix if no direct match is found.
• Configuration:
– Added rst_prolog config value.
– Added html_secnumber_suffix config value to control section numbering format.
– Added html_compact_lists config value to control docutils’ compact lists feature.
– The html_sidebars config value can now contain patterns as keys, and the values can be lists
that explicitly select which sidebar templates should be rendered. That means that the builtin
sidebar contents can be included only selectively.
– html_static_path can now contain single file entries.
– The new universal config value exclude_patterns makes the old unused_docs,
exclude_trees and exclude_dirnames obsolete.
– Added html_output_encoding config value.
– Added the latex_docclass config value and made the “twoside” documentclass option over-
ridable by “oneside”.
– Added the trim_doctest_flags config value, which is true by default.
– Added html_show_copyright config value.
– Added latex_show_pagerefs and latex_show_urls config values.
– The behavior of html_file_suffix changed slightly: the empty string now means “no suf-
fix” instead of “default suffix”, use None for “default suffix”.
• New builders:
– Added a builder for the Epub format.
– Added a builder for manual pages.
– Added a single-file HTML builder.
• HTML output:
– Inline roles now get a CSS class with their name, allowing styles to customize their appearance.
Domain-specific roles get two classes, domain and domain-rolename.
– References now get the class internal if they are internal to the whole project, as opposed to
internal to the current page.
– External references can be styled differently with the new externalrefs theme option for the
default theme.
308 http://docutils.sourceforge.net/docs/ref/rst/directives.html#include
– In the default theme, the sidebar can experimentally now be made collapsible using the new
collapsiblesidebar theme option.
– #129: Toctrees are now wrapped in a div tag with class toctree-wrapper in HTML output.
– The toctree callable in templates now has a maxdepth keyword argument to control the
depth of the generated tree.
– The toctree callable in templates now accepts a titles_only keyword argument.
– Added htmltitle block in layout template.
– In the JavaScript search, allow searching for object names including the module name, like
sys.argv.
– Added new theme haiku, inspired by the Haiku OS user guide.
– Added new theme nature.
– Added new theme agogo, created by Andi Albrecht.
– Added new theme scrolls, created by Armin Ronacher.
– #193: Added a visitedlinkcolor theme option to the default theme.
– #322: Improved responsiveness of the search page by loading the search index asynchronously.
• Extension API:
– Added html-collect-pages.
– Added needs_sphinx config value and require_sphinx() application API method.
– #200: Added add_stylesheet() application API method.
• Extensions:
– Added the viewcode extension.
– Added the extlinks extension.
– Added support for source ordering of members in autodoc, with autodoc_member_order =
'bysource'.
– Added autodoc_default_flags config value, which can be used to select default flags for
all autodoc directives.
– Added a way for intersphinx to refer to named labels in other projects, and to specify the project
you want to link to.
– #280: Autodoc can now document instance attributes assigned in __init__ methods.
– Many improvements and fixes to the autosummary extension, thanks to Pauli Virtanen.
– #309: The graphviz extension can now output SVG instead of PNG images, controlled by the
graphviz_output_format config value.
– Added alt option to graphviz extension directives.
– Added exclude argument to autodoc.between().
• Translations:
– Added Croatian translation, thanks to Bojan Mihelač.
– Added Turkish translation, thanks to Firat Ozgul.
– Added Catalan translation, thanks to Pau Fernández.
– Added simplified Chinese translation.
– Added Danish translation, thanks to Hjorth Larsen.
The changelog for versions before 1.0 can be found in the file CHANGES.old in the source distribution or
at GitHub309 .
309 https://github.com/sphinx-doc/sphinx/raw/master/CHANGES.old
TWENTYTHREE
This is an (incomplete) alphabetic list of projects that use Sphinx or are experimenting with using it for
their documentation. If you like to be included, please mail to the Google group310 .
I’ve grouped the list into sections to make it easier to find interesting examples.
• Alabaster311
• Blinker312
• Calibre313
• Click314 (customized)
• coala315 (customized)
• CodePy316
• Eve317 (Python REST API framework)
• Fabric318
• Fityk319
• Flask320
• Flask-OpenID321
• Invoke322
• Jinja323
• Lino324 (customized)
310 https://groups.google.com/forum/#!forum/sphinx-users
311 https://alabaster.readthedocs.io/
312 https://pythonhosted.org/blinker/
313 https://manual.calibre-ebook.com/
314 http://click.pocoo.org/
315 https://docs.coala.io/
316 https://documen.tician.de/codepy/
317 https://docs.python-eve.org/
318 https://docs.fabfile.org/
319 https://fityk.nieto.pl/
320 http://flask.pocoo.org/docs/
321 https://pythonhosted.org/Flask-OpenID/
322 https://docs.pyinvoke.org/
323 http://jinja.pocoo.org/docs/
324 http://www.lino-framework.org/
393
Sphinx Documentation, Release 3.0.0+/0fb832baa
• marbl325
• MDAnalysis326 (customized)
• MeshPy327
• Molecule328
• PyCUDA329
• PyOpenCL330
• PyLangAcq331
• pytest332 (customized)
• python-apt333
• PyVisfile334
• Requests335
• searx336
• Spyder337 (customized)
• Tablib338
• urllib3339 (customized)
• Werkzeug340 (customized)
• Blender API347
• Bugzilla348
• Buildbot349
• CMake350 (customized)
• Chaco351 (customized)
• CORE352
• CORE Python modules353
• Cormoran354
• DEAP355 (customized)
• Director356
• EZ-Draw357 (customized)
• F2py358
• Generic Mapping Tools (GMT)359 (customized)
• Genomedata360
• GetFEM++361 (customized)
• Glasgow Haskell Compiler362 (customized)
• Grok363 (customized)
• GROMACS364
• GSL Shell365
• Hands-on Python Tutorial366
• Kaa367 (customized)
• Leo368
• LEPL369 (customized)
• Mayavi370 (customized)
347 https://docs.blender.org/api/current/
348 https://bugzilla.readthedocs.io/
349 https://docs.buildbot.net/latest/
350 https://cmake.org/documentation/
351 https://docs.enthought.com/chaco/
352 https://downloads.pf.itd.nrl.navy.mil/docs/core/core-html/
353 https://downloads.pf.itd.nrl.navy.mil/docs/core/core-python-html/
354 http://cormoran.nhopkg.org/docs/
355 https://deap.readthedocs.io/
356 https://pythonhosted.org/director/
357 https://pageperso.lif.univ-mrs.fr/~edouard.thiel/ez-draw/doc/en/html/ez-manual.html
358 http://f2py.sourceforge.net/docs/
359 https://gmt.soest.hawaii.edu/doc/latest/
360 https://noble.gs.washington.edu/proj/genomedata/doc/1.3.3/
361 http://getfem.org/
362 https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/
363 http://grok.zope.org/doc/current/
364 http://manual.gromacs.org/documentation/
365 https://www.nongnu.org/gsl-shell/
366 https://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/
367 https://api.freevo.org/kaa-base/
368 https://leoeditor.com/
369 http://www.acooke.org/lepl/
370 https://docs.enthought.com/mayavi/mayavi/
• MediaGoblin371 (customized)
• mpmath372
• OpenCV373 (customized)
• OpenEXR374
• OpenGDA375
• Peach^3376 (customized)
• Plone377 (customized)
• PyEMD378
• Pyevolve379
• Pygame380 (customized)
• PyMQI381
• PyQt4382 (customized)
• PyQt5383 (customized)
• Python 2384
• Python 3385 (customized)
• Python Packaging Authority386 (customized)
• Ring programming language387 (customized)
• SageMath388 (customized)
• Segway389
• simuPOP390 (customized)
• Sprox391 (customized)
• SymPy392
• TurboGears393 (customized)
• tvtk394
371 https://mediagoblin.readthedocs.io/
372 http://mpmath.org/doc/current/
373 https://docs.opencv.org/
374 http://excamera.com/articles/26/doc/index.html
375 http://www.opengda.org/gdadoc/html/
376 https://peach3.nl/doc/latest/userdoc/
377 https://docs.plone.org/
378 https://pyemd.readthedocs.io/
379 http://pyevolve.sourceforge.net/
380 https://www.pygame.org/docs/
381 https://pythonhosted.org/pymqi/
382 http://pyqt.sourceforge.net/Docs/PyQt4/
383 http://pyqt.sourceforge.net/Docs/PyQt5/
384 https://docs.python.org/2/
385 https://docs.python.org/3/
386 https://www.pypa.io/
387 http://ring-lang.sourceforge.net/doc/
388 https://doc.sagemath.org/
389 https://noble.gs.washington.edu/proj/segway/doc/1.1.0/segway.html
390 http://simupop.sourceforge.net/manual_release/build/userGuide.html
391 http://sprox.org/
392 https://docs.sympy.org/
393 https://turbogears.readthedocs.io/
394 https://docs.enthought.com/mayavi/tvtk/
• ABRT402
• cartopy403
• Jython404
• LLVM405
• Matplotlib406
• MDAnalysis Tutorial407
• NetworkX408
• PyCantonese409
• Pyre410
• pySPACE411
• Pysparse412
• PyTango413
• Python Wild Magic414 (customized)
• RDKit415
• Reteisi416 (customized)
395 https://www.varnish-cache.org/docs/
396 https://waf.io/apidocs/
397 https://wxpython.org/Phoenix/docs/html/main.html
398 http://yum.baseurl.org/api/yum/
399 https://www.ibiblio.org/paulcarduner/z3ctutorial/
400 https://pythonhosted.org/zc.async/
401 https://docs.zope.org/zope2/
402 https://abrt.readthedocs.io/
403 https://scitools.org.uk/cartopy/docs/latest/
404 http://www.jython.org/docs/
405 https://llvm.org/docs/
406 https://matplotlib.org/
407 https://www.mdanalysis.org/MDAnalysisTutorial/
408 https://networkx.github.io/
409 http://pycantonese.org/
410 http://docs.danse.us/pyre/sphinx/
411 https://pyspace.github.io/pyspace/
412 http://pysparse.sourceforge.net/
413 https://www.esrf.eu/computing/cs/tango/tango_doc/kernel_doc/pytango/latest/
414 https://vmlaker.github.io/pythonwildmagic/
415 https://www.rdkit.org/docs/
416 http://www.reteisi.org/contents.html
• Sqlkit417 (customized)
• Turbulenz418
• Alembic419
• Cython420
• easybuild421
• jsFiddle422
• libLAS423 (customized)
• Lmod424
• MapServer425 (customized)
• Pandas426
• pyglet427 (customized)
• Setuptools428
• Spring Python429
• StatsModels430 (customized)
• Sylli431
• Breathe432 (haiku)
• MPipe433 (sphinx13)
• NLTK434 (agogo)
• Programmieren mit PyGTK und Glade (German)435 (agogo, customized)
• PyPubSub436 (bizstyle)
417 http://sqlkit.argolinux.org/
418 http://docs.turbulenz.com/
419 http://alembic.zzzcomputing.com/
420 http://docs.cython.org/
421 https://easybuild.readthedocs.io/
422 http://doc.jsfiddle.net/
423 https://www.liblas.org/
424 https://lmod.readthedocs.io/
425 https://mapserver.org/
426 https://pandas.pydata.org/pandas-docs/stable/
427 https://pyglet.readthedocs.io/
428 https://setuptools.readthedocs.io/
429 https://docs.spring.io/spring-python/1.2.x/sphinx/html/
430 https://www.statsmodels.org/
431 http://sylli.sourceforge.net/
432 https://breathe.readthedocs.io/
433 https://vmlaker.github.io/mpipe/
434 https://www.nltk.org/
435 https://www.florian-diesch.de/doc/python-und-glade/online/
436 https://pypubsub.readthedocs.io/
• Pylons437 (pyramid)
• Pyramid web framework438 (pyramid)
• Sphinx439 (sphinx13) :-)
• Valence440 (haiku, customized)
• Annotator441
• Ansible442 (customized)
• Arcade443
• aria2444
• ASE445
• Autofac446
• BigchainDB447
• Blender Reference Manual448
• Blocks449
• bootstrap-datepicker450
• Certbot451
• Chainer452 (customized)
• CherryPy453
• cloud-init454
• CodeIgniter455
• Conda456
• Corda457
• Dask458
437 https://docs.pylonsproject.org/projects/pylons-webframework/
438 https://docs.pylonsproject.org/projects/pyramid/
439 http://www.sphinx-doc.org/
440 https://docs.valence.desire2learn.com/
441 http://docs.annotatorjs.org/
442 https://docs.ansible.com/
443 http://arcade.academy/
444 https://aria2.github.io/manual/en/html/
445 https://wiki.fysik.dtu.dk/ase/
446 http://docs.autofac.org/
447 https://docs.bigchaindb.com/
448 https://docs.blender.org/manual/
449 https://blocks.readthedocs.io/
450 https://bootstrap-datepicker.readthedocs.io/
451 https://letsencrypt.readthedocs.io/
452 https://docs.chainer.org/
453 https://docs.cherrypy.org/
454 https://cloudinit.readthedocs.io/
455 https://www.codeigniter.com/user_guide/
456 https://conda.io/docs/
457 https://docs.corda.net/
458 https://dask.pydata.org/
• Databricks459 (customized)
• Dataiku DSS460
• DNF461
• edX462
• Electrum463
• Elemental464
• ESWP3465
• Ethereum Homestead466
• Exhale467
• Faker468
• Fidimag469
• Flake8470
• Flatpak471
• FluidDyn472
• Fluidsim473
• Gallium474
• GeoNode475
• Glances476
• Godot477
• Graylog478
• GPAW479 (customized)
• HDF5 for Python (h5py)480
• Hyperledger Fabric481
• Hyperledger Sawtooth482
459 https://docs.databricks.com/
460 https://doc.dataiku.com/
461 https://dnf.readthedocs.io/
462 https://docs.edx.org/
463 http://docs.electrum.org/
464 http://libelemental.org/documentation/dev/
465 https://eswp3.readthedocs.io/
466 http://www.ethdocs.org/
467 https://exhale.readthedocs.io/
468 https://faker.readthedocs.io/
469 https://fidimag.readthedocs.io/
470 http://flake8.pycqa.org/
471 http://docs.flatpak.org/
472 https://fluiddyn.readthedocs.io/
473 https://fluidsim.readthedocs.io/
474 https://gallium.readthedocs.io/
475 http://docs.geonode.org/
476 https://glances.readthedocs.io/
477 https://godot.readthedocs.io/
478 http://docs.graylog.org/
479 https://wiki.fysik.dtu.dk/gpaw/
480 http://docs.h5py.org/
481 https://hyperledger-fabric.readthedocs.io/
482 https://intelledger.github.io/
• IdentityServer483
• Idris484
• javasphinx485
• Julia486
• Jupyter Notebook487
• Lasagne488
• latexindent.pl489
• Learning Apache Spark with Python490
• Linguistica491
• Linux kernel492
• Mailman493
• MathJax494
• MDTraj495 (customized)
• micca - MICrobial Community Analysis496
• MicroPython497
• Minds498 (customized)
• Mink499
• Mockery500
• mod_wsgi501
• MoinMoin502
• Mopidy503
• MyHDL504
• Nextflow505
• NICOS506 (customized)
483 http://docs.identityserver.io/
484 http://docs.idris-lang.org/
485 https://bronto-javasphinx.readthedocs.io/
486 https://julia.readthedocs.io/
487 https://jupyter-notebook.readthedocs.io/
488 https://lasagne.readthedocs.io/
489 https://latexindentpl.readthedocs.io/
490 https://runawayhorse001.github.io/LearningApacheSpark
491 https://linguistica-uchicago.github.io/lxa5/
492 https://www.kernel.org/doc/html/latest/index.html
493 http://docs.list.org/
494 https://docs.mathjax.org/
495 http://mdtraj.org/latest/
496 https://micca.readthedocs.io/
497 https://docs.micropython.org/
498 https://www.minds.org/docs/
499 http://mink.behat.org/
500 http://docs.mockery.io/
501 https://modwsgi.readthedocs.io/
502 https://moin-20.readthedocs.io/
503 https://docs.mopidy.com/
504 http://docs.myhdl.org/
505 https://www.nextflow.io/docs/latest/index.html
506 https://forge.frm2.tum.de/nicos/doc/nicos-master/
• Pelican507
• picamera508
• Pillow509
• pip510
• Paver511
• peewee512
• Phinx513
• phpMyAdmin514
• PROS515 (customized)
• Pushkin516
• Pweave517
• PyPy518
• python-sqlparse519
• PyVISA520
• Read The Docs521
• Free your information from their silos (French)522 (customized)
• Releases Sphinx extension523
• Qtile524
• Quex525
• QuTiP526
• Satchmo527
• Scapy528
• SimGrid529
• SimPy530
507 http://docs.getpelican.com/
508 https://picamera.readthedocs.io/
509 https://pillow.readthedocs.io/
510 https://pip.pypa.io/
511 https://paver.readthedocs.io/
512 http://docs.peewee-orm.com/
513 http://docs.phinx.org/
514 https://docs.phpmyadmin.net/
515 https://pros.cs.purdue.edu/v5/
516 http://docs.pushkin.io/
517 http://mpastell.com/pweave/
518 http://doc.pypy.org/
519 https://sqlparse.readthedocs.io/
520 https://pyvisa.readthedocs.io/
521 https://docs.readthedocs.io/
522 http://redaction-technique.org/
523 https://releases.readthedocs.io/
524 http://docs.qtile.org/
525 http://quex.sourceforge.net/doc/html/main.html
526 http://qutip.org/docs/latest/
527 http://docs.satchmoproject.com/
528 https://scapy.readthedocs.io/
529 http://simgrid.gforge.inria.fr/simgrid/latest/doc/
530 https://simpy.readthedocs.io/
• six531
• SlamData532
• Solidity533
• Sonos Controller (SoCo)534
• Sphinx AutoAPI535
• sphinx-argparse536
• Sphinx-Gallery537 (customized)
• Sphinx with Github Webpages538
• SpotBugs539
• StarUML540
• Sublime Text Unofficial Documentation541
• SunPy542
• Sylius543
• Syncthing544
• Tango Controls545 (customized)
• Topshelf546
• Theano547
• ThreatConnect548
• Tuleap549
• TYPO3550 (customized)
• Veyon551
• uWSGI552
• virtualenv553
• Wagtail554
531 https://six.readthedocs.io/
532 https://newdocs.slamdata.com
533 https://solidity.readthedocs.io/
534 http://docs.python-soco.com/
535 https://sphinx-autoapi.readthedocs.io/
536 https://sphinx-argparse.readthedocs.io/
537 https://sphinx-gallery.readthedocs.io/
538 https://runawayhorse001.github.io/SphinxGithub
539 https://spotbugs.readthedocs.io/
540 https://docs.staruml.io/
541 http://docs.sublimetext.info/
542 https://docs.sunpy.org/
543 http://docs.sylius.org/
544 https://docs.syncthing.net/
545 https://tango-controls.readthedocs.io/
546 http://docs.topshelf-project.com/
547 http://www.deeplearning.net/software/theano/
548 https://docs.threatconnect.com/
549 https://tuleap.net/doc/en/
550 https://docs.typo3.org/
551 https://docs.veyon.io/
552 https://uwsgi-docs.readthedocs.io/
553 https://virtualenv.readthedocs.io/
554 https://docs.wagtail.io/
• Bootstrap Theme560
• C/C++ Software Development with Eclipse561
• Dataverse562
• e-cidadania563
• Hangfire564
• Hedge565
• ObsPy566
• Open Dylan567
• OPNFV568
• Pootle569
• PyUblas570
• seaborn571
• Apache Cassandra572
• Astropy573
• Bokeh574
555 http://docs.w3af.org/
556 https://docs.weblate.org/
557 https://x265.readthedocs.io/
558 https://zeronet.readthedocs.io/
559 https://zulip.readthedocs.io/
560 https://ryan-roemer.github.io/sphinx-bootstrap-theme/
561 https://eclipsebook.in/
562 http://guides.dataverse.org/
563 https://e-cidadania.readthedocs.io/
564 http://docs.hangfire.io/
565 https://documen.tician.de/hedge/
566 https://docs.obspy.org/
567 https://opendylan.org/documentation/
568 https://docs.opnfv.org/
569 http://docs.translatehouse.org/projects/pootle/
570 https://documen.tician.de/pyublas/
571 https://seaborn.pydata.org/
572 https://cassandra.apache.org/doc/
573 http://docs.astropy.org/
574 https://bokeh.pydata.org/
• Boto 3575
• CakePHP576
• CasperJS577
• Ceph578
• Chef579
• CKAN580
• Confluent Platform581
• Django582
• Doctrine583
• Enterprise Toolkit for Acrobat products584
• Gameduino585
• gensim586
• GeoServer587
• gevent588
• GHC - Glasgow Haskell Compiler589
• Guzzle590
• H2O.ai591
• Heka592
• Istihza (Turkish Python documentation project)593
• Kombu594
• Lasso595
• Mako596
• MirrorBrain597
• MongoDB598
575 https://boto3.readthedocs.io/
576 https://book.cakephp.org/
577 http://docs.casperjs.org/
578 http://docs.ceph.com/docs/master/
579 https://docs.chef.io/
580 https://docs.ckan.org/
581 https://docs.confluent.io/
582 https://docs.djangoproject.com/
583 https://www.doctrine-project.org/
584 https://www.adobe.com/devnet-docs/acrobatetk/
585 http://excamera.com/sphinx/gameduino/
586 https://radimrehurek.com/gensim/
587 http://docs.geoserver.org/
588 http://www.gevent.org/
589 https://downloads.haskell.org/~ghc/master/users-guide/
590 http://docs.guzzlephp.org/
591 http://docs.h2o.ai/
592 https://hekad.readthedocs.io/
593 https://belgeler.yazbel.com/python-istihza/
594 http://docs.kombu.me/
595 http://lassoguide.com/
596 http://docs.makotemplates.org/
597 http://mirrorbrain.org/docs/
598 https://docs.mongodb.com/
• Music21599
• MyHDL600
• ndnSIM601
• nose602
• ns-3603
• NumPy604
• ObjectListView605
• OpenERP606
• OpenCV607
• OpenLayers608
• OpenTURNS609
• Open vSwitch610
• PlatformIO611
• PyEphem612
• Pygments613
• Plone User Manual (German)614
• PSI4615
• PyMOTW616
• python-aspectlib617 (sphinx_py3doc_enhanced_theme618 )
• QGIS619
• qooxdoo620
• Roundup621
• SaltStack622
599 https://web.mit.edu/music21/doc/
600 http://docs.myhdl.org/
601 https://ndnsim.net/current/
602 https://nose.readthedocs.io/
603 https://www.nsnam.org/documentation/
604 https://docs.scipy.org/doc/numpy/reference/
605 http://objectlistview.sourceforge.net/python/
606 https://doc.odoo.com/
607 https://docs.opencv.org/
608 http://docs.openlayers.org/
609 https://openturns.github.io/openturns/master/
610 http://docs.openvswitch.org/
611 https://docs.platformio.org/
612 http://rhodesmill.org/pyephem/
613 http://pygments.org/docs/
614 https://www.hasecke.com/plone-benutzerhandbuch/4.0/
615 http://www.psicode.org/psi4manual/master/index.html
616 https://pymotw.com/2/
617 https://python-aspectlib.readthedocs.io/
618 https://pypi.org/project/sphinx_py3doc_enhanced_theme/
619 https://qgis.org/en/docs/index.html
620 https://www.qooxdoo.org/current/
621 http://www.roundup-tracker.org/
622 https://docs.saltstack.com/
• scikit-learn623
• SciPy624
• Scrapy625
• Seaborn626
• Selenium627
• Self628
• Substance D629
• Sulu630
• SQLAlchemy631
• tinyTiM632
• Twisted633
• Ubuntu Packaging Guide634
• WebFaction635
• WTForms636
• “A Web-Based System for Comparative Analysis of OpenStreetMap Data by the Use of CouchDB”676
• “Content Conditioning and Distribution for Dynamic Virtual Worlds”677
• “The Sphinx Thesis Resource”678
• Read the Docs679 , a software-as-a-service documentation hosting platform, uses Sphinx to automat-
ically build documentation updates that are pushed to GitHub.
• Spyder680 , the Scientific Python Development Environment, uses Sphinx in its help pane to render
rich documentation for functions, classes and methods automatically or on-demand.
665 http://www.amazon.co.jp/dp/4798032948/
666 https://www.amazon.co.jp/dp/479804315X/
667 https://www.amazon.co.jp/dp/4798053821/
668 https://www.oreilly.co.jp/books/9784873118048/
669 https://www.shuwasystem.co.jp/products/7980html/4825.html
670 https://www.amazon.com/repoze-bfg-Web-Application-Framework-Version/dp/0615345379
671 https://www.amazon.co.jp/dp/4822292274/
672 https://www.amazon.co.jp/dp/477414259X/
673 https://www.amazon.de/dp/1497448689/
674 https://www.theoretical-physics.net/
675 https://info.varnish-software.com/the-varnish-book
676 https://www.yumpu.com/et/document/view/11722645/masterthesis-markusmayr-0542042
677 https://www.cs.princeton.edu/research/techreps/TR-941-12
678 https://jterrace.github.io/sphinxtr/
679 https://readthedocs.org/
680 https://docs.spyder-ide.org/help.html
TWENTYFOUR
SPHINX AUTHORS
411
Sphinx Documentation, Release 3.0.0+/0fb832baa
413
Sphinx Documentation, Release 3.0.0+/0fb832baa
a sphinx.ext.inheritance_diagram, 140
sphinx.addnodes, 245 sphinx.ext.intersphinx, 142
sphinx.application, 223 sphinx.ext.jsmath, 148
sphinx.ext.linkcode, 144
b sphinx.ext.mathbase, 145
sphinx.builders, 109 sphinx.ext.mathjax, 147
sphinx.builders.changes, 113 sphinx.ext.napoleon, 148
sphinx.builders.dirhtml, 109 sphinx.ext.todo, 156
sphinx.builders.dummy, 114 sphinx.ext.viewcode, 157
sphinx.builders.epub3, 110
sphinx.builders.gettext, 113
l
sphinx.builders.html, 109 latex, 209
sphinx.builders.latex, 110
sphinx.builders.linkcheck, 114 p
sphinx.builders.manpage, 112 sphinx.parsers, 244
sphinx.builders.singlehtml, 109
sphinx.builders.texinfo, 112 s
sphinx.builders.text, 112 sphinxcontrib.applehelp, 110
sphinx.builders.xml, 114 sphinxcontrib.devhelp, 110
sphinxcontrib.htmlhelp, 109
c sphinxcontrib.qthelp, 110
conf, 71
d
docutils.parsers.rst, 239
sphinx.domains, 241
e
sphinx.environment, 236
sphinx.environment.collectors, 238
sphinx.errors, 235
sphinx.ext.autodoc, 117
sphinx.ext.autosectionlabel, 125
sphinx.ext.autosummary, 126
sphinx.ext.coverage, 129
sphinx.ext.doctest, 130
sphinx.ext.extlinks, 135
sphinx.ext.githubpages, 136
sphinx.ext.graphviz, 136
sphinx.ext.ifconfig, 139
sphinx.ext.imgconverter, 139
sphinx.ext.imgmath, 145
415
Sphinx Documentation, Release 3.0.0+/0fb832baa
417
Sphinx Documentation, Release 3.0.0+/0fb832baa
418 Index
Sphinx Documentation, Release 3.0.0+/0fb832baa
Index 419
Sphinx Documentation, Release 3.0.0+/0fb832baa
420 Index
Sphinx Documentation, Release 3.0.0+/0fb832baa
html4_writer, 89 latex_docclass, 97
html_add_permalinks, 84 latex_documents, 95
html_additional_pages, 85 latex_domain_indices, 95
html_baseurl, 82 latex_elements, 96
html_compact_lists, 86 latex_engine, 94
html_context, 83 latex_logo, 95
html_copy_source, 86 latex_show_pagerefs, 96
html_css_files, 83 latex_show_urls, 96
html_domain_indices, 85 latex_toplevel_sectioning, 95
html_experimental_html5_writer, 88 latex_use_latex_multicolumn, 96
html_extra_path, 84 latex_use_xindy, 96
html_favicon, 83 link-index, 175
html_file_suffix, 86 linkcheck_anchors, 100
html_js_files, 83 linkcheck_anchors_ignore, 100
html_last_updated_fmt, 84 linkcheck_ignore, 100
html_link_suffix, 86 linkcheck_retries, 100
html_logo, 83 linkcheck_timeout, 100
html_math_renderer, 88 linkcheck_workers, 100
html_output_encoding, 86 linkcode_resolve, 145
html_scaled_image_link, 88 locale_dirs, 80
html_search_language, 86 man_pages, 98
html_search_options, 87 man_show_urls, 98
html_search_scorer, 88 manpages_url, 75
html_secnumber_suffix, 86 master_doc, 73
html_short_title, 82 math_eqref_format, 82
html_show_copyright, 86 math_number_all, 82
html_show_sourcelink, 86 math_numfig, 82
html_show_sphinx, 86 mathjax_config, 147
html_sidebars, 84 mathjax_options, 147
html_sourcelink_suffix, 86 mathjax_path, 147
html_split_index, 85 modindex_common_prefix, 78
html_static_path, 83 napoleon_google_docstring, 152
html_style, 82 napoleon_include_init_with_doc, 153
html_theme, 82 napoleon_include_private_with_doc, 153
html_theme_options, 82 napoleon_include_special_with_doc, 153
html_theme_path, 82 napoleon_numpy_docstring, 153
html_title, 82 napoleon_use_admonition_for_examples, 153
html_use_index, 85 napoleon_use_admonition_for_notes, 154
html_use_opensearch, 86 napoleon_use_admonition_for_references, 154
html_use_smartypants, 84 napoleon_use_ivar, 154
htmlhelp_basename, 89 napoleon_use_keyword, 155
htmlhelp_file_suffix, 89 napoleon_use_param, 155
htmlhelp_link_suffix, 89 napoleon_use_rtype, 155
image_converter, 139 needs_extensions, 75
image_converter_args, 139 needs_sphinx, 75
imgmath_add_tooltips, 146 nitpick_ignore, 76
imgmath_dvipng, 146 nitpicky, 76, 175
imgmath_dvipng_args, 146 numfig, 76
imgmath_dvisvgm, 146 numfig_format, 76
imgmath_dvisvgm_args, 146 numfig_secnum_depth, 76
imgmath_font_size, 146 pdb, 175
imgmath_image_format, 145 primary_domain, 74
imgmath_latex, 146 project, 71, 175
imgmath_latex_args, 146 pygments_style, 78
imgmath_latex_preamble, 146 qthelp_basename, 99
imgmath_use_preview, 145 qthelp_namespace, 100
inheritance_alias, 142 qthelp_theme, 100
inheritance_edge_attrs, 142 qthelp_theme_options, 100
inheritance_graph_attrs, 142 release, 72, 175
inheritance_node_attrs, 142 rst_epilog, 74
intersphinx_cache_limit, 144 rst_prolog, 74
intersphinx_mapping, 143 show_authors, 78
intersphinx_timeout, 144 singlehtml_sidebars, 89
jsmath_path, 148 smartquotes, 76
keep_warnings, 74 smartquotes_action, 77
language, 79 smartquotes_excludes, 77
latex_additional_files, 97 source-dir, 174
latex_appendices, 95 source_encoding, 72
Index 421
Sphinx Documentation, Release 3.0.0+/0fb832baa
422 Index
Sphinx Documentation, Release 3.0.0+/0fb832baa
Index 423
Sphinx Documentation, Release 3.0.0+/0fb832baa
424 Index
Sphinx Documentation, Release 3.0.0+/0fb832baa
Index 425
Sphinx Documentation, Release 3.0.0+/0fb832baa
image_converter is_supported()
configuration value, 139 (sphinx.transforms.post_transforms.SphinxPostTransform
image_converter_args method), 251
configuration value, 139
ImageConverter (class in
sphinx.transforms.post_transforms.images), 252
J
imgmath_add_tooltips js:attr (role), 66
configuration value, 146 js:attribute (directive), 66
imgmath_dvipng js:class (directive), 66
configuration value, 146 js:class (role), 66
imgmath_dvipng_args js:data (directive), 66
configuration value, 146 js:data (role), 66
imgmath_dvisvgm js:func (role), 66
configuration value, 146 js:function (directive), 65
imgmath_dvisvgm_args js:meth (role), 66
configuration value, 146 js:method (directive), 66
imgmath_font_size js:mod (role), 66
configuration value, 146 js:module (directive), 65
imgmath_image_format jsmath_path
configuration value, 145 configuration value, 148
imgmath_latex JSONHTMLBuilder (class in sphinxcontrib.serializinghtml), 113
configuration value, 146
imgmath_latex_args K
configuration value, 146 kbd (role), 27
imgmath_latex_preamble keep_warnings
configuration value, 146 configuration value, 74
imgmath_use_preview keyword (role), 26
configuration value, 145
implementation
(sphinxcontrib.serializinghtml.SerializingHTMLBuilder L
attribute), 112 label (sphinx.domains.Domain attribute), 243
in version language
changes, 32 configuration value, 79
index (class in sphinx.addnodes), 246 language (built-in variable), 206
Index (class in sphinx.domains), 243 last_updated (built-in variable), 206
index (directive), 39 latex (module), 209
index (role), 40 latex_additional_files
indices (sphinx.domains.Domain attribute), 243 configuration value, 97
info() (sphinx.util.logging.SphinxLoggerAdapter method), 248 latex_appendices
inheritance-diagram (directive), 140 configuration value, 95
inheritance_alias latex_docclass
configuration value, 142 configuration value, 97
inheritance_edge_attrs latex_documents
configuration value, 142 configuration value, 95
inheritance_graph_attrs latex_domain_indices
configuration value, 142 configuration value, 95
inheritance_node_attrs latex_elements
configuration value, 142 configuration value, 96
inherited_members (built-in variable), 128 latex_engine
init() (in module sphinx.locale), 248 configuration value, 94
init() (sphinx.application.TemplateBridge method), 235 latex_logo
init() (sphinx.builders.Builder method), 238 configuration value, 95
init_console() (in module sphinx.locale), 248 latex_show_pagerefs
init_indexing() (sphinxcontrib.websupport.search.BaseSearch configuration value, 96
method), 185 latex_show_urls
initial_data (sphinx.domains.Domain attribute), 243 configuration value, 96
inliner (sphinx.util.docutils.SphinxRole attribute), 252 latex_toplevel_sectioning
intersphinx_cache_limit configuration value, 95
configuration value, 144 latex_use_latex_multicolumn
intersphinx_mapping configuration value, 96
configuration value, 143 latex_use_xindy
intersphinx_timeout configuration value, 96
configuration value, 144 LaTeXBuilder (class in sphinx.builders.latex), 110
is_available() lineno (docutils.parsers.rst.Directive attribute), 240
(sphinx.transforms.post_transforms.images.ImageConverter lineno (sphinx.util.docutils.SphinxRole attribute), 252
method), 252 link-index
is_parallel_allowed() (sphinx.application.Sphinx method), configuration value, 175
231 linkcheck_anchors
426 Index
Sphinx Documentation, Release 3.0.0+/0fb832baa
Index 427
Sphinx Documentation, Release 3.0.0+/0fb832baa
428 Index
Sphinx Documentation, Release 3.0.0+/0fb832baa
Q set_source_info() (sphinx.util.docutils.SphinxDirective
qthelp_basename method), 251
configuration value, 99 set_translator() (sphinx.application.Sphinx method), 224
qthelp_namespace setup_extension() (sphinx.application.Sphinx method), 224
configuration value, 100 shorttitle (built-in variable), 207
qthelp_theme show_authors
configuration value, 100 configuration value, 78
qthelp_theme_options show_source (built-in variable), 207
configuration value, 100 sidebar() (built-in function), 206
QtHelpBuilder (class in sphinxcontrib.qthelp), 110 SingleFileHTMLBuilder (class in sphinx.builders.singlehtml),
query() (sphinxcontrib.websupport.search.BaseSearch method), 185 109
singlehtml_sidebars
configuration value, 89
R smartquotes
rawtext (sphinx.util.docutils.SphinxRole attribute), 252 configuration value, 76
ref (role), 24 smartquotes_action
ReferenceRole (class in sphinx.util.docutils), 252 configuration value, 77
regexp (role), 27 smartquotes_excludes
relbar() (built-in function), 206 configuration value, 77
reldelim1 (built-in variable), 205 snippets
reldelim2 (built-in variable), 205 testing, 130
release source directory, 294
configuration value, 72, 175 source-dir
release (built-in variable), 206 configuration value, 174
relfn2path() (sphinx.environment.BuildEnvironment method), source-read
237 event, 232
rellinks (built-in variable), 207 source_encoding
RemoveInSphinxXXXWarning, 294 configuration value, 72
render() (sphinx.application.TemplateBridge method), 235 source_parsers
render_string() (sphinx.application.TemplateBridge method), configuration value, 73
235 source_suffix
require_sphinx() (sphinx.application.Sphinx method), 224 configuration value, 72
required_arguments (docutils.parsers.rst.Directive attribute), source_suffix (sphinx.project.Project attribute), 236
239 sourcecode, 34
resolve_any_xref() (sphinx.domains.Domain method), 242 sourcename (built-in variable), 208
resolve_xref() (sphinx.domains.Domain method), 242 Sphinx (class in sphinx.application), 223, 231
restore() (sphinx.project.Project method), 236 sphinx-apidoc command line option
reStructuredText, 294 -implicit-namespaces, 196
rfc (role), 28 -tocfile, 196
role, 294 -A <author>, 196
role() (sphinx.domains.Domain method), 242 -E, -no-headings, 196
roles (sphinx.domains.Domain attribute), 243 -F, -full, 196
rst:dir (role), 67 -H <project>, 196
rst:directive (directive), 66 -M, -module-first, 196
rst:directive:option (directive), 67 -P, -private, 196
:type: (directive option), 67 -R <release>, 196
rst:role (directive), 67 -T, -no-toc, 196
rst:role (role), 67 -V <version>, 196
rst_epilog -a, 196
configuration value, 74 -d <MAXDEPTH>, 196
rst_prolog -e, -separate, 196
configuration value, 74 -f, -force, 195
rubric (directive), 33 -l, -follow-links, 195
run() (docutils.parsers.rst.Directive method), 239 -n, -dry-run, 196
run() (sphinx.transforms.post_transforms.SphinxPostTransform -o <OUTPUT_PATH>, 195
method), 251 -s <suffix>, 196
sphinx-autogen command line option
S -i, -imported-members, 197
samp (role), 28 -o <outputdir>, 197
script_files (built-in variable), 205 -s <suffix>, -suffix <suffix>, 197
searchindex_filename -t <templates>, -templates <templates>, 197
(sphinxcontrib.serializinghtml.SerializingHTMLBuilder sphinx-build command line option
attribute), 113 -keep-going, 194
sectionauthor (directive), 38 -A name=value, 193
seealso (class in sphinx.addnodes), 246 -C, 193
seealso (directive), 33 -D setting=value, 193
SerializingHTMLBuilder (class in -E, 192
sphinxcontrib.serializinghtml), 112 -M buildername, 192
Index 429
Sphinx Documentation, Release 3.0.0+/0fb832baa
430 Index
Sphinx Documentation, Release 3.0.0+/0fb832baa
Index 431
Sphinx Documentation, Release 3.0.0+/0fb832baa
W
warning, 32
warning (directive), 32
warning() (built-in function), 206
warning() (sphinx.util.logging.SphinxLoggerAdapter method), 247
warning-is-error
configuration value, 174
WebSupport (class in sphinxcontrib.websupport), 181
Wrapper (C++ class), 62
Wrapper::Outer (C++ class), 62
Wrapper::Outer::Inner (C++ class), 62
write_doc() (sphinx.builders.Builder method), 238
X
xml_pretty
configuration value, 101
XMLBuilder (class in sphinx.builders.xml), 114
432 Index