reStructuredText Primer¶
reStructuredText is the default plaintext markup language used by Sphinx. Thissection is a brief introduction to reStructuredText (reST) concepts and syntax,intended to provide authors with enough information to author documentsproductively. Since reStructuredText was designed to be a simple, unobtrusive markuplanguage, this will not take too long.
See also
The authoritativereStructuredText User Documentation.The “ref” links in this document link to the description ofthe individual constructs in the reStructuredText reference.
Paragraphs¶
The paragraph (ref) is the most basic blockin a reStructuredText document.Paragraphs are simply chunks of text separated by one or more blank lines.As in Python, indentation is significant in reStructuredText,so all lines of the same paragraph must be left-alignedto the same level of indentation.
Inline markup¶
The standard reStructuredText inline markup is quite simple: use
one asterisk:
*text*
for emphasis (italics),two asterisks:
**text**
for strong emphasis (boldface), andbackquotes:
``text``
for code samples.
If asterisks or backquotes appear in running text and could be confused withinline markup delimiters, they have to be escaped with a backslash.
Be aware of some restrictions of this markup:
it may not be nested,
content may not start or end with whitespace:
*text*
is wrong,it must be separated from surrounding text by non-word characters. Use abackslash escaped space to work around that:
thisis\*one*\word
.
These restrictions may be lifted in future versions of the docutils.
It is also possible to replace or expand upon some of this inline markup withroles. Refer toRoles for more information.
Lists and Quote-like blocks¶
List markup (ref) is natural: just place an asterisk atthe start of a paragraph and indent properly. The same goes for numberedlists; they can also be autonumbered using a#
sign:
* This is a bulleted list.* It has two items, the second item uses two lines.1. This is a numbered list.2. It has two items too.#. This is a numbered list.#. It has two items too.
Nested lists are possible, but be aware that they must be separated from theparent list items by blank lines:
* this is* a list* with a nested list* and some subitems* and here the parent list continues
Definition lists (ref) are created as follows:
term (up to a line of text) Definition of the term, which must be indented and can even consist of multiple paragraphsnext term Description.
Note that the term cannot have more than one line of text.
Quoted paragraphs (ref) are created by just indentingthem more than the surrounding paragraphs.
Line blocks (ref) are a way of preserving line breaks:
| These lines are| broken exactly like in| the source file.
There are also several more special blocks available:
field lists (ref, with caveats noted inField Lists)
option lists (ref)
quoted literal blocks (ref)
doctest blocks (ref)
Literal blocks¶
Literal code blocks (ref) are introduced by ending aparagraph with the special marker::
. The literal block must be indented(and, like all paragraphs, separated from the surrounding ones by blanklines):
This is a normal text paragraph. The next paragraph is a code sample:: It is not processed in any way, except that the indentation is removed. It can span multiple lines.This is a normal text paragraph again.
The handling of the::
marker is smart:
If it occurs as a paragraph of its own, that paragraph is completely left outof the document.
If it is preceded by whitespace, the marker is removed.
If it is preceded by non-whitespace, the marker is replaced by a singlecolon.
That way, the second sentence in the above example’s first paragraph would berendered as “The next paragraph is a code sample:”.
Code highlighting can be enabled for these literal blocks on a document-widebasis using thehighlight
directive and on a project-wide basisusing thehighlight_language
configuration option. Thecode-block
directive can be used to set highlighting on ablock-by-block basis. These directives are discussed later.
Doctest blocks¶
Doctest blocks (ref) are interactive Python sessionscut-and-pasted into docstrings. They do not require theliteral blocks syntax. The doctest block must endwith a blank line and shouldnot end with an unused prompt:
>>> 1 + 12
Tables¶
Forgrid tables (ref), you have to “paint” the cellgrid 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 (ref) are easier to write, butlimited: they must contain more than one row, and the first column cells cannotcontain multiple lines. They look like this:
===== ===== =======A B A and B===== ===== =======False False FalseTrue False FalseFalse True FalseTrue True True===== ===== =======
Two more syntaxes are supported:CSV tables andList tables. They use anexplicit markup block. Refer toTables for more information.
Hyperlinks¶
External links¶
URLs and email addresses in text are automatically linked and do not needexplicit markup at all.For example,https://domain.invalid/ is written with no special markupin the source of this document, and is recognised as an external hyperlink.
To create text with a link, the best approach is generally to put the URLbelow the paragraph as follows (ref):
This is a paragraph that contains`a link`_..._a link: https://domain.invalid/
This keeps the paragraph more readable in source code.
Alternatively, you can embed the URL within the prose for an ‘inline link’.This can lead to longer lines, but has the benefit of keeping the link textand the URL pointed to in the same place.This uses the following syntax:`Linktext<https://domain.invalid/>`__
(ref).
Important
There must be a space between the link textand the opening angle bracket (’<
’) for the URL.
Tip
Use two trailing underscores when embedding the URL.Technically, a single underscore works as well,but that would create a named reference instead of an anonymous one.Named references typically do not have a benefit when the URL is embedded.Moreover, they have the disadvantage that you must make sure that youdo not use the same “Link text” for another link in your document.
You can also separate the link and the target definition (ref), like this:
This is a paragraph that contains`a link`_..._a link: https://domain.invalid/
Internal links¶
Internal linking is done via a special reStructuredText role provided by Sphinx,see the section on specific markup,Cross-referencing arbitrary locations.
Sections¶
Section headers (ref) are created by underlining (andoptionally overlining) the section title with a punctuation character, at leastas long as the text:
=================This is a heading=================
Normally, there are no heading levels assigned to certain characters as thestructure is determined from the succession of headings. However, thisconvention is used inPython Developer’s Guide for documenting which you mayfollow:
#
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 reStructuredTextdocumentation), and use a deeper nesting level, but keep in mind that mosttarget formats (HTML, LaTeX) have a limited supported nesting depth.
Field Lists¶
Field lists (ref) are sequences of fields marked up likethis:
:fieldname: Field content
They are commonly used in Python documentation:
def my_function(my_arg, my_other_arg): """A function just for me.:param my_arg: The first of my arguments.:param my_other_arg: The second of my arguments.:returns: A message (just for me, of course). """
Sphinx extends standard docutils behavior and intercepts field lists specifiedat the beginning of documents. Refer toField Lists for moreinformation.
Roles¶
A role or “custom interpreted text role” (ref) is an inlinepiece of explicit markup. It signifies that the enclosed text should beinterpreted in a specific way. Sphinx uses this to provide semantic markup andcross-referencing of identifiers, as described in the appropriate section. Thegeneral syntax is:rolename:`content`
.
Docutils supports the following roles:
emphasis – equivalent of
*emphasis*
strong – equivalent of
**strong**
literal – equivalent of
``literal``
subscript – subscript text
superscript – superscript text
title-reference – for titles of books, periodicals, and othermaterials
Refer toRoles for roles added by Sphinx.
Explicit Markup¶
“Explicit markup” (ref) is used inreStructuredText 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 bywhitespace and is terminated by the next paragraph at the same level ofindentation. (There needs to be a blank line between explicit markup andnormal paragraphs. This may all sound a bit complicated, but it is intuitiveenough when you write it.)
Directives¶
A directive (ref) is a generic block of explicit markup.Along with roles, it is one of the extension mechanisms of reStructuredText,and Sphinx makes heavy use of it.
Docutils supports the following directives:
Admonitions:attention,caution,danger,error,hint,important,note,tip,warning and the genericadmonition. (Most themes style only “note” and“warning” specially.)
Images:
Additional body elements:
contents (a local, i.e. for the current fileonly, table of contents)
container (a container with a custom class, useful to generate anouter
<div>
in HTML)rubric (a heading without relation to the document sectioning)
parsed-literal (literal block that supports inline markup)
epigraph (a block quote with optional attribution line)
highlights,pull-quote (block quotes with their ownclass attribute)
compound (a compound paragraph)
Special tables:
table (a table with title)
csv-table (a table generated from comma-separated values)
list-table (a table generated from a list of lists)
Special directives:
raw (include raw target-format markup)
include (include reStructuredText from another file) – in Sphinx,when given an absolute include file path, this directive takes it asrelative to the source directory
class (assign a class attribute to the next element)
Note
When the default domain contains a
class
directive, this directivewill be shadowed. Therefore, Sphinx re-exports it asrst-class
.Tip
If you want to add a class to a directive,you may consider the
:class:
option instead,which is supported by most directives and allows for a more compact notation.
HTML specifics:
meta(generation of HTML
<meta>
tags, see alsoHTML Metadata below)title (override document title)
Influencing markup:
default-role (set a new default role)
role (create a new role)
Since these are only per-file, better use Sphinx’s facilities for setting the
default_role
.
Directives added by Sphinx are described inDirectives.
Basically, a directive consists of a name, arguments, options and content.(Keep this terminology in mind, it is used in the next chapter describingcustom directives.) Looking at this example,
..function:: foo(x) foo(y, z):module: some.module.name Return a line of text input from the user.
function
is the directive name. It is given two arguments here, theremainder of the first line and the second line, as well as one optionmodule
(as you can see, options are given in the lines immediatelyfollowing the arguments and indicated by the colons). Options must be indentedto the same level as the directive content.
The directive content follows after a blank line and is indented relative tothe directive start or if options are present, by the same amount as theoptions.
Be careful as the indent is not a fixed number of whitespace, e.g. three, butany number whitespace. This can be surprising when a fixed indent is usedthroughout the document and can make a difference for directives which aresensitive to whitespace. Compare:
..code-block:::caption: A cool example The output of this line starts with four spaces...code-block:: The output of this line has no spaces at the beginning.
In the first code block, the indent for the content was fixated by the optionline to three spaces, consequently the content starts with four spaces.In the latter the indent was fixed by the content itself to seven spaces, thusit does not start with a space.
Images¶
reStructuredText supports an image directive (ref), used like so:
..image:: gnu.png (options)
When used within Sphinx, the file name given (heregnu.png
) must either berelative to the source file, or absolute which means that they are relative tothe top source directory. For example, the filesketch/spam.rst
couldrefer to the imageimages/spam.png
as../images/spam.png
or/images/spam.png
.
Sphinx will automatically copy image files over to a subdirectory of the outputdirectory on building (e.g. the_static
directory for HTML output.)
Interpretation of image size options (width
andheight
) is as follows:if the size has no unit or the unit is pixels, the given size will only berespected for output channels that support pixels. Other units (likept
forpoints) will be used for HTML and LaTeX output (the latter replacespt
bybp
as this is the TeX unit such that72bp=1in
).
Sphinx extends the standard docutils behavior by allowing an asterisk for theextension:
..image:: gnu.*
Sphinx then searches for all images matching the provided pattern anddetermines their type. Each builder then chooses the best image out of thesecandidates. For instance, if the file namegnu.*
was given and two filesgnu.pdf
andgnu.png
existed in the source tree, the LaTeXbuilder would choose the former, while the HTML builder would prefer thelatter. Supported image types and choosing priority are defined atBuilders.
Note that image file names should not contain spaces.
Changed in version 0.4:Added the support for file names ending in an asterisk.
Changed in version 0.6:Image paths can now be absolute.
Changed in version 1.5:latex target supports pixels (default is96px=1in
).
Footnotes¶
For footnotes (ref), use[#name]_
to mark the footnotelocation, and add the footnote body at the bottom of the document after a“Footnotes” rubric heading, like so:
Lorem ipsum[#f1]_ dolor sit amet ...[#f2]_..rubric:: Footnotes..[#f1] Text of the first footnote...[#f2] Text of the second footnote.
You can also explicitly number the footnotes ([1]_
) or use auto-numberedfootnotes without names ([#]_
).
Citations¶
Standard reStructuredText citations (ref) are supported,with the additional feature that they are “global”,i.e. all citations can be referenced from all files. Use them like so:
Lorem ipsum[Ref]_ dolor sit amet...[Ref] Book or article reference, URL or whatever.
Citation usage is similar to footnote usage, but with a label that is notnumeric or begins with#
.
Substitutions¶
reStructuredText supports “substitutions” (ref),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:
..|name|replace:: replacement*text*
or this:
..|caution|image:: warning.png:alt: Warning!
See thereStructuredText reference for substitutions for details.
If you want to use some substitutions for all documents, put them intorst_prolog
orrst_epilog
or put them into a separate fileand include it into all documents you want to use them in, using theinclude directive. (Be sure to give the include file a file nameextension differing from that of other source files, to avoid Sphinx finding itas a standalone document.)
Sphinx defines some default substitutions, seeSubstitutions.
Comments¶
Every explicit markup block which isn’t a valid markup construct (like thefootnotes above) is regarded as a comment (ref). Forexample:
.. This is a comment.
You can indent text after a comment start to form multiline comments:
.. This whole indented block is a comment. Still in the comment.
HTML Metadata¶
Themeta directive allows specifying the HTMLmetadata element of a Sphinx documentation page. For example, thedirective:
..meta:::description: The Sphinx documentation builder:keywords: Sphinx, documentation, builder
will generate the following HTML output:
<metaname="description"content="The Sphinx documentation builder"><metaname="keywords"content="Sphinx, documentation, builder">
Also, Sphinx will add the keywords as specified in the meta directive to thesearch index. Thereby, thelang
attribute of the meta element isconsidered. For example, the directive:
..meta:::keywords: backup:keywords lang=en: pleasefindthiskey pleasefindthiskeytoo:keywords lang=de: bittediesenkeyfinden
adds the following words to the search indices of builds with different languageconfigurations:
pleasefindthiskey
,pleasefindthiskeytoo
toEnglish builds;bittediesenkeyfinden
toGerman builds;backup
to builds in all languages.
Source encoding¶
Sphinx supports source files that are encoded in UTF-8.This means that the full range ofUnicode characters may be useddirectly in reStructuredText.
Gotchas¶
There are some problems one commonly runs intowhile authoring reStructuredText documents:
Separation of inline markup: As said above, inline markup spans must beseparated from the surrounding text by non-word characters, you have to use abackslash-escaped space to get around that. Seethe reference for the details.
No nested inline markup: Something like
*see:func:`foo`*
is notpossible.