Sphinx/Rest Memo¶
Contents:
Introduction¶
This Memo was written [history] to serve as quick reference for ReST and Sphinx syntax.
Sphinx itself is very well documented, but is very large and cover many aspects, all of them not for daily use. And the Documentation of Rest, while being very rigorous is not of an easy access, at least at my own taste. I use to spend a lot of time to clarify even a tiny aspect, as the documentation is often scattered in many locations.
Moreover Sphinx seems first to be an extension of Rest, but it is not always true and there are some difference of aims, and incompatibilities, between Sphinx and Rest constructs.
This Memo give the constructs that I use the most often, and give cross-references to the manuals for details.
[history] | This Memo is a fork of a previous version of Cristoph Reller reST Memo it has been deeply modified and largely extended, as Cristoph Reller also modified his memo, they have few in common. |
ReST
– reStructuredText¶
A simple markup language for plain text files.
Structural elements¶
Emacs ReST mode¶
C-c C-= |
Adjust/rotate or promote/demote the decorations |
C-- C-c C-= |
reverse Adjust |
C-c C-a C-d |
Display the title decoration hierarchy. |
C-- C-c C-r <tab> |
shift region left |
C-c C-r <tab> |
shift region right |
C-c C-t C-t |
display a table of content to navigate buffer |
Sectioning¶
Titles are under- (and over-)lined (decorated) by =*-^"~`:.'#
as below. The
exact order of the decoration is not important, the one below is the
Python convention.
####
Part
####
*********
Chapter
*********
Section
=======
|
Subsection
----------
Subsubsection
^^^^^^^^^^^^^
Paragraph
"""""""""
|
Normal paragraphs are separated by a blank line.
A =
with overlines is very often preferred to a *
with
overlines for chapters. The previously quoted
Python development guide while
advising to use stars uses internally equal character.
Docutils documentation uses
overlined =
for parts, overlined -
for chapters, =
for
sections, -
for subsections, back quotes (`) for subsubsections.
Transition¶
Any repetition of 4 or more punctuation characters with preceding and trailing blank line is a transition, and looks like this:
Inline markup¶
*emphasize* |
emphasize |
**emphasize strongly** |
emphasize strongly |
``code`` |
code |
`don't know` |
don’t know |
Asterisk \* |
Asterisk * |
back-quote \` |
back-quote ` |
**mark**\ up. |
markup. |
ReStructuredText Text Roles.¶
The ReStructuredText Interpreted Text Roles
are valid both for reST and Sphinx processing. They are:
:emphasis:
, :strong:
, :literal:
, :code:
, :math:
,
:pep-reference:
, :rfc-reference:
, :subscript:
,
:superscript:
, :title-reference:
, :raw:
. The first three
are seldom used because we prefer the shortcuts provided by previous
reST inline markup.
The Custom Interpreted Text Roles
which is a reST directive role
, the tailor the renderer to
apply some special formatting. We use it
in Sphinx section
to use a special css class for some span of text.
Lists¶
Bullet list¶
- First item with some lengthy
text wrapping hopefully
across several lines.
* We can have subitems
* separated by a blank line
* and indented.
- Second item
- First item with some lengthy
text wrapping hopefully
across several lines.
- We can have subitems
- separated by a blank line
- and indented.
- Second item
We can begin each item with *
, +
, -
, •
, ‣
, or
⁃
followed by at least one space, you should keep the indentation
of the text of the first line in subsequents lines.
Horizontal lists¶
.. hlist:: :columns: 3 * list of * short items * that should be * displayed * horizontally
|
|
|
hlist is a sphinx extension, not a ReST directive
Enumerated list¶
2. We start with point number 2
#. Automatically numbered item.
a) Point a
i) first subitem
ii) second subitem
b) Point b
#) Automatic point c.
- We start with point number 2
- Automatically numbered item.
- Point a
- first subitem
- second subitem
- Point b
- Automatic point c.
We can use enumerate with numerals, alphabetic lower case or upper case, roman numerals lower case or upper case.
We can write enumeration followed by a period, a right parenthese, or
surrounded by a parentheses; but these punctuation are not kept in the
rendering; rst2html render i.
, i)
or (i)
as “i.” and
Sphinx render them as “a.”.
A list must be separated from previous paragraph by a blank line, in the same way sublists must be separated from items of upper list by a blank line.
Any break of sequence in the source, produces a new list.
Definition list¶
what
Definition of "what". We add a few
words to show the line wrapping.
how
Definition of "how".
why :
We define "why" we do it.
In many paragraphs
- what
- Definition of “what”. We add a few words to show the line wrapping.
- how
- Definition of “how”.
- why : cause
We define “why” we do it.
In many paragraphs.
With ReST but not Sphinx you can use a classifier after the main term like
why : cause
We define "why" we do it.
We may have to escape a markup character to clear ambiguity between a definition list and an other construct like:
\(w)
This is a definition list, not an enumeration.
Field list¶
:Name: Isaac Newton
:Long: Here we insert more text
in many lines.
:Remark:
Starts on the next line.
|
|
See field list reference.
Options list¶
E.g. for listing command line options.
-v An option
-o file Same with value
--delta A long option
--delta=len Same with value
--option-name-is-long
description on the next line.
|
|
It is nice to align option descriptions, but not mandatory, but at least two spaces must separate an option from the description.
Blocks¶
Literal Block¶
A block which is not interpreted at all is preceded by a paragraph
consisting of ::
and a blank line. The block must be indented.
The double ::
is removed from the output.
To use a specific formatting, you can use the code directive
Block one
::
**No** interpretation of
|special| characters.
|
Block one **No** interpretation of
|special| characters.
|
You can also put the ::
at the end of the paragraph preceding the
block. When text immediately precedes the ::
the two colons are
displayed as “:”, if there is a space before the colons they are
removed from the output.
Block in condensed syntax::
- I'm not a list.
|
Block in condensed syntax: - I'm not a list.
|
Another block! ::
In the text body,
indentation is
preserved
|
Another block! In the text body,
indentation is
preserved
|
Warning
Sphinx use literal blocks to highlight source code, so **No**
is still written
with a bold font by Sphinx while being not interpreted by
rst2html.
To disable Pygment decorations in Sphinx use a
code block in text
language.
Line blocks¶
In a line block (ref)
every line is preceded with |
and at least one space.
| Line block
| New line and we are still on
the same line
| Yet a new line
|
Line block
New line and we are still on
the same line
Yet a new line
|
Block quote¶
created by ... surrounding paragraph.
Neither from itself nor from another,
Nor from both,
Nor without a cause,
Does anything whatever, anywhere arise.
--Nagarjuna - *Mulamadhyamakakarika*
Block quotes (ref) are created by just indenting them more than the surrounding paragraphs.
Neither from itself nor from another, Nor from both, Nor without a cause, Does anything whatever, anywhere arise.
—Nagarjuna - Mulamadhyamakakarika
An optional attribution can be set by a line beginning by two or three minus signs flushed left at the level of the quote.
Pull-quote¶
Pull-quotes (ref) are similar to blockquotes but are directives
.. pull-quote::
Just as a solid ...
Just as a solid rock is not shaken by the storm, even so the wise are not affected by praise or blame.
Epigraph and highlights¶
An epigraph directive (ref) and an highlights directive (ref) are aimed to put a quotation in a distinct font.
don’t forget the final s of highlights, or you fall down on the Sphinx code highlighting directive
.. highlights::
With these *highlights* ...
With these highlights we have completed the ReST blocks.
These three directives are similar in
html rendering to Block quote but with a class of pull-quote
,
highlights
or epigraph
that your css may use but default css
does not!
Container¶
.. container:: myclass
There is also a general ...
There is also a general container directive whose unique effect is adding some class name to the block that your css may use. In html this paragraph is enclosed in a
<div class="myclass container"> ... </div>
Class¶
.. class:: myclass
The class directive ....
-
class
reST.
myclass
¶
The class directive (ref) add a
class on its content or on the first immediately following non-comment
element. The name of the class is normalized by docutil to conform to
the regexp: [a-z](-?[a-z0-9]+)*
.
Note
While the docutil tool rst2html
put as expected the previous
paragraph in a:
<p class="myclass">....</p>
Sphinx shadows the class directive, so the previous code will not
have the expected result. In Sphinx you have to replace class
by rst-class
.
Tables¶
Simple tables¶
Simple tables (ref)
are preceded and ended with a sequence of “=
” to indicate the
columns, e.g:
aA | bB |
cC | dD |
Headers are indicated by another sequence of “=
”, e.g:
Vokal | Umlaut |
---|---|
aA | äÄ |
oO | öÖ |
Column spans are followed by a sequence of “-
” (except for the last header
or last row of the table where we must have “=
”), e.g:
Inputs | Output | |
---|---|---|
A | B | A or B |
False | False | |
True | False | True |
False | True | True |
True | True |
Simple table cells are treated like a small document on their own up to line breaks, but the first column must contain a single line. e.g:
|
blah blah blah
blah blah blah
blah
blah blah
|
|
We can wrap the text in source |
|
aha |
Grid tables¶
Grid tables (ref) have a more difficult syntax but can express more complex tables.
Header | Header with 2 cols | |
---|---|---|
A |
|
C |
B: *hey*
|
a block
of text
a break
|
You can edit them under emacs with table.el
(but be careful about conflicts with rst-mode
) or
use org tables with orgtbl-mode
and export to table with
org-table-convert
or org-table-create-with-table.el
( bound
to C-c ~ in org-mode
, but not in orgtbl-mode
)
csv table.¶
Description | In | Out | Balance |
---|---|---|---|
Travel | 230.00 | -230.00 | |
Fees | 400.00 | -630.00 | |
Grant | 700.00 | 70.00 | |
Train Fare | 70.00 | 0.00 |
The options are explained in the reference: rst directive: csv-table
You can choose a delimiter with :delim:
and source an external
file with the option :file:/path/of/the/file
.
List Table.¶
A list-table (ref) is a two level list, where the first level is a row and the second one a column list. The number of column must be uniform (no column span) but cell may contain structured markup.
.. list-table:: Weather forecast
:header-rows: 1
:widths: 7 7 7 7 60
:stub-columns: 1
* - Day
- Min Temp
- Max Temp
-
- Summary
* - Monday
- 11C
- 22C
- .. image:: _static/sunny.svg
:width: 30
- A clear day with lots of sunshine.
However, the strong breeze will bring
down the temperatures.
* - Tuesday
- 9C
- 10C
...
Day | Min Temp | Max Temp | Summary | |
---|---|---|---|---|
Monday | 11C | 22C | A clear day with lots of sunshine. However, the strong breeze will bring down the temperatures. | |
Tuesday | 9C | 10C | Cloudy with rain, across many northern regions. Clear spells across most of Scotland and Northern Ireland, but rain reaching the far northwest. |
LaTeX table rendering.¶
Rendering with tabulary.¶
Sphinx use the latex package tabulary to render tables in laTeX.
Tabulary is an extension of the tabular package which calculate the
width of columns; it has four new formats specifications: LRCJ
for
Left (Right, Centered, Justified) column with automatic width.
Sphinx uses by default L
, but you can override it with a directive
like:
.. tabularcolumns:: |L|C|C|R|
As examples in this document the source code directives table which has a proper Sphinx automatic rendering
in tabulary |L|L|
, which adapt the column size with a wider left one.
The two first simple tables the csv table and the list table are also rendered in tabulary with a proper calculation of table width by latex.
Rendering with tabular.¶
Tables that contain any kind of lists, such as object descriptions, blockquotes, or literal blocks are set by default with the tabular. In sphinx prior version 1.6 the :column: option for list table is not used for latex, and all columns are of the same size.
You can tailor the rendering by giving tabularcolumns directive which uses the p{width} column type.
Like this for three uneven columns:
.. tabularcolumns::
|p{0.10\linewidth}|p{0.10\linewidth}|p{0.30\linewidth}|
Cross reference.¶
Hypertext link.¶
Hypertext links are constituted of a reference and a target.
And there are four types of hyperlink targets:
An external hyperlink target is an URI or an email addresses like
_Docutils: http://docutils.sourceforge.net/ _John Lee: john.lee@gmail.com
It is possible, but not recommended, to avoid the target reference by using an anonymous hyperlink.
An internal document reference point to some location in the same document.
An indirect hyperlink has an other hyperlink reference as target.
An implicit hyperlink target is generated by the docutil ReST processor, for all sections of the document.
There exist three ways to write hyperlink references (ref)
- In Citation Style
- Inline with an Embedded URI which gives in the same construct both the reference and the target.
- In a standalone hyperlink the text of the target URI is used as reference.
Internal document reference.¶
To define label
as label also called explicit hyperlink target
for any text location internal to a document, precede the text location with:
.. _label:
.. _other label:
plus a blank line.
A :name:
option in any block is also an internal reference target.
You can also use inline internal targets
which are a _`span of running text` in a paragraph.
The ReST way of referencing a label or hyperlink targets is:
label_ or `other label`_
Indirect Hyperlink.¶
If for the same hyperlink target you want to use a you want to use many references you can use an indirect hyperlink or indirect reference. With the following indirect references pocoo, Sphinx, The manual and Documentation refer to the same place.
Like above don’t forget backquotes when there are embedded whitespaces.
.. _pocoo: http://sphinx.pocoo.org
.. _Sphinx: pocoo_
.. _The manual: pocoo_
.. _Documentation: `The manual`_
Note that if you only want to have multiple link text with the same target you can also use:
.. _Sphinx:
.. _The manual:
.. _pocoo: http://sphinx.pocoo.org
Multiple adjacent hyperlink references will all point to the same target.
An indirect hyperlink can also be defined inline with an embedded alias.
Anonymous Hyperlink¶
Anonymous hyperlinks are hyperlinks where the target has no label text but begins with double leading underscores, the reference itself ends with two trailing underscores. The target are found by their sequential order in the document. The reference number n, reference the target number n.
Example:
.. __: http://docutils.sourceforge.net/docs/ref/rst/
The `ReST reference manual`__
The anonymous hyperlinks make the source text quite obscure, as the association between reference and targets can only be seen by enumerating both. They break easily. Moving a bloc of text with either a target or reference invalidate all anonymous hyperlinks of the document. So it is wise to avoid them.
Implicit Hyperlink Targets¶
Section titles, footnotes, and citations automatically are
implicit hyperlink targets.
`Transition`_
produces Transition.
In pure ReST syntax you can reference the Transition section
as how to draw an horizontal line with
the hyperlink: `how to draw an horizontal line`_
and the
indirect hyperlink:
.. _how to draw an horizontal line: Transition_
You can also use them with an embedded alias
| The `Transition section <Transition>`_ shows
| `how to draw an horizontal line`_
in your document.
|
The Transition section shows
how to draw an horizontal line in your document.
|
Reference in citation style.¶
A link to `Sphinx Home`_ in citation style.
.. _Sphinx Home: http://sphinx.pocoo.org
A link to Sphinx Home in citation style ( ref).
In printed documents the link will be listed similar as a citation, as opposed to HTML documents.
The reference target is composed of words made of alphabetic and numeric
characters and characters in the set [,:_+-]
without double
hyphens, separated by spaces. (ref)
The references are equivalents when they differ only by case or number of spaces. The space character class include spaces, horizontal or vertical tabs, newlines, carriage returns, or form feeds.
When the reference has no embedded spaces the backquotes are not necessary:
A link to Sphinx_ in citation style.
If you want to use a styled reference you have to use a ref:replacement.
Embedded URI and Aliases¶
Reference: ref
You can directly embed an URI, a link target or an internal label in a reference enclosed in <
, >
in the reference.
In the same way than explicit Indirect Hyperlink. when we use a target defined elsewhere we have use a trailing underscore.
In the last example we use the label internal
which is placed before the following
section.
In-line versions is `Sphinx Home
<http://sphinx.pocoo.org>`_
|
In-line versions is Sphinx Home. |
.. _devguide:
http://docs.python.org/devguide/
`Python development <devguide_>`_
|
Python development |
`Sphinx main page <Sphinx Home_>`_
|
Sphinx main page |
`Internal target <internal_>`_
|
Internal target |
Standalone Hyperlink.¶
Reference: ref
| We may use URI like
http://sphinx.pocoo.org or
| an email address like
project@sphinx.org
|
We may use URI like
http://sphinx.pocoo or
an email address like
project@sphinx.org
|
Difference between ReST and Sphinx location reference¶
Sphinx has its own preferred syntax, it uses:
:ref:`displayed text <label>`
it is specific to Sphinx and you find it in the Sphinx section.
While ReST internal hyperlinks reference a target in the same document, Sphinx allow linking across files of the same project.
These two syntax do not have the same rendering, the text of the target label is used by ReST as default displayed text, while Sphinx syntax either need a reference displayed text or when the target is preceding a section the name of the section is used as default displayed text, the text of the label is never used by Sphinx to display the link.
In this document there is two reference targets before the section Sidebar and Topic, the next table show how they are rendered.
`Sidebar`_ versus `Topic`_
|
Sidebar versus Topic |
:ref:`Sidebar` versus :ref:`Topic`
|
Sidebar and Topic versus Sidebar and Topic |
You cannot use the Sphinx :ref:
syntax to reference
implicit hyperlink targets.
but there is an autosectionlabel extension which provides
a label for each section across the whole project.
When using the Sphinx syntax it is easier to always define an explicit target, which is also is more robust as a rewording of a section title will not invalidate the document.
Explicit Markup¶
They all begin with two periods and a white space.
Footnote¶
ref: footnotes
To define a footnote numbered 2 you write it
.. [2]
precedes the definition of the footnote 2. It is referenced by
[2]_
. E.g.
In the text [2]_.
.. [2] In the footnote.
|
In the text [2].
|
||||
First automatic [#]_.
Another automatic [#]_.
.. [#] The first automatic.
.. [#] The other automatic.
|
First automatic [1]. Another automatic [3].
|
||||
A labeled automatic [#one]_.
Another of these [#two]_.
.. [#one] footnote.
.. [#two] labeled footnotes.
|
A labeled automatic [4]. Another of these [5].
|
||||
An autosymbol [*]_.
More autosymbol [*]_.
.. rubric:: Footnotes
.. [*] Footnote in a *Footnotes*
``rubric`` at end of document.
.. [*] other labeled footnote.
|
An autosymbol [*]. More autosymbol [†]. Footnotes
|
Labeled footnotes are always numerics.
Citation¶
ref: citations and citation references
Citations are identical to footnotes except that they use only non-numeric labels.
More details are given in [project]_.
.. [project] This project began by ....
|
More details are given in [project].
|
||
We can use also links like Project_
|
As citation define ordinary target reference
We can use also links like Project
|
.. [project]
is followed by the definition of the citation
It is referenced as [project]__
.
Citation labels are single word reference name.
In Sphinx, definition and reference can reside in different files.
Rest Directives¶
Directives are a general-purpose extension mechanism. The general syntax is similar to explicit_markup:
.. ‹name›:: ‹argument 1›
‹argument 2›
:‹option 1›: ‹value›
‹body›
The reST directives are detailed in the docutils reference: reStructuredText Directives
We have yet see above the directives Pull-quote and Epigraph and highlights.
table of contents¶
Create a table of contents
containing (sub)titles ranging from level 1 to
level ‹number› if you use the :local:
option the TOC is local to
the section where it appears, otherwise it is for the whole file, the title may be empty:
.. contents:: `Table of contents`
:depth: ‹number›
:local:
image and figure¶
Images (ref) are simple pictures, see also images in the Sphinx documentation
.. image:: _static/NeoHittiteSphinx.svg
:width: 120px
:alt: Sphinx Neo-Hittite
:target: https://it.wikipedia.org/wiki/Telepinu_(divinità)
You can click on this image to go to the target Wikipedia (it): Telepinu.
A figure (ref) add to an image an optional caption and an optional legend.
.. figure:: _static/NeoHittiteSphinx.svg
:width: 120px
:alt: Sphinx Neo-Hittite
Sphinx Neo-Hittite
Telepinu is an `Hitite <http://en.wikipedia.org/wiki/Hittites>`_
deity.
Other options are:
:scale: <integer percentage>
,:align: {top|middle|bottom|left|right}
Images and LaTeX export¶
The reST command rst2latex use the width an hight of images and
figures but
the Sphinx laTeX exporter use also \includegraphics
to import the figure;
but (as a far as Sphinx 1.2pre) it does not use the width and height
attribute.
To get proper figure size in latex generated by Sphinx you may have either to
resize the figure before including it,
use the
:scale:
option that is supported and generates a latex\scalebox
or put a distinct laTeX code in an
raw:: latex
directive that use something like:\includegraphics[width=60mm, height=40mm]{myfig.png}
Latex does not support svg and it has to be converted to eps or pdf, pdf being the only one to support transparency. The conversion can be done with Inkscape, it can be automated as explained by Johan B. C. Engelen. You can also use the ipe drawing editor.
Code blocks¶
.. code:: ‹language›
:linenos:
‹body›
is the ReST directive which is called in python Code highlighting. or sourcecode.
You must use code-block
or sourcecode
with Sphinx
and the code
with ReST utilities.
ReST use the same code highlighting than Sphinx, look at Sphinx code highlighting to learn about the ways to specify it.
Replacement¶
ReST references: replace directive, unicode directive, date directive, substitution definitions (specification), substitution definition (definition files), Character Entity Sets.
See also: docutil FAQ: How can I represent esoteric characters?.
General replacements:
This example is |stupid|
.. |stupid| replace:: not so clever
|
This example is not so clever |
One use of replacements is to create styled reference.
If we are not satisfied by a reference like: more in ReST directives manual that you get with
.. _ more in ReST directives manual:
http://docutils.sourceforge.net/doc...
but you want to get: more in reST directives manual.
You use the replacement:
... want to get: |more-doc|_.
.. |more-doc| replace:: *more in* **reST** *directives manual*
.. _more-doc: http://docutils.sourceforge.net/doc...
We also use substitutions to include unicode characters like © with:
.. |copy| unicode:: U+000A9 .. COPYRIGHT SIGN
If you use Sphinx there are also three predefined substitutions:
|release|
, |version|
, |today|
.
File include¶
To include a ReST file use:
.. include:: subdir/incl.rst
You can put the file wherever you want the relative paths are interpreted relative to the source directory.
The options: start-line
, end-line
, start-after
, end-before
as referenced in reST Directives.
If you use include
with Sphinx, you should exclude the included
files from the source file lookup, by setting in conf.py
the value
exclude_patterns <config.html#confval-exclude_patterns> to a glob
pattern in like:
exclude_patterns = ["include/**"]
For including source code in Sphinx rather use the Sphinx directive literalinclude.
Sidebar and Topic¶
A sidebar or a topic are treated like documents on their own:
.. sidebar:: ‹Title›
‹body›
.. topic:: Topic Title
:name: mytopic
Subsequent indented lines comprise
the body of the topic, and are
interpreted as *body elements*.
Topic Title
Subsequent indented lines comprise the body of the topic, and are interpreted as body elements.
Comment¶
Everything starting like a directive with two periods and a space but not a valid construct is a comment. The comment consume all indented text following it. To avoid a confusion with an other constructs, you can let the first line of a block comment empty except the two periods.
When the two dots are not followed by any text, but a blank line, this is an empty comment, that will not consume a following indented block. Empty comments are used to terminate a preceding construct.
.. One line comment
..
A longer comment example
more comment
Still in comment
..
Here is a block-quote,
not a comment anymore
Here is a block-quote, not a comment anymore
Common options¶
ref: Directives Common Options
The class options :class:
and :name:
are supported by most of the directives.
In the following topic and autre the :name:
act as a
reference target. Here we can refer to the following block as say-no-more.
.. topic:: The end
:class: exceptional
:name: say-no-more
A final word.
The class
render in html as:
<div class="exceptional topic" id="say-no-more">
<p class="topic-title first">the end</p>
<p>A final word.</p>
</div>
the end
A final word.
Sphinx
– Sphinx¶
Sphinx inline markup¶
sphinx reference: Inline markup
Sphinx inline markup is down through interpreted text roles;
they are written :rolename:`content`.
.
There are three types of roles:
- The ReStructuredText Text Roles.
- The Sphinx roles that are described in the section Sphinx Roles. and the Sphinx cross references
- The roles added by Sphinx domains like the Python roles referenced below.
Location cross references¶
sphinx ref: Cross-referencing arbitrary locations and sphinx role: ref.
We use:
:ref:`displayed text <label>`
To reference label
defined in any document of the project.
It allows linking across files, while the rest way
is limited to a location in the same file.
If the label
definition is followed by a section title then
displayed text
can be omitted and will be replaced by the section
title.
E.g. the ReST – reStructuredText Internal document reference section is preceded
with .. _internal:
, so we have:
:ref:`internal` |
Internal document reference. |
:ref:`That section <internal>` |
That section |
We can also use as reference target a name option like
:ref:`see this topic <mytopic>` |
see this topic |
See also Difference between ReST and Sphinx location reference in the ReST chapter.
Automatic labels for sections¶
Sphinx as an extension autosectionlabel that allow to reference each section by its title. Its is similar to Implicit Hyperlink Targets, but works across document.
In the doc:ReST chapter <ReST> we have used an Implicit Hyperlink Targets with:
`Transition`_
`how to draw an horizontal line <Transition>`_
we cannot use in the present chapter this ReST way of referencing a target because ReST processor know only one document. but we can use it with the autosectionlabel extension with
| The section :ref:`Transition` show
| :ref:`how to draw an horizontal line <Transition>`
| in your document.
|
Once you use the autosectionlabel extension new in version 1.4 Sphinx will detect duplicate labels, in contrast with Implicit Hyperlink Targets autolabel define a new label for each section, so if you have manually put a label before a section title which is identical to the title, it will be detected as duplicate.
These duplicate are harmless since they reference the same point. But some title in many
document can be identical, you can have many introduction or conclusion in different
parts. The duplicate may be problematic as any one can be matched by a reference. To
disembiguate the labels there is an configuration option beginning version 1.6
autosectionlabel_prefix_document
which prefix the automatic labels with with the
name of the document it is in, followed by a colon.
With this setting instead of :ref:`Transition`
you have to use
:ref:`ReST:Transition`
it avoid a potential ambiguity with a Transition paragraph
in an other document, and has the additional benefit to avoid also all ambiguities with
explicit labels in your documents.
Cross-referencing documents.¶
sphinx ref: Cross-referencing documents
In Sphinx it is possible to reference a document as follows
:doc:`ReST` |
ReST – reStructuredText |
Extra cross-reference roles¶
Many are described in the sphinx ref:Cross-referencing other items of interest.
To reference a Python Enhancement Proposal use :pep:
, for a
Request for Comments :rfc:
Extensions that define new hyperlinks targets¶
The intersphinx extension generates automatic links to the documentation in other projects for objects not in your own project. It interprets the references to roles
To configure it, give in
conf.py
a dictionary like:intersphinx_mapping = { 'python': ('http://docs.python.org/3', None)}
The extension extlinks help when you have many links pointing to the same site. I use it for the previous reference with the code
:sphinx:`extlinks <ext/extlinks.html>`
and the configuration:extlinks = {'sphinx': ('http://sphinx.pocoo.org/en/latest/%s', 'Sphinx: ')}
Sphinx Roles.¶
The Sphinx roles are described in Sphinx: Inline markup and in the specific domains, e.g. python roles.
Some common markup are:
:abbr:`RFC(request for comments)` |
RFC |
:file:`/etc/profile` |
/etc/profile |
:manpage:`ls(1)` |
ls(1) |
:regexp:`^[a-z]*.[0-9]` |
^[a-z]*.[0-9] |
:samp:`cp {file} {target}` |
cp file target |
Python Roles.¶
role | reference |
---|---|
:py:mod: |
module |
:py:func: |
function |
:py:data: |
module-level variable. |
:py:const: |
constant |
:py:class: |
class [1] |
:py:meth: |
method [1] [2] |
:py:attr: |
data attribute of an object |
:py:exc: |
exception [1] |
[1] | (1, 2, 3) Class, methods, exceptions may be dotted names. |
[2] | The role text should include the type name and the method name |
You may supply an explicit title and reference target: :role:`title
<target>`
.
Sphinx directives¶
Sphinx includes its own directives, which are not available in the docutils builders.
Table of contents.¶
.. toctree::
:maxdepth: ‹depth›
:glob:
‹file 1 without file name extension›
‹file 2 without file name extension›
The toctree directive create a table of contents across files.
A glob
option enables to use wildcards in the filenames, e.g. /comp/*
means all files under the directory comp
.
Relative names are relative to the document the directive occurs in, absolute names are relative to the source directory.
The depth can be further restricted per file by inserting the following Field list type element in the very first line of the file:
:tocdepth: ‹depth›
See Sphinx: Toc tree for other options.
To get a table of content inside a file, use the reST table of contents
Index.¶
Entries in the index
are created automatically from all information units
like functions, classes or attributes but those with a :noindex:
option. Explicit manual entries are made as:
.. index:: ‹entry 1›, ‹entry 2›, !<entry 3> ...
single: ‹entry›; ‹sub-entry›
pair: ‹1st part›; ‹2nd part›
triple: ‹1st part›; ‹2nd part›; <3rd part>
The first two versions create single (sub-)entries, while pair creates two entries “‹1st part›; ‹2nd part›” and “‹2nd part›; <1st part›”; and triple makes three entries.
With the exclamation mark, the <entry 3> is the main entry for this term and is put in bold.
You can also use the keywords see and seealso with see: foo
bar
or seealso: bar foo
.
Glossary.¶
A glossary is a Definition list:
.. glossary::
:sorted:
name1
name2
definition of both name1 and name2
Note, Warning, Seealso.¶
They are paragraph-level markups
Note
This is a note.
Warning
This is a warning.
Selective inclusion.¶
A block may be included depending of the presence of some tag (Sphinx ref):
..only:: <expression>
The expression is made of tags combined in boolean expressions
like html and draft
.
The format and the name of the current
builder is set as predefined tag, if needed it can be prefixed to differentiate
format and builer, like format_html
or builder_html
You can define tags via the -t command-line option of sphinx-build.
In the configuration file you can use
tags.has('tag')
to query,
tags.add('tag')
and tags.remove('tag')
to change.
An alternative is the ifconfig
directive
(Sphinx ref)
from the sphinx.ext.ifconfig
extension:
.. ifconfig:: <Python expression>
To evaluate the expression all variables registered from conf.py
are availables, to add a config value use the setup function in
conf.py
:
def setup(app):
app.add_config_value('newconf', 'default', True)
the third parameter should always be True
.
Defining a css class for some part.¶
There is at least three ways of doing it:
.. role:: red
An example of :red:`red text`.
.. container:: red
Here the full block is red.
An undecorated paragraph.
.. class:: red
This paragraph too is is red.
.. admonition:: Big warning
:class: red
Big warning text is red.
After applying rst2html you get:
<p>An example of <span class="red">red text</span>.</p>
<div class="red container">
Here the full block of test is red.</div>
<p>An undecorated paragraph.</p>
<p class="red">This paragraph too is is red.</p>
<div class="red admonition">
<p class="first admonition-title">Big warning</p>
<p class="last">Big warning text is red.</p>
Here I have taken the admonition directive as example but any directive that allow the :class: option would do.
As it generates a span the role directive is the only one that allow to apply your style to a part of a paragraph.
The class
works as expected with rest2html
,
but directive fail with Sphinx. You have to replace it with
.. rst-class:: red
This paragraph too is is red.
Sphinx use rst-class
to replace the ReSt
class directive that is shadowed by Sphinx.
This is only stated in a small footnote of Sphinx reSt
Primer.
Using your new style¶
To use your new class you need a css style like:
.red {
color: red;
}
You put it in a stylesheet, to give it’s location:
With
rst2html
you must specify the stylesheet’s location with a--stylesheet
(for a URL) or--stylesheet-path
for a local file.With Sphinx a flexible solution is to add your own css file in the
_static
directory and give its location with a template that you put in the_template
directory. You can use a filelayout.html
wich extend the original template of the same name:{% extends "!layout.html" %} {% set css_files = css_files + ["_static/style.css"] %}
For more details refer to Sphinx: Templating.
Sphinx Source Code.¶
Code highlighting.¶
The code blocks are highlighted by sphinx, there is a default language
of Python
that can be changed in the configuration, by setting the
configuration option highlight_language
.
The default Highlighting language used by Pygment in Literal Blocks is set for following snippets of code examples by:
.. highlight:: ‹language›
:linenothreshold: ‹number›
The option language may be any language supported by a Pygment lexer.
The additional linenothreshold
option switches on line numbering
for blocks of size beyond ‹number› lines.
When using Sphinx you can specify the highlighting in a single literal block:
.. code-block:: ‹language›
:linenos:
‹body›
The linenos
option switches on line numbering.
You can also use some options that are described for the
Source code include., namely linenos
, lineno-start
,
caption
, name
, dedent
.
When using base ReST parser use instead code keyword.
Source code include.¶
Source code is included in Sphinx with the directive literalinclude.
To include the source file example.py
as a literal block use:
.. literalinclude:: code/example.py
:linenos:
1 | print("Hello {0}!".format("World"))
|
There are more options:
.. literalinclude:: code/example.py
:caption: Example of code
:name: example.py
:language: python
:dedent: 4
:linenos:
:lines: 1,3,5-10,20-
:emphasize-line: 4,5
caption
is the displayed title before the block, name
is the
reST name option used as an
internal reference target.
dedent
strip left whitespaces, linenos
add a line numbering
alternatively lineno-start
begin the numbering at the given number.
The options language
and linenos
set the highlighting to
‹language›
and enables line numbers respectively.
You can select lines by the lines
option or by
start-after: <string>
and/or end-before: <string>
(<string>s are not quoted).
Whe emphasize the fourth and fifth selected line, which in the above example are the lines 5 and 10 of the source.
If it is a Python module, instead of selecting by lines you can select
a a class function or method to include by using the option
pyobject
:
.. literalinclude:: code/example.py
:pyobject: MyClass.some_method
For including a ReST source file use the rest directive include.
Source code directives.¶
There are very powerful directives in Sphinx for documenting source code, each programming langage has a specific domains .
The following markups are related to documenting python source code.
.. module:: name |
Marks the beginning of the description of a module |
.. currentmodule:: name |
The classes, functions etc. documented from here are in the given module |
.. exception:: name[(signature)] |
Describes an exception class. |
.. class:: name[(signature)] |
Describes a class. [3] |
.. attribute:: name |
Describes an object data attribute. |
.. method:: name(signature) |
Describes an object method. |
.. staticmethod:: name(signature) |
Describes a static method. |
.. classmethod:: name(signature) |
Describes a class method. |
.. decorator:: name(signature) |
Describes a class method. |
.. classmethod:: name(signature) |
Describes a class method. |
[3] | Methods and attributes belonging to the class should be placed in this directive’s body. |
[4] | Signatures of functions, methods, class constructors, decorators can be given like in Python, but with optional parameters indicated by brackets: .. function:: compile(source[, filename, symbol])
|
autodoc¶
There is an autodoc version of the source code directives which include documentation from docstrings:
automodule
,autoclass
,autoexception
. Document a module, class or exception. They insert the docstring of the object itself; if you add a:members:
option followed by a specific list of members, they will be included in the documentation. An empty list of members includes all members... autoclass:: Noodle :members: eat, slurp
autofunction
,autodata
,automethod
,autoattribute
are used to document the respective type of object.
autodata
andautoattribute
support an annotation option taht will show not only the name but the representation of the object.
Using info field lists in Docstrings.¶
Inside Python object description directives the
following fields
are recognized:
param
, arg
, key
, type
, raises
, raise
,
except
, exception
, var
, ivar
, cvar
, returns
,
return
, rtype
.
-
Sphinx.
divide
(i, j) divide two numbers
Parameters: - i (int) – numerator
- j – denominator
Returns: quotient
Return type: integer
Raises:
def divide(self, i, j):
"""Divide two numbers.
This function is to show how the docstring look, using pure Sphinx syntax,
with explicit fields.
:param i: numerator
:type i: int
:param j: denominator
:type j: int
:return: quotient
:rtype: integer
:raises: :exc:`ZeroDivisionError`
"""
-
code.divide.
divide
(self, i, j) Divide two numbers.
This function is to show how the docstring look, using pure Sphinx syntax, with explicit fields.
Parameters: Returns: quotient
Return type: integer
Raises:
Docstring alternate syntax.¶
For docstrings you can use the previous fields or the alternate syntax that is recommended by Openalea Project. :
def example(arg1, arg2):
"""Docstring example.
:Parameters:
- `arg1` (float) - the first value
- `arg2` (float) - the second value
:Returns:
arg1/arg2
:Returns Type:
float
:Examples:
>>> import template
>>> a = MainClass()
>>> a.example(6,2)
1.5
.. note:: can be useful to emphasize
important features.
.. seealso:: :py:exc:`ZeroDivisionError`
.. warning:: arg2 must be non-zero.
.. todo:: check that arg2 is non zero.
"""
-
code.docstring.
example
(arg1, arg2) Docstring example.
Parameters: - arg1 (float) - the first value
- arg2 (float) - the second value
Returns: arg1/arg2
Returns Type: float
Examples: >>> import template >>> a = MainClass() >>> a.example(6,2) 1.5
Note
can be useful to emphasize important features.
See also
Warning
arg2 must be non-zero.
Todo
check that arg2 is non zero.
Google style docstrings.¶
Using Restructured texts in your python code, is quite cumbersome, it produces an easily readable documentation, but cryptic source code.
If we want to follow the style of PEP257 we can use the Google Python style guide also recommended by the Khan Academy Style Guide.
NumPy style guide Alternatively there is a NumPy/SciPy style of documentation.
But they produces docstrings that are not recognized by Sphinx, and not decorated in html output.
The extension napoleon preprocess NumPy and Google style docstrings and converts them to reStructuredText before Sphinx parse the source code. You need to configure it in your conf.py file.
def example(arg1, arg2):
"""Division of two reals.
This function is only to show how we can format docstrings using
Google Style Guide.
Args:
- arg1 (float): The first value.
- arg2 (float): The second value, cannot be Nul.
Returns:
float: Division arg1/arg2.
Raises:
ZeroDivisionError: if arg2 is zero.
Example:
>>> import template
>>> a = MainClass()
>>> a.example(6,2)
1.5
Todo:
Check that arg2 is non zero, and throw an exception.
"""
-
code.gstyle_docstring.
example
(arg1, arg2) Division of two reals.
This function is only to show how we can format docstrings using Google Style Guide.
- Args:
- arg1 (float): The first value.
- arg2 (float): The second value, cannot be Nul.
- Returns:
- float: Division arg1/arg2.
- Raises:
- ZeroDivisionError: if arg2 is zero.
- Example:
>>> import template >>> a = MainClass() >>> a.example(6,2) 1.5
- Todo:
- Check that arg2 is non zero, and throw an exception.
Look here for a larger example.
How napoleon transform my docstrings.¶
We may be curious to know what exactly napoleon generates. It can allow us to fix error in the output by changing our docstring or adding Sphinx fields.
We can call napoleon from python to learn what it generates:
>>> docstring="""
... Division of two reals.
...
..."""
>>> from sphinx.ext.napoleon import Config
>>> from sphinx.ext.napoleon.docstring import GoogleDocstring
>>> config = Config(napoleon_use_param=True, napoleon_use_rtype=True)
>>> print(GoogleDocstring(docstring), config)
And we have the decorated result:
Division of two reals.
This function is only to show how we can format docstrings using
Google Style Guide.
:param - arg1: The first value.
:type - arg1: float
:param - arg2: The second value, cannot be Nul.
:type - arg2: float
:returns: Division arg1/arg2.
:rtype: float
:raises: :exc:`ZeroDivisionError` -- if arg2 is zero.
.. rubric:: Example
>>> import template
>>> a = MainClass()
>>> a.example(6,2)
1.5
.. todo:: Check that arg2 is non zero, and throw an exception.
If you want to experiment with output of napoleon you can look at
the parameters of GoogleDocstring
in the source code
Sphinx extensions¶
We have described in the previous section the extensions: intersphinx, extlinks, ifconfig, napoleon.
todo extension¶
The extension sphinx.ext.todo allow to include todo blocks like
.. todo::
We need to achieve:
.. include:: include/feature.rst
An other directive todolist
is replaced by a list of all todo
directives in the whole documentation.
These blocks are by default excluded but can be included by setting to
True
the configuration variable todo_include_todos
.
You can either set it in the conf.py
file or trigger it by adding
the option to sphinx-build. An easy way is through the Make process by
doing:
$ make -k html SPHINXOPTS="-D todo_include_todos=1"
Sphinx Math¶
There are three mathematical typesetting Sphinx extensions imgmath, mathjax, and jsmath.
The extension imgmath
use LaTeX and dvipng
or dvisvgm
to render math into PNG or SVG
images. You need to install one of these utilities on the machine
where the doc is built.
To enable the extension, the following line has to appear in conf.py
:
extensions = ['sphinx.ext.imgmath']
You then can type standard LaTeX math expressions, either inline:
:math:`‹LaTeX math expression›`
or in display mode:
.. math::
‹LaTeX math expressions›
The second version is also available for a one line expression:
.. math:: ‹1 Line LaTeX math expression›
E.g:
Pythagoras
Mathjax and its predecessor jsmath render math through javascript.
Multiline Math¶
Sphinx Built-in Mechanism
Several lines of math expressions can be entered by leaving a blank line between
them. In addition there is something like an align
environment syntax if
lines are not separated by a blank line.
Explicit LaTeX with amsmath mechanism
If the option nowrap
is specified then the full LaTeX code (including the
math-environment) has to be given. We can assume that the amsmath package
is loaded. This is not limited to math typesetting, any LaTeX construct can be
rendered in this way.
.. math:: \[a = b\]
:nowrap:
or equivalenty
.. math::
:nowrap:
\[a = b\]
|
or equivalenty |
Graphs with Graphviz¶
The Graphviz graph drawing Sphinx extension is provided in Sphinx distribution.
To enable the extension we have to add it to the extensions
list in
conf.py
:
extensions = ['sphinx.est.graphviz']
It uses directly the dot command to process DOT language.
Sphinx project¶
To start a Sphinx project use the interactive
sphinx-quickstart command
(Sphinx ref).
This will ask you all the necessary questions. You can use a Makefile
to build the documentation.
Customization is done in the file conf.py
(Sphinx ref)
and the Makefile
(Sphinx ref).
The configuration of the extensions go also in conf.py
.
References¶
Sphinx and Rest References¶
- This doc began as a fork of a 2011 version of Cristoph Reller reST Memo which is now part of his Programming Notes. I adapted it according to my needs, and they have largely diverged now, but it still inherits from some content and layout.
- Sphinx documentation
- Sphinx reStructuredText Primer
- Documenting Your Project Using Sphinx from an example pypi project’s
- Thomas Cokelaer Openalea project: How to use sphinx ? and Sphinx and RST syntax guide.
- The ReStructuredText Documentation
- Docutil reStructuredText Primer you may prefer the python the Sphinx nicely formated documentation cited above, also available with a distinct layout as docs.python: reStructuredText Primer
- Quick reStructuredText
- reStructuredText Markup Specification
- reST Directives
- Interpreted Text Roles
- ReStructuredText Demonstration
- Emacs Support for reStructuredText
- Documenting Python in the Python Developer’s Guide
- sampledoc tutorial from matplotlib a python 2D plotting library.
- rst2pdf is a tool for transforming reStructuredText to PDF using ReportLab. It supports Sphinx formatting.
- Epydoc reST markup
How to write docstrings¶
- Look at examples in Official list of projects using Sphinx
- Documenting Python use Sphinx in function definitions it prefers to the pure Sphinx Syntax the Google style guide that is used in Full Code Example
- OpenAlea has a nice comparaison of three ways of filling the docstring. which compare Pure sphinx code, restructuredText and Sphinx, Numpy style. But it predates the Napoleon extension, so the cause of rejecting Numpy may be no longer valid. The source is template.py
- Google style guide.
- NumPy style guide.
- Sources of mongo python driver are also a good example
Extending Sphinx¶
- Sphinx Tutorial: Writing a simple extension.
- Creating Custom Link Roles.
- Defining Custom Roles in Sphinx a Sphinx blog post by Doug Hellmann
- Creating Interpreted Text Roles from docutils project.
- Creating reStructuredText Directives from docutils project.