Li-Pro.Net Sphinx Primer

PREAMBLE

How to write Li-Pro.Net documentation with Sphinx.

Excerpts from the Sphinx Tutorial by Eric Holscher and Documentation Style Guide by Bareos GmbH & Co. KG and others. See [juh2019swdocwspx] for an introduction to Sphinx.

This documentation is built using Sphinx, a static-site generator designed to create structured, semantic, and internally consistent documentation. Source documents are written in reStructuredText, a semantic, extensible markup syntax similar to Markdown. reStructuredText is a better tool than Markdown for documentation.

Note

Sphinx and reStructuredText can be very flexible. For the sake of consistency and maintainability, this how to guide is highly opinionated about how documentation source files are organized and marked up.

Concepts

Section author: Stephan Linz <linz@li-pro.net>

Let’s document the project. A lot of these reStructuredText syntax examples are covered in the Sphinx reStructuredText Primer. The outline for this chapter has been taken from Documenting Python and adapted and extended for our needs.

Use of whitespace

All reStructuredText files use an indentation of three (3) spaces; no tabs are allowed. The maximum line length is 80 characters for normal text, but tables, deeply indented code samples and long links may extend beyond that. Code example bodies should use normal four-(4)-space indentation.

Make generous use of blank lines where applicable; they help group things together.

Indentation

Indentation is meaningful in Sphinx and reStructuredText text. Usually, indenting a section means that is “belongs to” the line it is indented under.

for example
1
2
3
4
.. figure:: path-to-image.*

   This is the caption of the figure. Notice that it is indented under
   the line defining the figure.

The rules for indentation are:

  • Use spaces, not tabs.

  • Generally, indent three (3) spaces.

  • Code example, indent four (4) spaces, except reStructuredText examples.

The exception to the three (3) spaces rule is Unordered (bullet) Lists and Ordered (numbered) Lists, where indentation follows the content of the list item.

unordered (bulleted) list

(2) spaces
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
* This is a list item.

  This is some additional content related to first item. Notice that
  it is indented to the same column as the first line of content.
  In this case, that's three (2) spaces.

.
.
.

* The N-th item in a list.

ordered (numbered) list

(4) spaces
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
1.  This is a list item.

    This is some additional content related to Item 1. Notice that
    it is indented to the same column as the first line of content.
    In this case, that's three (3) spaces.

.
.
.

10. The tenth item in a list.

    This related content will be indented four (4) spaces.

Sphinx naming

reStructuredText/Sphinx have some specific wording:

Roles

A role or “custom interpreted text role” is an inline piece of explicit markup, see Inline Markup and Explicit Markup. It signifies that the enclosed text should be interpreted in a specific way. Sphinx uses this to provide semantic markup and cross-referencing of identifiers, as described in the appropriate section.

The general syntax is :rolename:`content`. Like Directives, roles are extensible. Own roles can be created. They are used inside other text structures.

Docutils supports the following roles (incomplete list):

:emphasis:

emphasis:emphasis:`emphasis` – equivalent of *emphasis*

:strong:

strong:strong:`strong` – equivalent of **strong**

:literal:

literal:literal:`literal` – equivalent of ``literal``

:code:

code:code:`code` – equivalent of ``code``

:subscript:

subscript:subscript:`subscript` – subscript text

The example

The Fibonacci numbers (without inline role for Mathematics).

1
2
3
4
.. |gE| unicode:: U+02267 .. GREATER-THAN OVER EQUAL TO

*f*\ :subscript:`n` = *f*\ :subscript:`n-1` + *f*\ :subscript:`n-2`
for *n* |gE| 3 with *f*\ :subscript:`1` = *f*\ :subscript:`2` = 1
Which gives

fn = fn-1 + fn-2 for n ≧ 3 with f1 = f2 = 1

:superscript:

superscript:superscript:`superscript` – superscript text

The example

The elementary charge (without inline role for Mathematics).

1
2
3
.. |sdot| unicode:: U+022C5 .. DOT OPERATOR

*e* = 1.602176634 |sdot| 10\ :superscript:`-19` C
Which gives

e = 1.602176634 ⋅ 10-19 C

:math:

math:math:`mathematic equations` – for Mathematics equations

:pep-reference:

pep-reference:pep-reference:`pep-reference` – equivalent to :pep:`pep reference number` – for External References into the PEP index

:rfc-reference:

rfc-reference:rfc-reference:`rfc-reference` – equivalent to :rfc:`rfc reference number` – for External References into the RFC index

:title-reference:

title-reference:title-reference:`title-reference` – for titles of books, periodicals, and other materials

See also

Directives

A directive is a generic block of Explicit Markup. Besides roles, it is one of the extension mechanisms of reStructuredText, and Sphinx makes heavy use of it.

Basically, a directive consists of a name, arguments, options and content. Keep this terminology in mind, it is used in section Explicit Markup describing custom directives. Looking at this example, that allows marking a block of content with special meaning.

basic directive syntax looks like this

the example
1
2
3
4
5
6
7
8
.. directive:: arg1 arg2 ...
   :option1: value
   :option2: value
   :option5: value
   ...

   Multiline content of the directive,
   ...

This line is no longer part of the block controlled by the directive.

directive

That is the directive name. It is given two arguments here.

arg1, arg2, ...

Arguments. The last argument can contain spaces (depending on the directive implementation).

:option0:, :option1:, ... :option9:

Options are optional. As you can see, options are given in the lines immediately following the arguments and indicated by the colons.

Multiline content of the directive,

The directive content follows after a blank line and is indented relative to the directive start.

Directives are supplied not only by Docutils, but Sphinx and custom extensions can add their own. Directives are written as a block.

Docutils supports the following directives (incomplete list):

Warning

Do not use the directives sectnum, header and footer.

See also

Footnotes

1

When the default domain contains a class directive, this directive will be shadowed. Therefore, Sphinx re-exports it as rst-class.

Domains

A domain is a collection of explicit and inline markup (reStructuredText Directives and Roles) to describe and link to objects belonging together, e.g. elements of a programming language. Directive and role names in a domain have names like domain:name, e.g. .. c:function:: int main(int argc, char **argv, char **env) or :c:func:`main`.

An object is 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.

The Standard Domain collects all markup that does not warrant a domain of its own. Its directives and roles are not prefixed with a domain name.

There is a set of directives allowing documenting command-line programs:

Sphinx directives for command-line programs

short description

directive (target)

role (reference)

Following document options for the program.

.. program:: name

Describes a command line argument or switch.

.. option:: name args, ...

:option:`name arg`

Describes an environment variable.

.. envvar:: name

:envvar:`name`

There is also a very generic object description directive, which is not tied to any domain. This directive produces the same formatting as the specific ones provided by domains, but does not create index entries or cross-referencing targets:

Sphinx directives for unspecific objects without referencing

short description

directive (target)

role (reference)

Describes an unspecific element.

.. describe:: text

Describes an unspecific object.

.. object:: text

Originally, Sphinx was conceived for a single project, the documentation of the Python language. Shortly afterwards, it was made available for everyone as a documentation tool, but the documentation of Python modules remained deeply built in – the most fundamental directives, like function, were designed for Python objects.

Since Sphinx has become somewhat popular, interest developed in using it for many different purposes: C/C++ projects, JavaScript, or even reStructuredText markup (like in this documentation). The following specific domains are provided by Sphinx (without additional extensions):

See also

Parts, Chapters, Titles, Sections

Every Sphinx document has multiple level of headings. Section headers are created by underlining (and optionally overlining) the section title with a punctuation character, at least as long as the text.

Normally, there are no heading levels assigned to certain characters as the structure is determined from the succession of headings. However, for this documentation, here is a suggested convention as covered in the Sphinx reStructuredText Primer to use them in this order:

  • # for title – with overline, for parts

  • * for subtitle – with overline, for chapters

  • =, for sections

  • -, for subsections

  • ^, for subsubsections

  • =, for paragraphs

They give structure to the document, which is used in navigation and in the display in all output formats. The part section header is not used at all. All regular documents starts with a title heading underlined by #. Therefore the specific names part, chapter, section,… might not match the actual context. Generally we speak about “sections” (or “section headings” or “section markers”).

Note

With reStructuredText, there is no leaving out a section level. If you write a chapter it is not possible to continue with a paragraph. Instead the next section must be of the type title.

If you try to do it overwise (chapter 1 * with overline → paragraph "), the “paragraph” is treated as a “title”. And if you continue by another chapter in the same file (chapter 2 * with overline → title #), sphinx-build got confused and at least produces a warning (Title level inconsistent) and possibly renders the result incorrectly.

the convention
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
####################################
Part -- Number Signs above and below
####################################

with overline, for parts

************************************
Chapter -- Asterisks above and below
************************************

with overline, for chapters

Title -- Number Signs
#####################

Suptitle -- Asterisks
*********************

Section -- Equal Signs
======================

Subsection -- Hyphens
---------------------

Subsubsection -- Circumflex
^^^^^^^^^^^^^^^^^^^^^^^^^^^

Paragraph -- Double Quotes
""""""""""""""""""""""""""

Table of Contents Tree

Now would be a good time to introduce the .. toctree::. One of the main concepts in Sphinx is that it allows multiple pages to be combined into a cohesive hierarchy. Since reStructuredText 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 and a fundamental part of this structure. Consider this example:

.. toctree::

For more details, see toctree directive.

The example
1
2
3
4
5
6
.. toctree::
   :maxdepth: 2

   install
   support
   (many more files listed here)
Which gives
index
├── install
├── support
├── (many more files here)
    ├── (many more sub-files here)

The above directive example will output a TOC in the page where it occurs, using the individual TOCs (including “sub-TOC trees”) of the files given in the directive body. The :maxdepth: 2 argument tells Sphinx to include 2 levels of headers in it’s output. It will output the 2 top-level headers of the pages listed; by default, all levels are included. This also tells Sphinx that the other pages are sub-pages of the current page, creating a “tree” structure of the pages.

This accomplishes two things:

  • Tables of contents from all those files are inserted, with a maximum depth of argument :maxdepth:, that means one nested heading. .. toctree:: directives in those files are also taken into account.

  • Sphinx knows that the relative order of the files install, support and so forth, and it knows that they are children of the shown file, the library index. From this information it generates “next chapter”, “previous chapter” and “parent chapter” links.

In the end, all files included in the build process must occur in (only) one .. 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.

The special file index.rst at the root of the source directory is the “root” of the TOC tree hierarchy; from it the “Contents” page is generated.

Note

The TOC Tree is also used for generating the navigation elements inside Sphinx. It is quite important, and one of the most powerful concepts in Sphinx.

Secondary sub-TOC trees

Collections of documents are mostly given their own table of content on an individual page (see, for example: Appendix and Glossary). In these cases, the page containing the .. toctree:: serves as a sort of intro page for the collection. That intro must, itself, be included in the Sidebar navigation menu. The contents of a .. toctree:: appear as section links in another .. toctree:: it is included in. That is, if a .. toctree:: in index.rst lists .. glossary::, and glossary.rst has a .. toctree::, then the contents of that second .. toctree:: will appear in the Sidebar navigation menu, as sub-items to Glossary.

Indeed, this is precisely the case in this Li-Pro.Net Sphinx Primer document currently.

How this document uses main and secondary TOC

  • Major topics get a .. toctree:: in index.rst

    Major topics include things like:

    • Each major parts (Extensions, Themes,…)

    • Large, general categories like Releases, Contributing, or Building

    Major topic tables of content include both sub-collection intro pages and also individual pages that don’t fit into a sub-collection.

    The :caption: attribute of the .. toctree:: directive may but not must defines the section label in the Sidebar navigation menu.

  • Within a large topic, documents are grouped into collections of related pages, defined by a .. toctree:: on a topic intro page.

    Intro pages (pages that contain secondary .. toctree:: directives) may include additional content, introducing the collection or providing contextual way-finding. However, this is not always necessary or desirable. Use your judgment, and avoid stating things just for the sake of having some text. (“Here are the pages in this collection.”)

    We also (very occasionally) include .. toctree:: directives in sub-collection pages, such as:

Tip

If it not obvious where a new document should appear in the navigation, the best practice is to simply ask about it in the GitHub issue driving the new page.

Note

For way-finding purposes, we sometimes create an Unordered (bullet) Lists of page links rather than a .. toctree:: directive (for example, see index.rst). We do this when using a .. toctree:: would create redundant links in the Sidebar navigation menu.

Paragraphs

The paragraph is the most basic block in 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-aligned to the same level of indentation. General rules can be looked up under Use of whitespace.

the example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
Paragraphs are separated by blank lines. Line breaks in the source code do not create line breaks in the output.

This means that you *could*, in theory,
include a lot of arbitrary line breaks
in your source document files.
These line breaks would not appear in the output.
Some people like to do this because they have been trained
to not exceed 80 column lines, and they like
to write :file:`.txt` files this way.
Please do not do this.

There is **no reason** to put a limit on line length in source files for documentation, since this is prose and not code.
Therefore, please do not put arbitrary line breaks in your files.
which gives

Paragraphs are separated by blank lines. Line breaks in the source code do not create line breaks in the output.

This means that you could, in theory, include a lot of arbitrary line breaks in your source document files. These line breaks would not appear in the output. Some people like to do this because they have been trained to not exceed 80 column lines, and they like to write .txt files this way. Please do not do this.

There is no reason to put a limit on line length in source files for documentation, since this is prose and not code. Therefore, please do not put arbitrary line breaks in your files.

Quotes (block quotation) Element

Block quoted paragraphs are quoted by just indenting them more than the surrounding paragraphs.

the example
1
2
3
4
5
6
7
8
9
This line is not a block quote. Block quotes are indented,
and otherwise unadorned.

   This is a block quote.

   --Adam Michael Wood - `Technical Content Writer`_

.. _`Technical Content Writer`:
   http://adammichaelwood.com/portfolio/
which gives

This line is not a block quote. Block quotes are indented, and otherwise unadorned.

This is a block quote.

—Adam Michael Wood - Technical Content Writer

.. pull-quote::

Pull-quoted paragraphs are similar to blockquotes but are directives for small selection of text to “pull out and quote”, typically in a larger typeface.

The example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
This line is not a pull quote.
Pull quotes are directive content.

.. pull-quote::

   This is a pull quote.

   --Adam Michael Wood - `Technical Content Writer`_

.. _`Technical Content Writer`:
   http://adammichaelwood.com/portfolio/
Which gives

This line is not a pull quote. Pull quotes are directive content.

This is a pull quote.

—Adam Michael Wood - Technical Content Writer

Line Blocks

Line blocks are useful for addresses, verse, and adornment-free lists. They are quoted by just a | pipe sign in front of each single line.

the example
1
2
3
4
| Each new line begins with a
| vertical bar ("``|``").
|     Line breaks and initial indents
|     are preserved.
which gives
Each new line begins with a
vertical bar (“|”).
Line breaks and initial indents
are preserved.

Doctest Blocks

Doctest blocks 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 an unused prompt, see Doctest blocks in Sphinx for more informations.

the example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
>>> print('this is a Doctest block')
this is a Doctest block

>>> print('Python-specific usage examples; begun with ">>>"')
Python-specific usage examples; begun with ">>>"
>>> print('(cut and pasted from interactive Python sessions)')
(cut and pasted from interactive Python sessions)

>>> a = [51,27,13,56]
>>> b = dict(enumerate(a))
>>> print(b)
{0: 51, 1: 27, 2: 13, 3: 56}
which gives
>>> print('this is a Doctest block')
this is a Doctest block
>>> print('Python-specific usage examples; begun with ">>>"')
Python-specific usage examples; begun with ">>>"
>>> print('(cut and pasted from interactive Python sessions)')
(cut and pasted from interactive Python sessions)
>>> a = [51,27,13,56]
>>> b = dict(enumerate(a))
>>> print(b)
{0: 51, 1: 27, 2: 13, 3: 56}

Inline Markup

If you want to make sure that text is shown in monospaced fonts for code examples or concepts, use double backticks around it. It looks like this on output.

the example
1
You can use **backticks** for showing ``highlighted`` code.
which gives

You can use backticks for showing highlighted code.

Refer to Inline markup added by Sphinx.

All the standard reStructuredText inline markups are quite simple, use:

  • one asterisk: *text* for emphasis (italics),

  • two asterisks: **text** for strong emphasis (boldface), and

  • backquotes: ``text`` for code samples as shown above (literal).

If asterisks or backquotes appear in running text and could be confused with inline markup delimiters, they have to be escaped with a backslash or encapsulated by Roles:

one escaped asterisk

the example
1
2
*italics \*with\* asterisk*,
**boldface \*with\* asterisk**
which gives

italics *with* asterisk, boldface *with* asterisk

two escaped asterisks

the example
1
2
*italics \*\*with\*\* asterisks*,
**boldface \*\*with\*\* asterisks**
which gives

italics **with** asterisks, boldface **with** asterisks,

two escaped backquotes

the example
1
2
*italics \`\`with\`\` backquotes*,
**boldface \`\`with\`\` backquotes**
which gives

italics ``with`` backquotes, boldface ``with`` backquotes

escaped backquote and asterisks

the example
1
:literal:`literal \`\`with\`\` backquotes **and** asterisks`
which gives

literal ``with`` backquotes **and** asterisks

Be aware of some restrictions of this markup:

  • it may not be nested (see nested inline markup in Docutils To Do List),

  • content may not start or end with whitespace: * text* is wrong,

  • it must be separated from surrounding text by non-word characters. Use a backslash escaped space to work around that: thisis\ **one**\ word (thisisoneword).

File, Directory, Path

File and directories (or generally paths) are formated by :file: inline markup. Backslashes (Windows paths) \ have to written as \\. The name of an executable program should be documented by :program: inline markup. 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. For OS-level command use :command: inline markup.

:file:

For more details, see file role; about the program role in Semantic Descriptions and References, and about the command role in Writing about User Interface.

The example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
| :file:`/bin/bash` or :file:`bash` -- but better is :command:`bash`
| :file:`/usr/local/bin/myapp` -- but better is :program:`myapp`

| :file:`filename.txt`
| :file:`/path/filename.txt`
| :file:`/path/subdir/` (ends with a ``/``)

| :file:`..\\MyApp\\core.conf`
| :file:`C:\\ProgramData\\MyApp\\core.conf`
| :file:`C:\\ProgramData\\MyApp\\` (ends with a ``\``)

| :file:`/usr/share/man/man{N}` (ends with a variable mark, *N* = 1..9)
Which gives
/bin/bash or bash – but better is bash
/usr/local/bin/myapp – but better is myapp
filename.txt
/path/filename.txt
/path/subdir/ (ends with a /)
..\MyApp\core.conf
C:\ProgramData\MyApp\core.conf
C:\ProgramData\MyApp\ (ends with a \)
/usr/share/man/manN (ends with a variable mark, N = 1..9)

Lists, Definition Lists

List markup is natural: just place an asterisk or hyphen at the start of a paragraph and indent properly. The same goes for numbered list (number or letter with tailed dot); they can also be automatically numbered using a # sign.

Nested lists are possible, but be aware that they must be separated from the parent list items by blank lines.

Unordered (bullet) Lists

Bullet lists contains list item elements which are uniformly marked with bullets. Bullets are typically simple dingbats (symbols) such as circles and squares.

bulleted lists ( <ul> )

the example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
* This is a bulleted list ...
* ... use asterisks.
* It has fife items, the third
  item uses two lines.
* Are unindented at the first level.
* Must have a blank line before and after.

  - This is a bulleted list ...
  - ... use hyphens.
  - Are indented at the first level to stand out from the
    previous paragraph.

    - the blank line requirement means that nested list items
      will have a blank line before and after as well

    - you may *optionally* put a blank line *between* list items
which gives
  • This is a bulleted list …

  • … use asterisks.

  • It has fife items, the third item uses two lines.

  • Are unindented at the first level.

  • Must have a blank line before and after.

    • This is a bulleted list …

    • … use hyphens.

    • Are indented at the first level to stand out from the previous paragraph.

      • the blank line requirement means that nested list items will have a blank line before and after as well

      • you may optionally put a blank line between list items

Ordered (numbered) Lists

Enumerated lists (a.k.a. “ordered” lists) are similar to bullet lists, but use enumerators instead of bullets. An enumerator consists of an enumeration sequence member and formatting, followed by whitespace. Different enumeration sequences are possible, e.g. Arabic or Roman numerals or alphabet characters.

numbered lists ( <ol> )

the example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
1. This is a numbered list.
2. Start each line with a number and period.
3. Can begin on any number.

8. Must have a blank line before and after.
9. Can have nested sub-lists.

   a. nested lists are numbered separately
   #. nested lists need a blank line before and after

#. Can have automatic number with the ``#`` character.
which gives
  1. This is a numbered list.

  2. Start each line with a number and period.

  3. Can begin on any number.

  1. Must have a blank line before and after.

  2. Can have nested sub-lists.

    1. nested lists are numbered separately

    2. nested lists need a blank line before and after

  3. Can have automatic number with the # character.

Definition (description) Lists

Definition Lists contains a list of terms and their definitions. Each list item element contains a term, optional classifiers, and a definition.

definition list ( <dl> )

the example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
Definition list
   a list with several term-definition pairs in the form

   .. parsed-literal::

      **TERM**
         DEFINITION (*description of term*)

   Terms
      should not be indented

   Definitions
      should be indented under the term

Line spacing
   there should be a blank line between term-definition pairs
which gives
Definition list

a list with several term-definition pairs in the form

TERM
   DEFINITION (description of term)
Terms

should not be indented

Definitions

should be indented under the term

Line spacing

there should be a blank line between term-definition pairs

Field (description) Lists

Field lists are special definition lists. They may also be used for two-column table-like structures resembling database records (label & data pairs). Sphinx extends standard docutils behavior for Field Lists and intercepts field lists specified at the beginning of documents and adds some extra (optional) functionality.

field list

the example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
:Date: 2001-08-16
:Version: 1
:Authors: - Me
          - Myself
          - I
:Indentation: Since the field marker may be quite long, the second
   and subsequent lines of the field body do not have to line up
   with the first line, but they must be indented relative to the
   field name marker, and they must line up with each other.
:Parameter i: integer
which gives
Date

2001-08-16

Version

1

Authors
  • Me

  • Myself

  • I

Indentation

Since the field marker may be quite long, the second and subsequent lines of the field body do not have to line up with the first line, but they must be indented relative to the field name marker, and they must line up with each other.

Parameter i

integer

Explicit Markup

“Explicit markup” is used in reStructuredText 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 two dots 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.

Comments

Every explicit markup block which is not a valid markup construct (like the footnotes above) is regarded as a comment.

However, it must have some text in the ".. " line, otherwise it is ignored, and content will be displayed (indented).

the example
1
2
3
4
5
6
7
8
9
.. This is a comment
..
   _so: is this!
..
   [and] this!
..
   this:: too!
..
   |even| this:: !

Directives

Directives are generic blocks of explicit markup. Besides Roles, it is one of the extension mechanisms of reStructuredText, and Sphinx makes heavy use of it. Basically, a directive consists of a name, arguments, options and content. Keep this terminology in mind, it is used in one of the next chapter describing custom directives.

the example
1
2
3
4
5
.. cpp:function:: char* foo(x)
                  char* foo(y, z)
   :noindexentry:

   Return a line of text input from the user.
which gives
char *foo(x)
char *foo(y, z)

Return a line of text input from the user.

.. cpp: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 :noindexentry:. As you can see, options are given in the lines immediately following the arguments and indicated by the colons.

The directive content follows after a blank line and is indented relative to the directive start.

If you want to suppress the addition of an entry in the shown index, you can give the directive option flag :noindexentry:. If you want to typeset an object description, without even making it available for cross-referencing, you can give the directive option flag :noindex: (which implies :noindexentry:).

Hint

As far as possible, all examples in this document use the :noindexentry: option to keep the automatically created index as clean as possible but still be able to reference it.

Footnotes

For footnotes, use [#]_ to mark the footnote location, and add the footnote body at the bottom of the document after a “Footnotes” rubric heading.

the example
1
2
3
4
5
6
Lorem ipsum [#]_ dolor sit amet ... [#]_

.. rubric:: Footnotes

.. [#] Text of the first footnote.
.. [#] Text of the second footnote.
which gives

Lorem ipsum 1 dolor sit amet … 2

Footnotes

1

Text of the first footnote.

2

Text of the second footnote.

You can also explicitly number the footnotes for better context.

Citations

Citations are identical to footnotes except that they use only non-numeric labels such as [note]_ or [GVR2001]_. Citation labels are simple reference names (case-insensitive single words consisting of alphanumerics plus internal hyphens, underscores, and periods; no whitespace). Citations may be rendered separately and differently from footnotes.

the example
1
2
3
4
Here is a citation reference: [CIT2002]_.

.. [CIT2002] This is the citation. It's just like a footnote,
   except the label is textual.
which gives

Here is a citation reference: [CIT2002].

CIT2002

This is the citation. It’s just like a footnote, except the label is textual.

To use a professional bibliography, you should use the Sphinx extension BibTeX Citations.

Reuse Content

Sphinx supports several ways to reuse content within and across projects.

Include a Shared File

.. include::

For more details, see Including an External Document Fragment in Docutils.

You can store complex content, such as tasks, or code samples, in a file that is then included in multiple reStructuredText document files.

If you are working on multiple documents, you can save entire topics in shared files, and include those files in multiple documents.

You add a shared file to content in your project with the .. include:: directive. For example:

.. include:: /{absolut-document-subdirectory}/{file}.rsti
.. include:: {relative-document-subdirectory}/{file}.rsti

The contents of the shared file will then be built in the document.

Caution

Include paths are relative to the file in the document project, not the file in shared content.

Standard data files intended for inclusion in reStructuredText documents are distributed with the Docutils source code, located in the docutils package in the docutils/parsers/rst/include directory. To access these files, use the special syntax for standard include data files, angle brackets around the file name:

.. include:: <isonum.txt>

Note

You must reference the shared file from a file within the document. You cannot use a direct TOC reference to files outside of the document directory.

Substitutions

Substitutions are a useful way to define a value which is needed in many places. Substitution definitions are indicated by an explicit markup start (".. ") followed by a vertical bar, the substitution text (which gets substituted), another vertical bar, whitespace, and the definition block.

A substitution definition block may contain inline-compatible directives such as Images and Figures, Downloadable Files, or other Substitution Directives:

For more information, see reStructuredText Primer, section Substitutions, or refer the Substitution References. Sphinx provides additional predefined Substitutions.

.. replace::
The example
1
2
3
.. |RST| replace:: reStructuredText

Here, :rst:`|RST|` will be replaced by |RST|.
Which gives

Here, |RST| will be replaced by reStructuredText.

Styled Reference

You can also create a reference with styled text, nested inline markup.

the example
1
2
3
4
5
6
7
.. |gh| replace:: :strong:`GitHub`
.. _`gh`: https://github.com/

Here, :rst:`|gh|` will be replaced by |gh|.

You can use the hyperlink reference by appending a :rst:`"_"` at the end
of the vertical bars and :rst:`|gh|_` will be replaced by |gh|_.
which gives

Here, |gh| will be replaced by GitHub.

You can use the hyperlink reference by appending a "_" at the end of the vertical bars and |gh|_ will be replaced by GitHub.

Use Prolog and Epilog

The Sphinx configuration values rst_prolog and rst_epilog in conf.py contains a list of global substitutions that can be used from any file. The (incomplete) list for this document is given below:

"|project|"

→ leads to: “Li-Pro.Net Sphinx Primer”

"|author|"

→ leads to: “The LP/N Documentation Team”

"|publisher|"

→ leads to: “Li–Pro.Net”

"|copyright|"

→ leads to: “2020, Li–Pro.Net, The LP/N Documentation Team and individual contributors.”

"|LICENSE|"

→ leads to: “LICENSE

"|CREDITS|"

→ leads to: “CREDITS

Inline Image

You can add inline images in the document using substitutions. The following block of code substitutes arrow in the text with the image specified.

the example
1
2
3
4
5
6
:|lpn_16x16|: The logo as in front of this documentation.

.. |lpn_16x16| image:: /_images/lpn.*
               :alt: Li-Pro.Net.
               :height: 16px
               :width: 16px
which gives
Li-Pro.Net.

The logo as in front of this documentation.

Images and Figures

SVG Graphics only

All vector graphics or diagrams should be SVG files. This helps us keep our graphic conversion tooling simple, and generally results in higher-quality representation. SVG graphics with an parameterized opacity (transparency) should be possible as well as an animated SVG, see Figure 1.1 and Figure 1.2.

_images/transparent-vector.svg

Example of transparent SVG 1

_images/animated-vector.svg

Example of animated SVG 2

Whenever possible, you should generate your graphics as SVG rather than converting to SVG from another format. That avoids bitmap raster images embedded in a SVG container. The goal of SVG usage is to hold vector graphic as long as possible, from the editor up to the presentation. If you have to start in another vector graphic format use lossless vector formats whenever possible. These include EPS/PS, AI, DXF, EMF/EMZ, WMF/WMZ or some special XML vector graphics schemes. In any case avoid embedded bitmaps, as this is a lossy format for vector informations that does not replicate scaling very well. Figure 1.3 demonstrats differences between bitmapped raster and vector graphics. The bitmap raster is composed of a fixed set of pixels, while the vector is composed of a fixed set of shapes. In the picture, scaling the bitmap reveals the pixels while scaling the vector image preserves the shapes.

_images/rast-vs-vect.svg

Demonstration of differences between bitmapped raster and vector images. 3

Bitmap raster images are good for photographic images or screenshots but not for stencils, sketches, diagrams or graphs and often they do not support transparency.

—Superuser - JPEG vs. PNG vs. BMP vs. GIF vs. SVG

Raster graphics are resolution dependent, meaning they cannot scale up to an arbitrary resolution without loss of apparent quality. This property contrasts with the capabilities of vector graphics, which easily scale up to the quality of the device rendering them. Raster graphics deal more practically than vector graphics with photographs and photo-realistic images, while vector graphics often serve better for typesetting or for graphic design.

—Wikipedia - Raster graphics

Vector graphics have the unique advantage over raster graphics in that the points, lines, and curves may be scaled up or down to any resolution with no aliasing.

—Wikipedia - Vector graphics

Footnotes

1

Indication of provenance: STEAMcoded.org: atom1.svg (public domain for teachers and students learning to code)

2

Indication of provenance: STEAMcoded.org: atom.svg (public domain for teachers and students learning to code)

3

Indication of provenance: Wikimedia: 6/6b/Bitmap_VS_SVG.svg (licensed under CC-BY-SA-2.5)

PNG Images only

All still bitmap raster images or photos should be PNG files. This helps us keep our image compression tooling simple, and generally results in higher-quality screenshots. PNG images with an 8-bit transparency channel should be possible as well as an animated PNG, see Figure 1.4 and Figure 1.5.

_images/transparent-bitmap.png

Example of transparent PNG 4

_images/animated-bitmap.png

Example of animated PNG 5

Whenever possible, you should generate your images as PNG rather than converting to PNG from another format. If you have to start in another format, use lossless formats whenever possible. These include BMP/DIB, GIF, and TIFF. Avoid JPEG/JFIF if possible, as this is a lossy format that does not replicate screenshots very well. Figure 1.6 comparing lossy compression in JPEG with lossless compression in PNG: the JPEG artifacts can be easily visible in the background of this kind of image data, where the PNG image has solid color.

_images/lossless-vs-lossy.png

Demonstration of differences between lossy encoding and lossless method. 6

JPEG is good for photographic images but not for sharp transitions and does not support transparency.

—Wikipedia - PNG comparison with JPEG

The JPEG format can produce a smaller file than PNG for photographic (and photo-like) images, since JPEG uses a lossy encoding method specifically designed for photographic image data. Using PNG instead of a high-quality JPEG for such images would result in a large increase in filesize with negligible gain in quality. In comparison, when storing images that contain text, line art, or graphics – images with sharp transitions and large areas of solid color – the PNG format can compress image data more than JPEG can. Additionally, PNG is lossless, while JPEG produces visual artifacts around high-contrast areas.

JPEG’s lossy compression also suffers from generation loss, where repeatedly decoding and re-encoding an image to save it again causes a loss of information each time, degrading the image. This does not happen with repeated viewing or copying, but only if the file is edited and saved over again. Because PNG is lossless, it is suitable for storing images to be edited.

Where an image contains both sharp transitions and photographic parts, a choice must be made between the two effects:

Footnotes

4

Indication of provenance: Wikimedia: 4/47/PNG_transparency_demonstration_1.png (licensed under CC-BY-SA-3.0)

5

Indication of provenance: Wikimedia: 1/14/Animated_PNG_example_bouncing_beach_ball.png (released into the public domain by its author, Holger Will)

6

Indication of provenance: Superuser: a/55706, http://lbrandy.com/assets/jpg_vs_png2.png (licensed under CC-BY-SA-3.0)

Inserting

To place an graphic or image in a document, use the .. image:: directive (see Image).

.. image:: /img/{absolut-document-subdirectory}/{file}.svg
  :alt: Alt text. Every image should have descriptive alt text.

.. image:: {relative-document-subdirectory}/{file}.*
  :alt: Alt text. Every image should have descriptive alt text.

Note the literal asterisk (*) at the end, in place of a file extension. Use the asterisk, and omit the file extension (see reStructuredText Primer, section Images).

.. image::
The example
1
2
3
4
5
6
7
8
9
.. image:: /_images/lpn.svg
   :alt: The Li-Pro.Net logo. (explicitely as SVG)
   :height: 32px
   :width: 32px

.. image:: /_images/lpn.*
   :alt: The Li-Pro.Net logo. (scaled to the half)
   :scale: 50 %
   :align: right
Which gives
The Li-Pro.Net logo. (explicitely as SVG) The Li-Pro.Net logo. (scaled to the half)

Inserting with Captions

Use .. figure:: directive to markup a graphic or image with a caption (see Figure).

.. figure:: {file-with-directory-same-as-for image}.*
  :alt: Alt text. Every image should have descriptive alt text.

  The rest of the indented content will be the (optional) caption.
  This can be a short sentence or multiline paragraph.

Captions can contain any other complex reStructuredText markup. Further paragraphs after the caption will be the (optional) legend which are also arbitrary body elements.

.. figure::
The example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
.. figure:: /_images/lpn.*
   :name: the-lpn-logo
   :alt: The Li-Pro.Net logo.
   :figclass: align-center
   :align: center
   :scale: 75 %

   The |ghlpn|_ logo.

   Legend of all elements you can see in the graphic:

   .. list-table:: The legend for the |ghlpn|_ logo.
      :widths: 10 40
      :width: 50 %
      :align: center
      :header-rows: 1
      :stub-columns: 1

      * - Letter
        - Meaning
      * - L (in blue)
        - Li
      * - P (in blue)
        - Pro
      * - N (in red)
        - Net

.. |ghlpn| unicode:: Li U+02013 Pro.Net U+0040 GitHub
.. _`ghlpn`: https://github.com/lipro
Which gives

Inserting Inline

To information on creating inline images, see Inline Image.

Tables

For more details, see Table in Docutils or Tables Basics and Tables Directives.

.. table::

The .. table:: directive serves as optional wrapper of the Grid Style and Simple Style.

.. tabularcolumns::

The .. tabularcolumns:: directive gives a column spec for the next table occurring in the source file. The spec is the second argument to the LaTeX tabulary package’s environment (which Sphinx uses to translate tables). For more details, see tabularcolumns.

Grid Style

For more details, see Grid Tables in Docutils.

the example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
.. tabularcolumns:: p{0.132\linewidth}p{0.198\linewidth}p{0.330\linewidth}
.. table:: Example table in grid style
   :name: tables-grid-example
   :widths: 20, 30, 50
   :class: longtable
   :align: center
   :width: 66%

   +------------+------------+-----------+
   | Header 1   | Header 2   | Header 3  |
   +============+============+===========+
   | body row 1 | column 2   | column 3  |
   +------------+------------+-----------+
   | body row 2 | Cells may span columns.|
   +------------+------------+-----------+
   | body row 3 | Cells may  | - Cells   |
   +------------+ span rows. | - contain |
   | body row 4 |            | - blocks. |
   +------------+------------+-----------+
which gives
Example table in grid style

Header 1

Header 2

Header 3

body row 1

column 2

column 3

body row 2

Cells may span columns.

body row 3

Cells may span rows.

  • Cells

  • contain

  • blocks.

body row 4

Simple Style

For more details, see Simple Tables in Docutils.

the example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
.. tabularcolumns:: p{0.132\linewidth}p{0.198\linewidth}p{0.330\linewidth}
.. table:: Example table in simple style
   :name: tables-simple-example
   :widths: 20, 30, 50
   :align: center
   :width: 66%

   ====== ====== ======
       Inputs    Output
   ------------- ------
   A      B      A or B
   ====== ====== ======
   False
   --------------------
   True
   --------------------
   True   False  True
   ------ ------ ------
   False  True
   ====== =============
which gives
Example table in simple style

Inputs

Output

A

B

A or B

False

True

True

False

True

False

True

List Table

.. list-table::

For more details, see List Tables in Docutils.

Hint

For table content that needs a higher complexity than the list table is able to support use the flat-table.

The example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
.. tabularcolumns:: p{0.132\linewidth}p{0.198\linewidth}p{0.330\linewidth}
.. list-table:: Example list table
   :name: tables-list-example
   :widths: 20, 30, 50
   :class: longtable
   :header-rows: 1
   :align: center
   :width: 66%

   * - Treat
     - Quantity
     - Description
   * - Albatross
     - 2.99
     - On a stick!
   * - Crunchy Frog
     - 1.49
     - If we took the bones out, it would not be
       crunchy, now would it?
   * - Gannet Ripple
     - 1.99
     - On a stick!
Which gives
Example list table

Treat

Quantity

Description

Albatross

2.99

On a stick!

Crunchy Frog

1.49

If we took the bones out, it would not be crunchy, now would it?

Gannet Ripple

1.99

On a stick!

CSV Table

.. csv-table::

For more details, see CSV Tables in Docutils.

Hint

In almost all cases, csv-table is the easiest and most maintainable way to insert a table into a document. It should be preferred unless there is a compelling reason to use one of the other styles.

The example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
.. tabularcolumns:: p{0.132\linewidth}p{0.198\linewidth}p{0.330\linewidth}
.. csv-table:: Example CSV table
   :name: tables-csv-example
   :header: "Treat", "Quantity", "Description"
   :widths: 20, 30, 50
   :class: longtable
   :align: center
   :width: 66%

   "Albatross", 2.99, "On a stick!"
   "Crunchy Frog", 1.49, "If we took the bones out, it would not be
   crunchy, now would it?"
   "Gannet Ripple", 1.99, "On a stick!"
Which gives
Example CSV table

Treat

Quantity

Description

Albatross

2.99

On a stick!

Crunchy Frog

1.49

If we took the bones out, it would not be crunchy, now would it?

Gannet Ripple

1.99

On a stick!

Some of the options recognized are:

:widths:

Contains a comma or space-separated list of relative column widths. The default is equal-width columns.

The special value auto may be used by writers to decide whether to delegate the determination of column widths to the backend.

In most cases, the best result is either the default or auto. If you’re unsure, try it both ways and see which looks better to you.

:header:

Contains column titles. It must use the same CSV format as the main CSV data.

:delim:

Contains a one character string used to separate fields. Default value is comma. It must be a single character or Unicode code.

The only reason to use something other than a comma is when copying large blocks of content from another source that uses a different style. If you are creating new table content yourself, use the comma.

The example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
.. csv-table:: Example CSV table with customized delimiter
   :name: tables-csv-delim-example
   :header: "Name", "Password"
   :widths: auto
   :delim: :
   :align: center
   :width: 66%

   "Peter":":literal:`QW8rTn@*emk;=J3f`"
   "Paul":":literal:`b3%C/-9\`][cnG,;{`"
Which gives
Example CSV table with customized delimiter

Name

Password

Peter

QW8rTn@*emk;=J3f

Paul

b3%C/-9`][cnG,;{

:align:

It specifies the horizontal alignment of the table. It can be left, right or center.

The example
1
2
3
4
5
6
7
8
.. csv-table:: Example CSV table with right alignment
   :name: tables-csv-align-example
   :header: "Name", "Password"
   :delim: #
   :align: right

   "Peter"#":literal:`QW8rTn@*emk;=J3f`"
   "Paul"# ":literal:`b3%C/-9\`][cnG,;{`"
Which gives
Example CSV table with right alignment

Name

Password

Peter

QW8rTn@*emk;=J3f

Paul

b3%C/-9`][cnG,;{

:url:

Contains an Internet URL reference to a CSV data file.

:file:

Contains the local file system path to a CSV data file.

The example
1
2
3
4
5
6
7
8
.. csv-table:: Example CSV table from source file
   :name: tables-csv-srcfile-example
   :file: example.csv
   :delim: |
   :encoding: utf-8-sig
   :header-rows: 1
   :stub-columns: 1
   :width: 66%
Which gives
Example CSV table from source file

Name

Password

Peter

QW8rTn@*emk;=J3f

Paul

b3%C/-9`][cnG,;{

Which needs

The example above processed the following CSV file content:

CSV example file (tables/csv/srcfile/example.csv)
1
2
3
Name|Password
Peter|:literal:`QW8rTn@*emk;=J3f`
Paul|:literal:`b3%C/-9\`][cnG,;{`

Note

There is no support for checking that the number of columns in each row is the same. However, this directive supports CSV generators that do not insert “empty” entries at the end of short rows, by automatically adding empty entries.

Code Example

The syntax for displaying code is the :: mark, see Literal blocks. When it is used at the end of a sentence, Sphinx is smart and displays one : sign in the output, and knows there is a code example in the following indented block, the Indented literal (code) block. Quoted literal (code) block are unindented contiguous blocks of text where each line begins with the same non-alphanumeric printable 7-bit ASCII character.

.. highlight::

For more details, see highlight directive.

The example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
.. highlight:: none

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 next paragraph is a quoted sample -- John Doe wrote::

>> Great idea!
>
> Why didn't I think of that?

You just did!  ;-)
Which gives

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 next paragraph is a quoted sample – John Doe wrote:

>> Great idea!
>
> Why didn't I think of that?

You just did! ;-)

The handling of the :: marker is smart:

  • If it occurs as a paragraph of its own, that paragraph is completely left out of 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 single colon.

That way, the first sentence in the above example’s first paragraph would be rendered as “… The next paragraph is a code sample:”.

Sphinx extends the default language setup for each literal (code) block with the .. highlight:: directive. That is very useful if a specific directive is not able to set the language by argument or option, even in this case here.

Explicit Code Blocks

Source code will be formatted by the directive .. code-block::. Sphinx, like Python, uses meaningful whitespace. Blocks of content are structured based on the indention level they are on.

.. code-block::

For more details, see code-block directive.

The example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
.. highlight:: bash
   :linenothreshold: 1

A cool bit of code::

   #!/bin/bash
   # Some cool Bash code
   echo ${BASH_VERSINFO[*]}

.. highlight:: none

.. code-block:: rst
   :caption: Documentation

   A bit of **rst** which should be *highlighted* properly.

.. code-block:: python
   :caption: Script
   :linenos:

   import sys
   sys.exit(1)
Which gives

A cool bit of code:

1
2
3
#!/bin/bash
# Some cool Bash code
echo ${BASH_VERSINFO[*]}
Documentation
A bit of **rst** which should be *highlighted* properly.
Script
1
2
import sys
sys.exit(1)

Valid values for the highlighting :language: (first argument) are:

  • none (no highlighting)

  • python (the default)

  • c and cpp (C/C++)

  • rst or rest (reStructuredText)

  • bash or ksh or sh (Unix Shell scripts)

  • shell-session (Unix Shell sessions)

  • ps1 or posh or powershell (Windows PowerShell code)

  • ps1con (Windows PowerShell sessions)

  • dosbatch or winbatch (MS-DOS/Windows Batch file)

  • doscon (MS-DOS sessions)

  • cfg or ini (Generic configuration file, mostly INI files)

  • sql (Generic SQL commands)

  • registry (Windows Registry files produced by regedit)

  • guess (let Pygments guess the lexer based on contents, only works with certain well-recognizable languages)

  • … and any other lexer alias that Pygments supports.

Explicit Code Includes

If the text resides in a separate file, use the .. literalinclude:: directive:

.. literalinclude::

For more details, see literalinclude directive.

The example
1
2
.. literalinclude:: /docutils.conf
   :language: cfg
Which gives
;
; Docutils Configuration
;
; The configuration file consists of sections, lead by a "[section]"
; header and followed by "name: value" entries, with continuations
; in the style of RFC 822; "name=value" is also accepted. Note that
; leading whitespace is removed from values. ... Lines beginning
; with "#" or ";" are ignored and may be used to provide comments.
;
; see: https://docutils.sourceforge.io/docs/user/config.html
;

; https://docutils.sourceforge.io/docs/user/config.html#parsers
; https://docutils.sourceforge.io/docs/user/config.html#restructuredtext-parser

[restructuredtext parser]
syntax_highlight = short

All included files could be located under /include. The beginning / means, root directory of the documentation source directory. Without it, the path is relative to the directory of the including file.

Mathematics

In Sphinx you can include inline math \(x\leftarrow y\ x\forall y\ x-y\) (as role :math:`x\leftarrow y\ x\forall y\ x-y`) or display math as directive block which is able to cross-referencing equations:

()\[W^{3\beta}_{\delta_1 \rho_1 \sigma_2} = U^{3\beta}_{\delta_1 \rho_1} + \frac{1}{8 \pi 2} \int^{\alpha_2}_{\alpha_2} d \alpha^\prime_2 \left[ \frac{ U^{2\beta}_{\delta_1 \rho_1} - \alpha^\prime_2U^{1\beta}_{\rho_1 \sigma_2} }{U^{0\beta}_{\rho_1 \sigma_2}}\right ]\]
.. math::

To include math in your document, just use the .. math:: directive. For more details, see math directive.

The example
1
2
3
4
.. math::

   W^{3\beta}_{\delta_1 \rho_1 \sigma_2}
   \approx U^{3\beta}_{\delta_1 \rho_1}
Which gives
()\[W^{3\beta}_{\delta_1 \rho_1 \sigma_2} \approx U^{3\beta}_{\delta_1 \rho_1}\]
:math:numref:

The math domain (name math) provides the role :math:numref:`label` which is for cross-referencing equations defined by .. math:: directive via their label. For more details, see math:numref role.

The example
1
2
3
4
5
.. math:: e^{i\pi} + 1 = 0
   :label: euler

Euler's identity, :math:numref:`euler`, was elected one
of the most beautiful mathematical formulas.
Which gives
()\[e^{i\pi} + 1 = 0\]

Euler’s identity, Equastion 1.3, was elected one of the most beautiful mathematical formulas.

When the equation is only one line of text, it can also be given as a directive argument (as used in Euler’s identity above).

:eq:

The role :eq:`euler` is the same as :math:numref:`euler`. For more details, see eq role.

Recent versions of Sphinx include built-in support for math. There are three flavors:

Additionally, there are special Sphinx extensions provided by matplotlib that has its own math support for writing mathematical expressions and inserting automatically-generated plots:

See also

See Mathematical Plots for more details about the Sphinx matplotlib extensions with examples.

Admonitions

Generic Admonition

The Generic admonition is a simple titled admonition. The title may be anything the author desires. The author-supplied title is also used as a “classes” attribute value after being converted into a valid identifier form. As well as this implicitly behavior the :class: option value can set to any implemented specific type and overrides the computed “classes” attribute value.

.. admonition::
The example
1
2
3
4
5
6
.. admonition:: Neque porro quisquam
   :class: error

   Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus
   mattis commodo eros, quis posuere enim lobortis quis. Nullam ut
   tempus nibh.
Which gives

Neque porro quisquam

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus mattis commodo eros, quis posuere enim lobortis quis. Nullam ut tempus nibh.

Specific Admonitions

Specific Admonitions are specially marked “topics” that can appear anywhere an ordinary body element can. Typically, an admonition is rendered as an offset block in a document, sometimes outlined or shaded, with a title matching the admonition type. The following admonition directives have been implemented.

Attention Admonition
.. attention::
The example
1
2
3
4
5
.. attention:: Neque porro quisquam

   Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus
   mattis commodo eros, quis posuere enim lobortis quis. Nullam ut
   tempus nibh.
Which gives

Attention

Neque porro quisquam

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus mattis commodo eros, quis posuere enim lobortis quis. Nullam ut tempus nibh.

Caution Admonition
.. caution::
The example
1
2
3
4
5
.. caution:: Neque porro quisquam

   Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus
   mattis commodo eros, quis posuere enim lobortis quis. Nullam ut
   tempus nibh.
Which gives

Caution

Neque porro quisquam

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus mattis commodo eros, quis posuere enim lobortis quis. Nullam ut tempus nibh.

Danger Admonition
.. danger::
The example
1
2
3
4
5
.. danger:: Neque porro quisquam

   Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus
   mattis commodo eros, quis posuere enim lobortis quis. Nullam ut
   tempus nibh.
Which gives

Danger

Neque porro quisquam

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus mattis commodo eros, quis posuere enim lobortis quis. Nullam ut tempus nibh.

Error Admonition
.. error::
The example
1
2
3
4
5
.. error:: Neque porro quisquam

   Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus
   mattis commodo eros, quis posuere enim lobortis quis. Nullam ut
   tempus nibh.
Which gives

Error

Neque porro quisquam

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus mattis commodo eros, quis posuere enim lobortis quis. Nullam ut tempus nibh.

Hint Admonition
.. hint::
The example
1
2
3
4
5
.. hint:: Neque porro quisquam

   Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus
   mattis commodo eros, quis posuere enim lobortis quis. Nullam ut
   tempus nibh.
Which gives

Hint

Neque porro quisquam

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus mattis commodo eros, quis posuere enim lobortis quis. Nullam ut tempus nibh.

Important Admonition
.. important::
The example
1
2
3
4
5
.. important:: Neque porro quisquam

   Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus
   mattis commodo eros, quis posuere enim lobortis quis. Nullam ut
   tempus nibh.
Which gives

Important

Neque porro quisquam

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus mattis commodo eros, quis posuere enim lobortis quis. Nullam ut tempus nibh.

Note Admonition
.. note::

For more details, see note directive.

The example
1
2
3
4
5
.. note:: Neque porro quisquam

   Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus
   mattis commodo eros, quis posuere enim lobortis quis. Nullam ut
   tempus nibh.
Which gives

Note

Neque porro quisquam

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus mattis commodo eros, quis posuere enim lobortis quis. Nullam ut tempus nibh.

Tip Admonition
.. tip::
The example
1
2
3
4
5
.. tip:: Neque porro quisquam

   Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus
   mattis commodo eros, quis posuere enim lobortis quis. Nullam ut
   tempus nibh.
Which gives

Tip

Neque porro quisquam

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus mattis commodo eros, quis posuere enim lobortis quis. Nullam ut tempus nibh.

Warning Admonition
.. warning::

For more details, see warning directive.

The example
1
2
3
4
5
.. warning:: Neque porro quisquam

   Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus
   mattis commodo eros, quis posuere enim lobortis quis. Nullam ut
   tempus nibh.
Which gives

Warning

Neque porro quisquam

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus mattis commodo eros, quis posuere enim lobortis quis. Nullam ut tempus nibh.

Sphinx Additional Admonitions

Seealso Admonition
.. seealso::

Many sections include a list of references to module documentation or external documents. These lists are created using the seealso directive.

The example
1
2
3
4
5
.. seealso:: Neque porro quisquam

   Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus
   mattis commodo eros, quis posuere enim lobortis quis. Nullam ut
   tempus nibh.
Which gives

See also

Neque porro quisquam

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus mattis commodo eros, quis posuere enim lobortis quis. Nullam ut tempus nibh.

Referencing

Another important Sphinx feature is that it allows referencing across documents. This is another powerful way to tie documents together.

The simplest way to do this is to define an explicit reference object which can then be referenced directly as internal hyperlink target or with :ref:`refname` or in rare cases with :numref:`refname` depending on the toctree section numbering setup. Sphinx also supports :doc:`docname` for linking to a document via built-in extension sphinx.ext.intersphinx and also supports auto-generated labels for each section via built-in extension sphinx.ext.autosectionlabel.

The Hyperlink Targets in Docutils provides the basic specification for internal and external hyperlink targets. These are also called explicit and also available as implicit hyperlink targets.

:doc:
:ref:
:numref:

For more details, see doc, ref and numref role.

The example
1
2
3
4
5
6
Clicking on this internal hyperlink will take us to the target_ below.

:ref:`reference-name`, this is
:ref:`the same (cool) section <reference-name>`, and again the reference
with support of the extension **autosectionlabel** --
:ref:`concepts/referencing:A cool section` or :doc:`./referencing`.
1
2
3
4
5
6
7
8
.. _reference-name:

A cool section
""""""""""""""

.. _target:

The hyperlink target above points to this paragraph.
Which gives

Clicking on this internal hyperlink will take us to the target below.

A cool section, this is the same (cool) section, and again the reference with support of the extension autosectionlabelA cool section or Referencing.

A cool section

The hyperlink target above points to this paragraph.

External References

Sphinx also includes a number of predefined references for external concepts. Things like PEP’s and RFC’s. You can read more about this in the Sphinx Roles section.

:pep:
:rfc:

For more details, see pep and rfc role.

The example
1
You can learn more about this at :pep:`8` or :rfc:`1984`.
Which gives

You can learn more about this at PEP 8 or RFC 1984.

Downloadable Files

To place a downloadable file in a document, use the download role.

To understand the procedure better, see this
:download:`example script </_downloads/contributing/example_script.py>`.

Downloadable files with a dedicated context to a specific part of the documentation should also be placed exactly at this point in the source tree of the documentation. Other common artefacts should be put in the documentation root or the /_downloads/ subdirectory, and they should be in a subdirectory with the same name as the document in which they appear (that is, the filename without the .rst extension).

Attention

Downloads are not fully supported by all Sphinx builders. Especially offline documents like LaTeX/PDF will be created correctly, but will not provide additional artifacts.

:download:

For more details, see download role.

The example
1
2
3
4
5
6
7
8
All artifacts were selected and download by using this references:

* matplotlib example: |ellipses.py| (published as `ellipses.py`_)

.. |ellipses.py| replace::
   :download:`ellipses.py </_images/mplplots/ellipses.py>`
.. _`ellipses.py`:
   https://matplotlib.org/gallery/shapes_and_collections/ellipse_demo.html#ellipse-rotated
Which gives

All artifacts were selected and download by using this references:

Semantic Descriptions and References

Sphinx also has much more powerful semantic referencing capabilities, which knows all about software development concepts.

Say you’re creating a CLI application. You can define the name of the executable application program and its option and envvar quite easily.

.. program::
.. option::
.. envvar::

For more details, see program, option and envvar directive.

The example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
.. _dlapp:

.. rubric:: Dreamland

A fantasy command-line interface application.

.. program:: dlapp

.. option:: -f, --force

   Force the operation.

.. option:: -i <regex>, --ignore <regex>

   Ignore things that match a specific pattern.

.. envvar:: DLAPPRC

   Set location of resources.
Which gives

Dreamland

A fantasy command-line interface application.

-f, --force

Force the operation.

-i <regex>, --ignore <regex>

Ignore things that match a specific pattern.

DLAPPRC

Set location of resources.

That can now also be referenced quite simply.

:program:
:option:
:envvar:

For more details, see program, option and envvar role.

The example
1
2
3
4
5
.. seealso:: Working with :ref:`dlapp` (:program:`dlapp`):

   * forcing with :option:`dlapp --force`
   * ignoring with :option:`dlapp -i`
   * defaults with :envvar:`DLAPPRC`
Which gives

See also

Working with Dreamland (dlapp):

Sphinx includes a large number of these semantic types, including:

Writing about User Interface

Several roles are used when describing user interactions.

:guilabel:

Marks up actual UI text of form labels or buttons. For more details, see guilabel role.

The example
1
Press the :guilabel:`Submit` button.
Which gives

Press the Submit button.

:menuselection:

Marks up the actual UI text of a navigation menu or form select element. For more details, see menuselection role.

The example
1
2
3
Select :menuselection:`Help` from menu.

To save your file, go to :menuselection:`File --> Save` in the Main Menu.
Which gives

Select Help from menu.

To save your file, go to File ‣ Save in the Main Menu.

When writing about multi-level menus, use a single :menuselection: role, and separate menu choices with -->.

Note

In some situations you might not be clear about which option, menuselection or guilabel, to use. GUIs in real life can sometimes be ambiguous. The general rule is:

  • Actual UI text will always receive guilabel role unless the text could reasonably be understood to be part of a menu.

  • If the actual UI text could be understood as a menu, menuselection should be used.

These both render the same on output, so don’t worry too much if you get it wrong. Just use your judgment and take your best guess.

:kbd:

Marks up a sequence of literal keyboard strokes. For more details, see kbd role.

The example
1
To stop the local server, type :kbd:`CTRL+C`.
Which gives

To stop the local server, type CTRL+C.

:command:

Marks up a terminal command. For more details, see command role.

The example
1
To build the documentation, use :command:`sphinx-build`.
Which gives

To build the documentation, use sphinx-build.

To document a CLI application, you will find more information in Semantic Descriptions and References.

Other Semantic Markup

:abbr:

Marks up 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. For more details, see abbr role.

The example
1
2
This is the :abbr:`ISDN (Integrated Services Digital Network)`
device.
Which gives

This is the ISDN device.

:dfn:

Marks the defining instance of a term outside the index or glossary. For more details, see dfn role.

The example
1
2
This library has a :dfn:`CAPI`, a Common ISDN Application
Programming Interface.
Which gives

This library has a CAPI, a Common ISDN Application Programming Interface.

Glossary

Sphinx has a built-in Glossary structure that you can use to:

  • Produce a consolidated glossary of terms.

  • Link terms in other content to their glossary definitions.

Create a Glossary

.. glossary::

For more details, see glossary directive.

To add glossary terms, you use the directive .. glossary::. Write each glossary entry as a definition list, with a term, followed by a single-line indented definition.

Each glossary entry is nested below the .. glossary:: directive. For example:

.. glossary::

    Sphinx
       Sphinx is a tool that makes it easy to create intelligent and
       beautiful documentation. It was originally created for the
       Python documentation, and it has excellent facilities for the
       documentation of software projects in a range of languages.

    RST
       reStructuredText is an easy-to-read, what-you-see-is-what-you-get
       plain text markup syntax and parser system. It is useful for
       in-line program documentation (such as Python docstrings), for
       quickly creating simple web pages, and for standalone documents.
       reStructuredText is designed for extensibility for specific
       application domains. The reStructuredText parser is a component
       of Docutils.

    Sublime Text
       Sublime Text is a sophisticated text editor for code, markup
       and prose. You'll love the slick user interface, extraordinary
       features and amazing performance.

Link a Term to its Glossary Entry

:term:

For more details, see index role.

When a glossary term is used in text, you can link it to its definition with the :term: role. For example, to link the term Sphinx to its definition, use the following syntax:

:term:`Sphinx`

The term specified must exactly match a term in Glossary directive.

You can link to a term in the glossary while showing different text in the topic by including the term in angle brackets. For example:

:term:`reStructuredText<RST>`

The term in angle brackets must exactly match a term in the glossary. The text before the angle brackets is what users see on the page.

Index

.. index::

For more details, see index directive.

Some roles and directives do already create indices automatically.

However, there is also an explicit directive available, to make the index more comprehensive and enable index entries in documents where information is not mainly contained in information units.

The directive is .. index:: and 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
   triple: module; search; path
:index:

For more details, see index role.

While the index directive is a block-level markup and links to the beginning of the next paragraph, there is also a corresponding role that sets the link target directly where it is used.

The content of the role can be a simple phrase, which is then kept in the text and used as an index entry. It can also be a combination of text and index entry, styled like with explicit targets of cross-references. In that case, the “target” part can be a full entry as described for the directive above. For example:

This is a normal reST :index:`paragraph` that contains several
:index:`index entries <pair: index; entry>`.

Note

The :index: role must contain text. This text will be printed and referenced by the index.

Extensions

Section author: Stephan Linz <linz@li-pro.net>

Spelling Checker

PyPI Package

https://pypi.org/project/sphinxcontrib-spelling/

Documentation

https://sphinxcontrib-spelling.readthedocs.io/

Git Repository

https://github.com/sphinx-contrib/spelling

Spelling checker for Sphinx. It uses PyEnchant to produce a report showing misspelled words.

Features
  1. Supports multiple source languages using the standard enchant dictionaries.

  2. Supports project-specific dictionaries for localized jargon and other terminology that may not appear in the global dictionaries.

  3. Suggests alternatives to words not found in the dictionary, when possible.

It consists:

Private Dictionaries

For more details, see Configuration Options section Private Dictionaries.

.. spelling::

The .. spelling:: directive can be used to create a list of words known to be spelled correctly within a single file. For example, if a document refers to a person or project by name, the name can be added to the list of known words for just that single document.

When a more common list of words is needed, related to check multiple document at once, the spelling_word_list_filename variable should be set properly.

spelling_word_list_filename

That is a list specifying files containing a list of words known to be spelled correctly but that do not appear in the refered language dictionary. The files should contain one word per line. Refer to the PyEnchant tutorial for details.

BibTeX Citations

PyPI Package

https://pypi.org/project/sphinxcontrib-bibtex/

Documentation

https://sphinxcontrib-bibtex.readthedocs.org/

Git Repository

https://github.com/mcmtroffaes/sphinxcontrib-bibtex

Allowing BibTeX citations to be inserted into documentation via a .. bibliography:: directive, and a :cite: role, which work similarly to LaTeX’s \begin{thebibliography} ... \end{thebibliography} environment and \cite{cite_key} command. It consists:

Create a citation to a bibliographic entry.

Todo

activate “BibTeX Citations” extension.

.. rst:role:: cite

   For more details, see :rst:role:`scbibtex:cite` role.

   :the example:

      .. code-block:: rst
         :linenos:

         See :cite:`juh2014swdocwspx` for an introduction to Sphinx.

   :which gives:

      See :cite:`juh2014swdocwspx` for an introduction to Sphinx.

For this sample you will need a corresponding bibliography for all cited
references.

.. rst:directive:: bibliography

   For more details, see :rst:dir:`scbibtex:bibliography` directive.

   :the example:

      .. code-block:: rst
         :linenos:

         .. bibliography:: bibliography.bibtex
            :style: kcsalpha
            :encoding: utf
            :all:

   :which gives:

      .. only:: html or man or texinfo or text

         .. rubric:: Documentation with Sphinx

      .. only:: latex

         All entries in the central document bibliography list, mostly on the
         end of the document.

      .. bibliography:: bibliography.bibtex
         :style: kcsalpha
         :encoding: utf
         :all:

   :which needs:

      The example above processed the following |BibTeX| file content:

      .. literalinclude:: bibliography.bibtex
         :caption: BibTeX example file (bibliography.bibtex)
         :language: bibtex
         :emphasize-lines: 1
         :start-at: @book
         :linenos:

.. spelling::

   Hasecke

LinuxDoc

Documentation

https://return42.github.io/linuxdoc/

Git Repository

https://github.com/return42/linuxdoc

The LinuxDoc library with extensions of the Linux-Kernel documentation, you can use these extensions in common Sphinx projects. It consists:

Todo

activate “LinuxDoc” extension.

Flat list table

.. flat-table::

The .. flat-table::` (FlatTable) is a double-stage list similar to the .. list-table::` with some additional features:

  • column-span: with the role :cspan:`num` a cell can be extended through additional columns

  • row-span: with the role :rspan:`num` a cell can be extended through additional rows

  • auto-span: rightmost cell of a table row over the missing cells on the right side of that table-row. With Option :fill-cells: this behavior can changed from auto span to auto fill, which automatically inserts (empty) cells instead of spanning the last cell.

Options
:header-rows: (integer)

count of header rows

:stub-columns: (integer)

count of stub columns

:widths: (list of integer)

widths of columns

:fill-cells:

instead of auto-span missing cells, insert missing cells

Roles
:cspan:

(integer): additional columns (morecols)

:rspan:

(integer): additional rows (morerows)

The example below shows how to use this markup. The first level of the staged list is the table-row. In the table-row there is only one markup allowed, the list of the cells in this table-row. Exception are comments ( .. ) and targets (e.g. a ref to row 2 of table’s body).

the example

Attention

line 2: The option :class: longtable will not interpreted from directive .. flat-table:: and has no effects.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
.. flat-table:: LinuxDoc :rst:`.. flat-table::` example (table title)
   :class: longtable
   :widths: 15 15 15 15 40
   :header-rows: 2
   :stub-columns: 1

   * - :rspan:`1` head / stub
     - :cspan:`3` head 1.1-4

   * - head 2.1
     - head 2.2
     - head 2.3
     - head 2.4

   * .. row body 1 / this is a comment

     - row 1
     - :rspan:`2` cell 1-3.1
     - cell 1.2
     - cell 1.3
     - cell 1.4

   * .. Comments and targets are allowed on *table-row* stage.
     .. _`row body 2`:

     - row 2
     - cell 2.2
     - :rspan:`1` :cspan:`1`
       cell 2.3 with a span over

       * col 3-4 &
       * row 2-3

   * - row 3
     - cell 3.2

   * - row 4
     - cell 4.1
     - cell 4.2
     - cell 4.3
     - cell 4.4

   * - row 5
     - cell 5.1 with automatic span to right end

   * - row 6
     - cell 6.1
     - .. empty cell 6.2 with automatic span to right end
:which gives:

   .. include:: linuxdoc/flat-table/example.rsti

Program Output

PyPI Package

https://pypi.org/project/sphinxcontrib-programoutput/

Documentation

https://sphinxcontrib-programoutput.readthedocs.org/

Git Repository

https://github.com/NextThought/sphinxcontrib-programoutput

Literally insert the output of arbitrary commands into documents, helping you to keep your command examples up to date. It consists:

Todo

activate “Program Output” extension.

Complete output

To include the output of a command into your document, use the .. program-output:: directive provided by this extension.

.. program-output::

For more details, see program-output directive.

The example
1
.. program-output:: python --version
:which gives:

   .. program-output:: python --version

The whole output of python --version, including any messages on standard error, is inserted into the current document, formatted as literal text without any syntax highlighting. You can omit the content of the standard error stream with the :nostderr: option.

By default, commands are executed in the top-level source directory. You can choose an alternate working directory with the :cwd: option. The argument of this option is either a path relative to the current source file, or a absolute path which means that it is relative to the top level source directory.

Shortening the output

Lengthy output can be shortened with the :ellipsis: option. Its value denotes lines to omit when inserting the output of the command. Instead, a single ellipsis ... is inserted.

the example

If used with a single number, all lines after the specified line are omitted:

1
2
.. program-output:: python --help
   :ellipsis: 2
:which gives:

   The above omits all lines after the second one:

   .. program-output:: python --help
      :ellipsis: 2

Negative numbers count from the last line backwards, thus replacing 2 with -2 in the above example would only omit the last two lines.

the example

If used with two comma-separated line numbers, all lines in between the specified lines are omitted. Again, a negative number counts from the last line backwards:

1
2
.. program-output:: python --help
   :ellipsis: 2,-2
:which gives:

   The above omits all lines except the first two and the last two lines:

   .. program-output:: python --help
      :ellipsis: 2,-2

Mimicking shell input

You can mimic shell input with the .. command-output:: directive 1. This directive inserts the command along with its output into the document.

.. command-output::

For more details, see command-output directive.

The example
1
.. command-output:: python --version
:which gives:

   .. command-output:: python --version

The appearance of this output can be configured with programoutput_prompt_template. When used in conjunction with :ellipsis:, the command itself and any additional text is never omitted. :ellipsis: always refers to the immediate output of the command.

the example
1
2
.. command-output:: python --help
   :ellipsis: 2
:which gives:

   .. command-output:: python --help
      :ellipsis: 2

Command execution and shell expansion

Normally the command is splittet according to the POSIX shell syntax (see shlex), and executed directly. Thus special shell features like expansion of environment variables will not work.

the example
1
.. command-output:: echo "$USER"
:which gives:

   .. command-output:: echo "$USER"

To enable these features, enable the :shell: option. With this option, the command is literally passed to the system shell.

the example
1
2
.. command-output:: echo "$USER"
   :shell:
:which gives:

   .. command-output:: echo "$USER"
      :shell:

Other shell features like process expansion consequently work, too.

the example
1
2
.. command-output:: ls -l $(which grep)
   :shell:
:which gives:

   .. command-output:: ls -l $(which grep)
      :shell:

Warning

Remember to use :shell: carefully to avoid unintended interpretation of shell syntax and swallowing of fatal errors!

Error handling

If an unexpected exit code (also known as return code) is returned by a command, it is considered to have failed. In this case, a build warning is emitted to help you to detect misspelled commands or similar errors. By default, a command is expected to exit with an exit code of 0, all other codes indicate an error. In some cases however, it may be reasonable to demonstrate failed programs. To avoid a (superfluous) warning in such a case, you can specify the expected return code of a command with the :returncode: option.

the example
1
2
.. command-output:: python -c 'import sys, platform; print(sys.version); sys.exit(1)'
   :returncode: 1
:which gives:

   .. command-output:: python -c 'import sys, platform; print(sys.version); sys.exit(1)'
      :returncode: 1

The above command returns the exit code 1 (as given to sys.exit()), but no warning will be emitted. On the contrary, a warning will be emitted, should the command return 0!

Note

Upon fatal errors which even prevent the execution of the command neither return code nor command output are available. In this case an error message is inserted into the document instead.

If :shell: is set however, most of these fatal errors are handled by the system shell and turned into return codes instead. In this case the error message will only appear in the output of the shell. If you’re using :shell:, double-check the output for errors. Best avoid :shell:, if possible.

Footnotes

1

This directive is just an alias for the .. program-output:: directive with the :prompt: option set.

Mathematical Plots

Attention

Matplotlib does not support labels and auto-references. You can not refer to a equation and you will never see an entry to .. mathmpl:: expressions in the list of equations.

PyPI Package

https://pypi.org/project/matplotlib/

Project Home

https://matplotlib.org/

Documentation

https://matplotlib.org/contents.html

Git Repository

https://github.com/matplotlib/matplotlib

Documentation

https://matplotlib.org/sampledoc/index.html

Git Repository

https://github.com/matplotlib/sampledoc

Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. It consists:

Todo

activate “Mathematical Plots” extension.

Expressions

See the Writing mathematical expressions for lots more information how to writing mathematical expressions in matplotlib.

With matplotlib in |Sphinx| you can include inline math
:mathmpl:`(\alpha^{ic} > \beta_{ic})` (as role
:rst:`:mathmpl:`(\alpha^{ic} > \beta_{ic})``) or display math:

.. mathmpl::

   \sum_{i=0}^\infty x_i
.. mathmpl::
The example
1
2
3
.. mathmpl::

   \left(\frac{5 - \frac{1}{x}}{4}\right)
:which gives:

   .. include:: matplotlib/mathmpl/example.rsti

Plots

.. plot::

See the matplotlib Pyplot tutorial and the Gallery for lots of examples of matplotlib plots.

The source code for the plot may be included in one of three ways:

inline content

the example
1
2
3
4
5
6
7
8
9
.. plot::
   :align: center
   :scale: 75

   import matplotlib.pyplot as plt
   import matplotlib.image as mpimg
   import numpy as np
   img = mpimg.imread('https://github.com/matplotlib/matplotlib/raw/master/doc/_static/stinkbug.png')
   imgplot = plt.imshow(img)
:which gives:

   .. include:: matplotlib/inline/example.rsti

doctest content

the example
1
2
3
4
5
6
7
8
.. plot::
   :format: doctest
   :align: center
   :scale: 75

   >>> import matplotlib.pyplot as plt
   >>> plt.plot([1, 2, 3], [4, 5, 6])  # doctest: +ELLIPSIS
   [<matplotlib.lines.Line2D object at 0x...>]
:which gives:

   .. include:: matplotlib/doctest/example.rsti

source file content

When a path to a source file is given, the Sphinx configuration option plot_basedir will respect. It is the base directory, to which .. plot:: file names are relative to. If None or empty, file names are relative to the directory where the file containing the directive is.

.. ifconfig:: not plot_basedir

   :plot_basedir: **None or empty**, file names are **relative**

.. ifconfig:: plot_basedir

   :plot_basedir: currently set to :file:`{plot_basedir}`.
the example
1
2
3
4
5
6
.. plot:: ellipses.py
   :include-source:
   :encoding: utf
   :format: python
   :align: center
   :scale: 75
:which gives:

   .. include:: matplotlib/srcfile/example.rsti

3D-Plots

See mplot3d, mplot3d FAQ, and mplot3d API.

the example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
.. plot::
   :format: python
   :align: center
   :scale: 75

   import matplotlib.pyplot as plt
   from matplotlib import cm
   from mpl_toolkits.mplot3d import axes3d

   fig = plt.figure()
   ax = fig.gca(projection='3d')
   X, Y, Z = axes3d.get_test_data(0.005)
   ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3)
   cset = ax.contourf(X, Y, Z, zdir='z', offset=-100, cmap=cm.coolwarm)
   cset = ax.contourf(X, Y, Z, zdir='x', offset=-40, cmap=cm.coolwarm)
   cset = ax.contourf(X, Y, Z, zdir='y', offset=40, cmap=cm.coolwarm)

   ax.set_xlabel('X'); ax.set_xlim(-40, 40)
   ax.set_ylabel('Y'); ax.set_ylim(-40, 40)
   ax.set_zlabel('Z'); ax.set_zlim(-100, 100)

   plt.show()
:which gives:

   .. include:: matplotlib/mplot3d/example.rsti

PGF/TikZ LaTeX Pictures

Attention

Only practicable and usable for HTML and LaTeX builder.

PyPI Package

https://pypi.org/project/sphinxcontrib-tikz/

Documentation

http://sphinxcontrib-tikz.readthedocs.io/

Git Repository

https://bitbucket.org/philexander/tikz

Sphinx extension, which enables the use of the PGF/TikZ LaTeX package to draw nice pictures.

This extension relies on two software packages being installed on your computer:

  1. latex with the tikz and the amsmath packages

  2. A software package that is able to convert a PDF to an image. Currently, four different ways of doing this conversion are supported, called conversion “suites”. Below is a list for each suite what must be installed on your computer. Only one such suite need to be installed:

    • pdf2svg suite: pdf2svg (preferred, default)

    • Netpbm suite: pdftoppm (part of the Poppler PDF library) and pnmtopng (part of the Netpbm package)

    • ImageMagick suite: pdftoppm (part of the Poppler PDF library) and convert (part of the ImageMagick package)

    • GhostScript suite: ghostscript

See Configuration in the extension documentation for more details.

Todo

activate “PGF/TikZ LaTeX Pictures” extension.

:tikz:

For more details, see Usage in the extension documentation.

inline content

The example
1
2
An example role :tikz:`[thick] \node[blue,draw] (a) {A};
\node[draw,dotted,right of=a] {B} edge[<-] (a);`
:which gives:

   .. include:: tikz/inline/example.rsti
.. tikz::

For more details, see Usage in the extension documentation.

explicit markup

The example
1
2
3
4
.. rst-class:: centered
.. tikz:: [>=latex',dotted,thick] \draw[->] (0,0) -- (1,1) -- (1,0)
   -- (2,0);
   :libs: arrows
:which gives:

   .. include:: tikz/explicit/example.rsti

from source file

The example
1
2
3
4
.. rst-class:: centered
.. tikz:: Control system principles (PGF/TikZ example)
   :include: ctrloop.tikz
   :libs: arrows,shapes
:which gives:

   .. include:: tikz/srcfile/example.rsti
Which needs

The example above comes from the Control system principles web page and processed the following TikZ file content:

TikZ example file (ctrloop.tikz)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
[auto, node distance=2cm,>=latex']
\tikzstyle{block} = [draw, fill=blue!20, rectangle,
                     minimum height=3em, minimum width=6em]
\tikzstyle{sum} = [draw, fill=blue!20, circle, node distance=1cm]
\tikzstyle{input} = [coordinate]
\tikzstyle{output} = [coordinate]
\tikzstyle{pinstyle} = [pin edge={to-,thin,black}]
% placing the blocks
\node [input, name=input] {};
\node [sum, right of=input] (sum) {};
\node [block, right of=sum] (controller) {Controller};
\node [block, right of=controller, pin={[pinstyle]above:Disturbances},
       node distance=3cm] (system) {System};
% draw an edge between the controller and system block to calculate
% the coordinate -- need it to place the measurement block
\draw [->] (controller) -- node[name=u] {$u$} (system);
\node [output, right of=system] (output) {};
\node [block, below of=u] (measurements) {Measurements};
% once the nodes are placed, connecting them is easy
\draw [draw,->] (input) -- node {$r$} (sum);
\draw [->] (sum) -- node {$e$} (controller);
\draw [->] (system) -- node [name=y] {$y$}(output);
\draw [->] (y) |- (measurements);
\draw [->] (measurements) -| node[pos=0.99] {$-$}
                             node [near end] {$y_m$} (sum);

Block Diagram Family

Todo

activate “Block Diagram Family” extensions.

blockdiag and its family generate diagram images from simple text files:

.. blockdiag::

   blockdiag {
       blockdiag -> generates -> "block-diagrams";
       blockdiag -> is -> "very easy!";

       blockdiag [color = "greenyellow"];
       "block-diagrams" [color = "pink"];
       "very easy!" [color = "orange"];
   }
Features
  1. Supports many types of diagrams

  2. Generates beautiful diagram images from simple text format (similar to Graphviz’s dot format)

  3. Layouts diagram elements automatically

  4. Embeds to many documentations; Sphinx, Trac, Redmine, and some Wikis

Block Diagram

sphinxcontrib-blockdiag is a Sphinx extension for embedding block diagrams. You can embed block diagrams with the .. blockdiag:: directive.

PyPI Package

https://pypi.org/project/sphinxcontrib-blockdiag/

Documentation

http://blockdiag.com/en/blockdiag/sphinxcontrib.html

Git Repository

https://github.com/blockdiag/sphinxcontrib-blockdiag

Sphinx extension for embedding block diagrams using blockdiag.

Features
  1. Generate block-diagram from dot like text (basic feature).

  2. Multilingualism for node-label (utf-8 only).

Todo

activate “Block Diagram” extension.

Directive Body Diagram
.. blockdiag::

For more details, see sphinxcontrib-blockdiag in the extension demonstration and the README.rst in the extension Git repository.

The example
1
2
3
4
5
6
7
.. blockdiag::
   :align: center

   blockdiag {
       A -> B -> C;
            B -> D;
   }
:which gives:

   .. include:: blockdiag/directive-body/example.rsti
Description Table
the example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
.. blockdiag::
   :align: center
   :desctable:

   blockdiag {
       A -> B -> C;
       A [description = "browsers in each client"];
       B [description = "web server"];
       C [description = "database server"];
   }
:which gives:

   .. include:: blockdiag/description-table/example.rsti
Include Diagram
the example
1
2
3
4
.. blockdiag:: blockdiag/example.diag
   :caption: Style attributes to nodes and edges (Block Diagram example)
   :align: center
   :width: 640
:which gives:

   .. blockdiag:: blockdiag/example.diag
      :caption: Style attributes to nodes and edges (Block Diagram example)
      :align: center
      :width: 640
which needs

The example above comes from the original Sample diagrams web page and processed the following file content:

Block Diagram example file (blockdiag/example.diag)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
blockdiag {
    // Set boder-style, backgroun-color and text-color to nodes.
    A [style = dotted];
    B [style = dashed];
    C [color = pink, style = "3,3,3,3,15,3"]; //dashed_array format style
    D [shape = circle, color = "#888888", textcolor="#FFFFFF"];

    // Set border-style and color to edges.
    A -> B [style = dotted];
    B -> C [style = dashed];
    C -> D [color = "red", style = "3,3,3,3,15,3"]; //dashed_array format style

    // Set numbered-badge to nodes.
    E [numbered = 99];

    // Set background image to nodes (and erase label).
    F [label = "", background = "https://github.com/sphinx-doc/sphinx/raw/master/doc/_static/sphinx.png"];
    G [label = "", background = "https://www.python.org/static/community_logos/python-logo-master-v3-TM.png"];
    H [icon = "https://github.com/blockdiag/blockdiag.com/raw/master/sources/en/_static/help-browser.png"];
    I [icon = "https://github.com/blockdiag/blockdiag.com/raw/master/sources/en/_static/internet-mail.png"];
    J [shape = actor]

    // Set arrow direction to edges.
    E -> F [dir = none, label = edge];
    F -> G [dir = forward];
    G -> H [dir = back];

    group {
        orientation = portrait;
        color = lightgray;
        H -> I [dir = both];
    }

    // Set width and height to nodes.
    K [width = 192]; // default value is 128
    L [shape = square, height = 64]; // default value is 40

    // Use thick line
    J -> K [thick]
    K -> L;
}

Sequence Diagram

sphinxcontrib-seqdiag is a Sphinx extension for embedding sequence diagrams. You can embed sequence diagrams with the .. seqdiag:: directive.

PyPI Package

https://pypi.org/project/sphinxcontrib-seqdiag/

Documentation

http://blockdiag.com/en/seqdiag/sphinxcontrib.html

Git Repository

https://github.com/blockdiag/sphinxcontrib-seqdiag

Sphinx extension for embedding sequence diagrams using seqdiag.

Features
  1. Generate sequence-diagram from dot like text (basic feature).

  2. Multilingualism for node-label (utf-8 only).

Todo

activate “Sequence Diagram” extension.

Directive Body Diagram
.. seqdiag::

For more details, see sphinxcontrib-seqdiag in the extension demonstration and the README.rst in the extension Git repository.

The example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
.. seqdiag::
   :align: center

   seqdiag {
       # define order of elements
       # seqdiag sorts elements by order they appear
       browser; database; webserver;

       browser  -> webserver [label = "GET /index.html"];
       browser <-- webserver;
       browser  -> webserver [label = "POST /blog/comment"];
                   webserver  -> database [label = "INSERT comment"];
                   webserver <-- database;
       browser <-- webserver;
   }
:which gives:

   .. include:: seqdiag/directive-body/example.rsti
Description Table
the example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
.. seqdiag::
   :align: center
   :desctable:

   seqdiag {
       A -> B -> C;
       A [description = "browsers in each client"];
       B [description = "web server"];
       C [description = "database server"];
   }
:which gives:

   .. include:: seqdiag/description-table/example.rsti
Include Diagram
the example
1
2
3
4
.. seqdiag:: seqdiag/example.diag
   :caption: Style attributes to diagram and edges (Sequence Diagram example)
   :align: center
   :height: 640
:which gives:

   .. seqdiag:: seqdiag/example.diag
      :caption: Style attributes to diagram and edges (Sequence Diagram example)
      :align: center
      :height: 640
which needs

The example above comes from the original Sample diagrams web page and processed the following file content:

Sequence Diagram example file (seqdiag/example.diag)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
seqdiag {
    // Set edge metrix.
    edge_length = 300;  // default value is 192
    span_height = 80;  // default value is 40

    // Set fontsize.
    default_fontsize = 16;  // default value is 11

    // Do not show activity line
    activation = none;

    // Numbering edges automaticaly
    autonumber = True;

    // Change note color
    default_note_color = lightgreen;

    browser  -> webserver [label = "GET \n/index.html"];
    browser <-- webserver [note = "Apache works!"];

    // Separator
    === Separator line ===

    // color of edge
    browser -> webserver [label = "misformatted", color = red];

    // failed edge
    browser -> webserver [label = "failed browser", failed];
}

Activity Diagram

sphinxcontrib-actdiag is a Sphinx extension for embedding activity diagrams. You can embed activity diagrams with the .. actdiag::` directive.

PyPI Package

https://pypi.org/project/sphinxcontrib-actdiag/

Documentation

http://blockdiag.com/en/actdiag/sphinxcontrib.html

Git Repository

https://github.com/blockdiag/sphinxcontrib-actdiag

Sphinx extension for embedding activity diagrams using actdiag.

Features
  1. Generate activity-diagram from dot like text (basic feature).

  2. Multilingualism for node-label (utf-8 only).

Todo

activate “Activity Diagram” extension.

Directive Body Diagram
.. actdiag::

For more details, see sphinxcontrib-actdiag in the extension demonstration and the README.rst in the extension Git repository.

The example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
.. actdiag::
   :align: center
   :scale: 75

   actdiag {
        A -> B -> C -> D;

        lane foo {
             A; B;
        }
        lane bar {
             C; D;
        }
   }
:which gives:

   .. include:: actdiag/directive-body/example.rsti
Description Table
the example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
.. actdiag::
   :align: center
   :scale: 75
   :desctable:

   actdiag {
        A -> B -> C;
        A [description = "browsers in each client"];
        B [description = "web server"];
        C [description = "database server"];
   }
:which gives:

   .. include:: actdiag/description-table/example.rsti
Include Diagram
the example
1
2
3
4
5
.. blockdiag:: actdiag/example.diag
   :caption: Style attributes to frames and nodes (Activity Diagram example)
   :align: center
   :scale: 75
   :width: 640
:which gives:

   .. actdiag:: actdiag/example.diag
      :caption: Style attributes to frames and nodes (Activity Diagram example)
      :align: center
      :scale: 75
      :width: 640
which needs

The example above comes from the original Sample diagrams web page and processed the following file content:

Activity Diagram example file (actdiag/example.diag)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
actdiag {
    write -> convert -> image;

    lane user {
         label = "User";
         write [label = "Writing reST"];
         image [label = "Get diagram IMAGE"];
    }
    lane actdiag {
         convert [label = "Convert reST to Image"];
    }
}

Network Diagram

sphinxcontrib-nwdiag is a Sphinx extension for embedding network diagrams. You can embed network diagrams with the .. nwdiag::, .. rackdiag:: and .. packetdiag:: directives.

PyPI Package

https://pypi.org/project/sphinxcontrib-nwdiag/

Documentation

http://blockdiag.com/en/nwdiag/sphinxcontrib.html

Git Repository

https://github.com/blockdiag/sphinxcontrib-nwdiag

Sphinx extension for embedding network diagrams using nwdiag.

Features
  1. Generate network-diagram from dot like text (basic feature).

  2. Multilingualism for node-label (utf-8 only).

Todo

activate “Network Diagram” extension.

Directive Body Diagram
.. nwdiag::

For more details, see sphinxcontrib-nwdiag in the extension demonstration and the README.rst in the extension Git repository.

The example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
.. nwdiag::
   :align: center
   :scale: 75

   nwdiag {
       network dmz {
           web01;
           web02;
       }
   }
:which gives:

   .. include:: nwdiag/directive-body/example.rsti
Description Table
the example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
.. nwdiag::
   :align: center
   :scale: 75
   :desctable:

   nwdiag {
       network dmz {
           web01 [address = "192.168.0.1", description = "web server01"];
           web02 [address = "192.168.0.2", description = "web server02"];
       }
       network internal {
           web01 [address = "172.0.0.1"];
           db01 [address = "172.0.0.2,172.0.0.20", description = "database server"];
       }
   }
:which gives:

   .. include:: nwdiag/description-table/example.rsti
Include Diagram
Network
the example
1
2
3
4
5
.. nwdiag:: nwdiag/example.diag
   :caption: Peer networks and grouping nodes (Network Diagram example)
   :align: center
   :scale: 75
   :width: 640
:which gives:

   .. nwdiag:: nwdiag/example.diag
      :caption: Peer networks and grouping nodes (Network Diagram example)
      :align: center
      :scale: 75
      :width: 640
which needs

The example above comes from the original Sample diagrams: nwdiag web page and processed the following file content:

Network Diagram example file (nwdiag/example.diag)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
nwdiag {
    inet [shape = cloud];
    inet -- router;

    network front {
        address = "192.168.0.0/24";
        router;
        web01;
        web02;

        // define network using defined nodes
        group db {
            web01;
            web02;
        }
    }
}
Rack
.. rack::

For more details, see sphinxcontrib-nwdiag in the extension demonstration and the README.rst in the extension Git repository.

The example
1
2
3
4
.. rackdiag:: rackdiag/example.diag
   :caption: Multiple racks with multiple and blocked units (Rack Diagram example)
   :align: center
   :height: 480
:which gives:

   .. rackdiag:: rackdiag/example.diag
      :caption: Multiple racks with multiple and blocked units (Rack Diagram example)
      :align: center
      :height: 480
Which needs

The example above comes from the original Sample diagrams: rackdiag web page and processed the following file content:

Rack Diagram example file (rackdiag/example.diag)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
rackdiag {
    default_fontsize = 10;

    // define 1st (height) rack
    rack {
        16U;

        // define rack items
        1: UPS [2U, fontsize = 14];
        3: DB Server;
        // put 2 units to rack-level 4
        4: Web\nServer 1;
        4: Web\nServer 2;
        5: Web\nServer 3;
        5: Web\nServer 4;
        7: Load Balancer;
        8: L3 Switch;
    }

    // define 2nd rack
    rack {
        12U;

        // define rack items
        1: UPS [2U, fontsize = 14];
        3: DB Server;
        4: Web Server;
        5: Web Server;
        6: Web Server;
        7: Load Balancer;
        8: L3 Switch;
    }

    // define 3rd rack (with not available units)
    rack {
        12U;

        1: Server;
        2: Server;
        3: Server;
        4: Server;
        5: N/A [8U, fontsize = 14];
    }
}
Packet
.. packet::

For more details, see sphinxcontrib-nwdiag in the extension demonstration and the README.rst in the extension Git repository.

The example
1
2
3
4
.. packetdiag:: packetdiag/example.diag
   :caption: Structure of TCP Header (Packet Diagram example)
   :align: center
   :width: 640
:which gives:

   .. packetdiag:: packetdiag/example.diag
      :caption: Structure of TCP Header (Packet Diagram example)
      :align: center
      :width: 640
Which needs

The example above comes from the original Sample diagrams: packetdiag web page and processed the following file content:

Packet Diagram example file (packetdiag/example.diag)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
packetdiag {
    colwidth = 32;
    node_height = 40;
    default_fontsize = 12;

    0-15: Source Port;
    16-31: Destination Port;
    32-63: Sequence Number;
    64-95: Acknowledgment Number;
    96-99: Data\nOffset;
    100-105: Reserved;
    106: URG [rotate = 270];
    107: ACK [rotate = 270];
    108: PSH [rotate = 270];
    109: RST [rotate = 270];
    110: SYN [rotate = 270];
    111: FIN [rotate = 270];
    112-127: Window;
    128-143: Checksum;
    144-159: Urgent Pointer;
    160-191: (Options and Padding);
    192-223: Data [colheight = 3];
}

Tabbed Content

Attention

Only practicable and usable for HTML builder.

PyPI Package

https://pypi.org/project/sphinx-tabs/

Documentation

https://sphinx-tabs.readthedocs.io/

Git Repository

https://github.com/executablebooks/sphinx-tabs

Create tabbed content in Sphinx documentation when building HTML.

Features
  1. Basic and nested tabs.

  2. Grouped Tabs.

  3. Code Tabs.

Todo

activate “Tabbed Content” extension.

.. tabs::
.. tab::

For more details, see Simple Tabs in the extension demonstration and the README.md in the extension Git repository.

The example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
.. tabs::

   .. tab:: **Apples**

      Apples are green, or sometimes red.

   .. tab:: **Pears**

      Pears are green.

   .. tab:: **Oranges**

      Oranges are orange.
:which gives:

   .. include:: sphinx-tabs/example.rsti

Nested tabs are also possible.

The example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
.. tabs::

   .. tab:: Stars

      .. tabs::

         .. tab:: The Sun

            The closest star to us.

         .. tab:: Proxima Centauri

            The second closest star to us.

         .. tab:: Polaris

            The North Star.

   .. tab:: Moons

      .. tabs::

         .. tab:: The Moon

            Orbits the Earth

         .. tab:: Titan

            Orbits Jupiter
:which gives:

   .. include:: sphinx-tabs/nested/example.rsti
.. group-tab::

Also tabs can stick together in groups.

The example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
.. rubric:: operating systems

.. tabs::

   .. group-tab:: Linux

      **Linux** is Unix-like, but was developed without any Unix code.
      The Linux kernel originated in 1991, as a project of Linus
      Torvalds, while a university student in Finland.

   .. group-tab:: Mac OS X

      **Mac OS X** is a line of open core graphical operating systems
      developed, marketed, and sold by Apple Inc.

   .. group-tab:: Microsoft Windows

      **Microsoft Windows** is a family of proprietary operating systems
      designed by Microsoft Corporation and primarily targeted to
      Intel architecture based computers.

.. rubric:: integrated development environments

.. tabs::

   .. group-tab:: Linux

      **There is no dedicated or default integrated development
      environment (IDE)** on *Linux*. `Here is a list`_ of IDEs
      which will run natively on *Linux*.

   .. group-tab:: Mac OS X

      **Xcode** is an integrated development environment (IDE) for
      *Mac OS X* containing a suite of software development tools
      developed by Apple Inc.

   .. group-tab:: Microsoft Windows

      **Microsoft Visual Studio** is an integrated development
      environment (IDE) from Microsoft Corporation. It is used to
      develop computer programs uses Microsoft software development
      platforms such as *Windows API*, *Windows Forms*, *Windows
      Presentation Foundation*, *Windows Store* and *Microsoft
      Silverlight*.

.. _`Here is a list`:
   https://en.wikipedia.org/wiki/Category:Linux_integrated_development_environments
:which gives:

   .. include:: sphinx-tabs/group/example.rsti

Paneled Content

Attention

Only practicable and usable for HTML builder.

PyPI Package

https://pypi.org/project/sphinx-panels/

Documentation

https://sphinx-panels.readthedocs.io/

Git Repository

https://github.com/executablebooks/sphinx-panels

Create paneled content in Sphinx documentation when building HTML.

Features
  1. Panels in grid or cards layout.

  2. Panels with click-able link-button.

  3. Panels with toggle-able content by drop-downs.

  4. Panels with styling: header, footer, images, icons, badges, animations

For more details, see sphinx-panels in the extension demonstration and the README.md in the extension Git repository.

Todo

activate “Paneled Content” extension.

.. panels::

For more details, see Panels Usage.

.. dropdown::

For more details, see Dropdown Usage.

For more details, see Link Buttons.

.. div::

For more details, see Div Directive.

:badge:

For more details, see Link Badges.

:opticon:
:fa:

For more details, see Inline Icons.

Extension not applicable

This Sphinx extension is quite new and is under constant development. The current behavior disturbs the integration, so the extension is disabled for now (see conf.py). Currently known bugs are:

  • annoying side effects with the Tabbed Content extension by the automatically integrated and delivered Bootstrap 4.0 CSS

  • no proper and practical LaTeX builder support

Email Obfuscate

Attention

Only practicable and usable for HTML builder.

PyPI Package

https://pypi.org/project/sphinxcontrib-email/

Documentation

https://github.com/sphinx-contrib/email/blob/master/README.rst

Git Repository

https://github.com/sphinx-contrib/email

Python 3 Fixes

https://github.com/rexut/sphinxcontrib-email/tree/python3-fixes

Todo

activate “Email Obfuscate” extension.

To obfuscate an email address use something like:

:email:`Name Surname <user@myplace.org>`
:email:`Name Surname (user@myplace.org)`

That renders as Name Surname with the appropriate mailto link.

:email:`user@myplace.org`

That renders as user@myplace.org with the appropriate mailto link.

:email:
The example
1
2
3
* :email:`Name Surname <user@myplace.org>`
* :email:`Name Surname (user@myplace.org)`
* :email:`user@myplace.org`
:which gives:

   .. include:: email/example.rsti

Themes

Section author: Stephan Linz <linz@li-pro.net>

Let’s decorate the project documentation. There are a lot of themes for the Sphinx HTML builder available on the Sphinx Themes Demo Page.

This documentation use the Read the Docs Sphinx Theme as demonstrate at the Sphinx RTD Theme Demo Page.

Another interesting and actively developed theme is The Sphinx Book Theme, the theme by The Executable Book Project.

Read the Docs Sphinx Theme

PyPI Package

https://pypi.org/project/sphinx-rtd-theme/

Documentation

https://sphinx-rtd-theme.readthedocs.io/

Git Repository

https://github.com/readthedocs/sphinx_rtd_theme

This theme is primarily focused to be used on Read the Docs but can work with your own sphinx projects. You can find a working demo of the theme in the theme documentation.

screen_desktop.png

Sphinx RTD theme on Desktop

screen_mobile.png

Sphinx RTD theme on Mobiles

Cheat Sheet

Section author: Stephan Linz <linz@li-pro.net>

We have made a cheat sheet for helping you remember the syntax for reStructuredText & Sphinx programs. The basic reStructuredText Cheat Sheet could also be very helpful.

Cheat Sheet reStructuredText & Sphinx 1/2

Cheat Sheet reStructuredText & Sphinx 1/2

Cheat Sheet reStructuredText & Sphinx 2/2

Cheat Sheet reStructuredText & Sphinx 2/2

Appendix

Section author: Stephan Linz <linz@li-pro.net>

License

License text of the Li-Pro.Net Sphinx Primer
Creative Commons Legal Code

Attribution-ShareAlike 3.0 Unported

    CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
    LEGAL SERVICES. DISTRIBUTION OF THIS LICENSE DOES NOT CREATE AN
    ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
    INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
    REGARDING THE INFORMATION PROVIDED, AND DISCLAIMS LIABILITY FOR
    DAMAGES RESULTING FROM ITS USE.

License

THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE
COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY
COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS
AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.

BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE
TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY
BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS
CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND
CONDITIONS.

1. Definitions

 a. "Adaptation" means a work based upon the Work, or upon the Work and
    other pre-existing works, such as a translation, adaptation,
    derivative work, arrangement of music or other alterations of a
    literary or artistic work, or phonogram or performance and includes
    cinematographic adaptations or any other form in which the Work may be
    recast, transformed, or adapted including in any form recognizably
    derived from the original, except that a work that constitutes a
    Collection will not be considered an Adaptation for the purpose of
    this License. For the avoidance of doubt, where the Work is a musical
    work, performance or phonogram, the synchronization of the Work in
    timed-relation with a moving image ("synching") will be considered an
    Adaptation for the purpose of this License.
 b. "Collection" means a collection of literary or artistic works, such as
    encyclopedias and anthologies, or performances, phonograms or
    broadcasts, or other works or subject matter other than works listed
    in Section 1(f) below, which, by reason of the selection and
    arrangement of their contents, constitute intellectual creations, in
    which the Work is included in its entirety in unmodified form along
    with one or more other contributions, each constituting separate and
    independent works in themselves, which together are assembled into a
    collective whole. A work that constitutes a Collection will not be
    considered an Adaptation (as defined below) for the purposes of this
    License.
 c. "Creative Commons Compatible License" means a license that is listed
    at https://creativecommons.org/compatiblelicenses that has been
    approved by Creative Commons as being essentially equivalent to this
    License, including, at a minimum, because that license: (i) contains
    terms that have the same purpose, meaning and effect as the License
    Elements of this License; and, (ii) explicitly permits the relicensing
    of adaptations of works made available under that license under this
    License or a Creative Commons jurisdiction license with the same
    License Elements as this License.
 d. "Distribute" means to make available to the public the original and
    copies of the Work or Adaptation, as appropriate, through sale or
    other transfer of ownership.
 e. "License Elements" means the following high-level license attributes
    as selected by Licensor and indicated in the title of this License:
    Attribution, ShareAlike.
 f. "Licensor" means the individual, individuals, entity or entities that
    offer(s) the Work under the terms of this License.
 g. "Original Author" means, in the case of a literary or artistic work,
    the individual, individuals, entity or entities who created the Work
    or if no individual or entity can be identified, the publisher; and in
    addition (i) in the case of a performance the actors, singers,
    musicians, dancers, and other persons who act, sing, deliver, declaim,
    play in, interpret or otherwise perform literary or artistic works or
    expressions of folklore; (ii) in the case of a phonogram the producer
    being the person or legal entity who first fixes the sounds of a
    performance or other sounds; and, (iii) in the case of broadcasts, the
    organization that transmits the broadcast.
 h. "Work" means the literary and/or artistic work offered under the terms
    of this License including without limitation any production in the
    literary, scientific and artistic domain, whatever may be the mode or
    form of its expression including digital form, such as a book,
    pamphlet and other writing; a lecture, address, sermon or other work
    of the same nature; a dramatic or dramatico-musical work; a
    choreographic work or entertainment in dumb show; a musical
    composition with or without words; a cinematographic work to which are
    assimilated works expressed by a process analogous to cinematography;
    a work of drawing, painting, architecture, sculpture, engraving or
    lithography; a photographic work to which are assimilated works
    expressed by a process analogous to photography; a work of applied
    art; an illustration, map, plan, sketch or three-dimensional work
    relative to geography, topography, architecture or science; a
    performance; a broadcast; a phonogram; a compilation of data to the
    extent it is protected as a copyrightable work; or a work performed by
    a variety or circus performer to the extent it is not otherwise
    considered a literary or artistic work.
 i. "You" means an individual or entity exercising rights under this
    License who has not previously violated the terms of this License with
    respect to the Work, or who has received express permission from the
    Licensor to exercise rights under this License despite a previous
    violation.
 j. "Publicly Perform" means to perform public recitations of the Work and
    to communicate to the public those public recitations, by any means or
    process, including by wire or wireless means or public digital
    performances; to make available to the public Works in such a way that
    members of the public may access these Works from a place and at a
    place individually chosen by them; to perform the Work to the public
    by any means or process and the communication to the public of the
    performances of the Work, including by public digital performance; to
    broadcast and rebroadcast the Work by any means including signs,
    sounds or images.
 k. "Reproduce" means to make copies of the Work by any means including
    without limitation by sound or visual recordings and the right of
    fixation and reproducing fixations of the Work, including storage of a
    protected performance or phonogram in digital form or other electronic
    medium.

2. Fair Dealing Rights. Nothing in this License is intended to reduce,
limit, or restrict any uses free from copyright or rights arising from
limitations or exceptions that are provided for in connection with the
copyright protection under copyright law or other applicable laws.

3. License Grant. Subject to the terms and conditions of this License,
Licensor hereby grants You a worldwide, royalty-free, non-exclusive,
perpetual (for the duration of the applicable copyright) license to
exercise the rights in the Work as stated below:

 a. to Reproduce the Work, to incorporate the Work into one or more
    Collections, and to Reproduce the Work as incorporated in the
    Collections;
 b. to create and Reproduce Adaptations provided that any such Adaptation,
    including any translation in any medium, takes reasonable steps to
    clearly label, demarcate or otherwise identify that changes were made
    to the original Work. For example, a translation could be marked "The
    original work was translated from English to Spanish," or a
    modification could indicate "The original work has been modified.";
 c. to Distribute and Publicly Perform the Work including as incorporated
    in Collections; and,
 d. to Distribute and Publicly Perform Adaptations.
 e. For the avoidance of doubt:

     i. Non-waivable Compulsory License Schemes. In those jurisdictions in
        which the right to collect royalties through any statutory or
        compulsory licensing scheme cannot be waived, the Licensor
        reserves the exclusive right to collect such royalties for any
        exercise by You of the rights granted under this License;
    ii. Waivable Compulsory License Schemes. In those jurisdictions in
        which the right to collect royalties through any statutory or
        compulsory licensing scheme can be waived, the Licensor waives the
        exclusive right to collect such royalties for any exercise by You
        of the rights granted under this License; and,
   iii. Voluntary License Schemes. The Licensor waives the right to
        collect royalties, whether individually or, in the event that the
        Licensor is a member of a collecting society that administers
        voluntary licensing schemes, via that society, from any exercise
        by You of the rights granted under this License.

The above rights may be exercised in all media and formats whether now
known or hereafter devised. The above rights include the right to make
such modifications as are technically necessary to exercise the rights in
other media and formats. Subject to Section 8(f), all rights not expressly
granted by Licensor are hereby reserved.

4. Restrictions. The license granted in Section 3 above is expressly made
subject to and limited by the following restrictions:

 a. You may Distribute or Publicly Perform the Work only under the terms
    of this License. You must include a copy of, or the Uniform Resource
    Identifier (URI) for, this License with every copy of the Work You
    Distribute or Publicly Perform. You may not offer or impose any terms
    on the Work that restrict the terms of this License or the ability of
    the recipient of the Work to exercise the rights granted to that
    recipient under the terms of the License. You may not sublicense the
    Work. You must keep intact all notices that refer to this License and
    to the disclaimer of warranties with every copy of the Work You
    Distribute or Publicly Perform. When You Distribute or Publicly
    Perform the Work, You may not impose any effective technological
    measures on the Work that restrict the ability of a recipient of the
    Work from You to exercise the rights granted to that recipient under
    the terms of the License. This Section 4(a) applies to the Work as
    incorporated in a Collection, but this does not require the Collection
    apart from the Work itself to be made subject to the terms of this
    License. If You create a Collection, upon notice from any Licensor You
    must, to the extent practicable, remove from the Collection any credit
    as required by Section 4(c), as requested. If You create an
    Adaptation, upon notice from any Licensor You must, to the extent
    practicable, remove from the Adaptation any credit as required by
    Section 4(c), as requested.
 b. You may Distribute or Publicly Perform an Adaptation only under the
    terms of: (i) this License; (ii) a later version of this License with
    the same License Elements as this License; (iii) a Creative Commons
    jurisdiction license (either this or a later license version) that
    contains the same License Elements as this License (e.g.,
    Attribution-ShareAlike 3.0 US)); (iv) a Creative Commons Compatible
    License. If you license the Adaptation under one of the licenses
    mentioned in (iv), you must comply with the terms of that license. If
    you license the Adaptation under the terms of any of the licenses
    mentioned in (i), (ii) or (iii) (the "Applicable License"), you must
    comply with the terms of the Applicable License generally and the
    following provisions: (I) You must include a copy of, or the URI for,
    the Applicable License with every copy of each Adaptation You
    Distribute or Publicly Perform; (II) You may not offer or impose any
    terms on the Adaptation that restrict the terms of the Applicable
    License or the ability of the recipient of the Adaptation to exercise
    the rights granted to that recipient under the terms of the Applicable
    License; (III) You must keep intact all notices that refer to the
    Applicable License and to the disclaimer of warranties with every copy
    of the Work as included in the Adaptation You Distribute or Publicly
    Perform; (IV) when You Distribute or Publicly Perform the Adaptation,
    You may not impose any effective technological measures on the
    Adaptation that restrict the ability of a recipient of the Adaptation
    from You to exercise the rights granted to that recipient under the
    terms of the Applicable License. This Section 4(b) applies to the
    Adaptation as incorporated in a Collection, but this does not require
    the Collection apart from the Adaptation itself to be made subject to
    the terms of the Applicable License.
 c. If You Distribute, or Publicly Perform the Work or any Adaptations or
    Collections, You must, unless a request has been made pursuant to
    Section 4(a), keep intact all copyright notices for the Work and
    provide, reasonable to the medium or means You are utilizing: (i) the
    name of the Original Author (or pseudonym, if applicable) if supplied,
    and/or if the Original Author and/or Licensor designate another party
    or parties (e.g., a sponsor institute, publishing entity, journal) for
    attribution ("Attribution Parties") in Licensor's copyright notice,
    terms of service or by other reasonable means, the name of such party
    or parties; (ii) the title of the Work if supplied; (iii) to the
    extent reasonably practicable, the URI, if any, that Licensor
    specifies to be associated with the Work, unless such URI does not
    refer to the copyright notice or licensing information for the Work;
    and (iv) , consistent with Ssection 3(b), in the case of an
    Adaptation, a credit identifying the use of the Work in the Adaptation
    (e.g., "French translation of the Work by Original Author," or
    "Screenplay based on original Work by Original Author"). The credit
    required by this Section 4(c) may be implemented in any reasonable
    manner; provided, however, that in the case of a Adaptation or
    Collection, at a minimum such credit will appear, if a credit for all
    contributing authors of the Adaptation or Collection appears, then as
    part of these credits and in a manner at least as prominent as the
    credits for the other contributing authors. For the avoidance of
    doubt, You may only use the credit required by this Section for the
    purpose of attribution in the manner set out above and, by exercising
    Your rights under this License, You may not implicitly or explicitly
    assert or imply any connection with, sponsorship or endorsement by the
    Original Author, Licensor and/or Attribution Parties, as appropriate,
    of You or Your use of the Work, without the separate, express prior
    written permission of the Original Author, Licensor and/or Attribution
    Parties.
 d. Except as otherwise agreed in writing by the Licensor or as may be
    otherwise permitted by applicable law, if You Reproduce, Distribute or
    Publicly Perform the Work either by itself or as part of any
    Adaptations or Collections, You must not distort, mutilate, modify or
    take other derogatory action in relation to the Work which would be
    prejudicial to the Original Author's honor or reputation. Licensor
    agrees that in those jurisdictions (e.g. Japan), in which any exercise
    of the right granted in Section 3(b) of this License (the right to
    make Adaptations) would be deemed to be a distortion, mutilation,
    modification or other derogatory action prejudicial to the Original
    Author's honor and reputation, the Licensor will waive or not assert,
    as appropriate, this Section, to the fullest extent permitted by the
    applicable national law, to enable You to reasonably exercise Your
    right under Section 3(b) of this License (right to make Adaptations)
    but not otherwise.

5. Representations, Warranties and Disclaimer

UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR
OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY
KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE,
INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY,
FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF
LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS,
WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION
OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.

6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE
LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR
ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES
ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

7. Termination

 a. This License and the rights granted hereunder will terminate
    automatically upon any breach by You of the terms of this License.
    Individuals or entities who have received Adaptations or Collections
    from You under this License, however, will not have their licenses
    terminated provided such individuals or entities remain in full
    compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will
    survive any termination of this License.
 b. Subject to the above terms and conditions, the license granted here is
    perpetual (for the duration of the applicable copyright in the Work).
    Notwithstanding the above, Licensor reserves the right to release the
    Work under different license terms or to stop distributing the Work at
    any time; provided, however that any such election will not serve to
    withdraw this License (or any other license that has been, or is
    required to be, granted under the terms of this License), and this
    License will continue in full force and effect unless terminated as
    stated above.

8. Miscellaneous

 a. Each time You Distribute or Publicly Perform the Work or a Collection,
    the Licensor offers to the recipient a license to the Work on the same
    terms and conditions as the license granted to You under this License.
 b. Each time You Distribute or Publicly Perform an Adaptation, Licensor
    offers to the recipient a license to the original Work on the same
    terms and conditions as the license granted to You under this License.
 c. If any provision of this License is invalid or unenforceable under
    applicable law, it shall not affect the validity or enforceability of
    the remainder of the terms of this License, and without further action
    by the parties to this agreement, such provision shall be reformed to
    the minimum extent necessary to make such provision valid and
    enforceable.
 d. No term or provision of this License shall be deemed waived and no
    breach consented to unless such waiver or consent shall be in writing
    and signed by the party to be charged with such waiver or consent.
 e. This License constitutes the entire agreement between the parties with
    respect to the Work licensed here. There are no understandings,
    agreements or representations with respect to the Work not specified
    here. Licensor shall not be bound by any additional provisions that
    may appear in any communication from You. This License may not be
    modified without the mutual written agreement of the Licensor and You.
 f. The rights granted under, and the subject matter referenced, in this
    License were drafted utilizing the terminology of the Berne Convention
    for the Protection of Literary and Artistic Works (as amended on
    September 28, 1979), the Rome Convention of 1961, the WIPO Copyright
    Treaty of 1996, the WIPO Performances and Phonograms Treaty of 1996
    and the Universal Copyright Convention (as revised on July 24, 1971).
    These rights and subject matter take effect in the relevant
    jurisdiction in which the License terms are sought to be enforced
    according to the corresponding provisions of the implementation of
    those treaty provisions in the applicable national law. If the
    standard suite of rights granted under applicable copyright law
    includes additional rights not granted under this License, such
    additional rights are deemed to be included in the License; this
    License is not intended to restrict the license of any rights under
    applicable law.


Creative Commons Notice

    Creative Commons is not a party to this License, and makes no warranty
    whatsoever in connection with the Work. Creative Commons will not be
    liable to You or any party on any legal theory for any damages
    whatsoever, including without limitation any general, special,
    incidental or consequential damages arising in connection to this
    license. Notwithstanding the foregoing two (2) sentences, if Creative
    Commons has expressly identified itself as the Licensor hereunder, it
    shall have all rights and obligations of Licensor.

    Except for the limited purpose of indicating to the public that the
    Work is licensed under the CCPL, Creative Commons does not authorize
    the use by either party of the trademark "Creative Commons" or any
    related trademark or logo of Creative Commons without the prior
    written consent of Creative Commons. Any permitted use will be in
    compliance with Creative Commons' then-current trademark usage
    guidelines, as may be published on its website or otherwise made
    available upon request from time to time. For the avoidance of doubt,
    this trademark restriction does not form part of the License.

    Creative Commons may be contacted at https://creativecommons.org/.

Credits

Authors cited when creating the Li-Pro.Net Sphinx Primer
___________________________________________________________________________

AUTHORS (in alphabetical order)
___________________________________________________________________________

Armin Ronacher <armin.ronacher@active-4.com>  Sphinx Code and Documentation
Bareos GmbH & Co. KG <info@bareos.org>        Bareos Documentation
David Goodger <goodger@python.org>            Docutils and reStructuredText
Eric Holscher <eric@ericholscher.com>         Sphinx Tutorial
Georg Brandl <georg@python.org>               Sphinx Code and Documentation
Richard Jones <rjones@ekit-inc.com>           ReStructuredText Primer
Stephan Linz <linz@li-pro.net>                Li-Pro.Net Sphinx Primer
___________________________________________________________________________

Glossary

Section author: Stephan Linz <linz@li-pro.net>

Terms

Commons

Docutils

Docutils is an open-source text processing system for processing plaintext documentation into useful formats, such as HTML, LaTeX, man-pages, open-document or XML. It includes reStructuredText, the easy to read, easy to use, what-you-see-is-what-you-get plaintext markup language.

LaTeX

LaTeX is a document preparation system for high-quality typesetting. It is most often used for medium-to-large technical or scientific documents but it can be used for almost any form of publishing. LaTeX uses the TeX typesetting program for formatting its output, and is itself written in the TeX macro language.

PyEnchant

PyEnchant is a Python binding for Enchant.

Pygments

Pygments is a generic syntax highlighter written in Python which supports a wide range of over 500 languages with related lexers and other text formats and is ready for new languages and formats added easily.

reStructuredText

reStructuredText (RST, ReST, or reST) is a file format for textual data used primarily in the Python programming language community for technical documentation. It is part of the Docutils project of the Python Doc-SIG (Documentation Special Interest Group).

Sphinx

Sphinx is a documentation generator written and used by the Python community. It is written in Python, and also used in other environments. Sphinx converts reStructuredText files into HTML websites and other formats including PDF, EPub, Texinfo and man.

reStructuredText is extensible, and Sphinx exploits its extensible nature through a number of extensions–for autogenerating documentation from source code, writing mathematical notation or highlighting source code, etc.

Programming Languages

C

C is a general-purpose, imperative procedural computer programming language supporting structured programming, lexical variable scope, and recursion, with a static type system. It was designed to be compiled to provide low-level access to memory and language constructs that map efficiently to machine instructions, all with minimal runtime support. C has been standardized by the ANSI X3J11 since 1989 (ANSI C) and by the ISO/IEC JTC1/SC22/WG14 (ISO C).

See also

C++

C++ is a general-purpose programming language as an extension of the C programming language, or “C with Classes”. Modern C++ implementations now has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation. C++ is standardized by the ISO/IEC JTC1/SC22/WG14 since 1998.

See also

ES
ECMAScript

ES is a general-purpose programming language, standardized by Ecma International since 1997 according to the document ECMA-262. It is a JavaScript standard meant to ensure the interoperability of Web pages across different Web browsers. ES is standardized by the ISO/IEC JTC1/SC22 since 1998.

See also

JS
JavaScript

JS is a programming language that conforms to the ECMAScript specification. JavaScript is high-level, often just-in-time compiled, and multi-paradigm. It has curly-bracket syntax, dynamic typing, prototype-based object-orientation, and first-class functions.

Alongside HTML and CSS, JavaScript is one of the core technologies of the World Wide Web. JavaScript enables interactive web pages and is an essential part of web applications. The vast majority of websites use it for client-side page behavior, and all major web browsers have a dedicated JavaScript engine to execute it.

Python

Python is an interpreted, high-level and general-purpose programming language. Python interpreters are available for many operating systems. A global community of programmers develops and maintains CPython, a free and open-source reference implementation. A non-profit organization, the Python Software Foundation, manages and directs resources for Python and CPython development.

CPython is the reference implementation of Python. It is written in C, meeting the C89 standard with several select C99 features. Python’s development is conducted largely through the PEP process, the primary mechanism for proposing major new features, collecting community input on issues and documenting Python design decisions. Python coding style is covered in PEP 8.

Technologies

BibTeX

BibTeX is a widely used bibliography management tool in LaTeX, with BibTeX the bibliography entries are kept in a separate file and then imported into the main document.

CSS

CSS is a style sheet language used for describing the presentation of a document written in a markup language like HTML. CSS is a cornerstone technology of the WWW, alongside HTML and JavaScript. In addition to HTML, other markup languages support the use of CSS including plain XML and SVG. The CSS specifications is standardized by the W3C/TR/CSS since 1996.

See also

Enchant

Enchant is a free software project developed as part of the AbiWord word processor with the aim of unifying access to the various existing spell-checker software.

HTML

HTML is the standard markup language for documents designed to be displayed in a web browser. It can be assisted by technologies such as CSS and scripting languages such as JavaScript. The HTML specifications is standardized by the W3C/TR/HTML since 1997 and ISO/IEC JTC1/SC34 since 1998.

See also

PDF

PDF is a file format developed by Adobe in 1993 to present documents, including text formatting and images, in a manner independent of application software, hardware, and operating systems. Based on the PS language, each PDF file encapsulates a complete description of a fixed-layout flat document, including the text, fonts, vector graphics, raster images and other information needed to display it. PDF is standardized by the ISO TC171/SC2/WG8 since 2008, and no longer requires any royalties for its implementation.

ISO standardized subsets of PDF:

See also

PGF
TikZ
PGF/TikZ

PGF/TikZ is a pair of languages for producing vector graphics (for example: technical illustrations and drawings) from a geometric/algebraic description, with standard features including the drawing of points, lines, arrows, paths, circles, ellipses and polygons. PGF, is a lower-level language, while TikZ, which is written in TeX, is a set of higher-level macros that use PGF.

PNG

PNG is a raster-graphics file format that supports lossless data compression. PNG was developed as an improved, non-patented replacement for GIF with support for interactivity and animation. The PNG specification is standardized by the W3C/TR/PNG since 1996 and ISO/IEC JTC1/SC24/WG7 since 2003 as an open standard.

See also

SVG

SVG is an XML-based vector image format for two-dimensional graphics with support for interactivity and animation. The SVG specification is standardized by the W3C/TR/SVG since 1999 as an open standard.

SVG drawings can be dynamic and interactive. Time-based modifications to the elements can be described in SMIL, or can be programmed in a scripting language (e.g. ECMAScript or JavaScript). The W3C explicitly recommends SMIL as the standard for animation in SVG.

See also

TeX

TeX is a computer language designed for use in typesetting system; in particular, for typesetting math and other technical material. It has been noted as one of the most sophisticated digital typographical systems and is also used for many other typesetting tasks, especially in the form of LaTeX, ConTeXt, and other macro packages.

XML

XML is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. The design of XML focuses on documents, the language is widely used for the representation of arbitrary data structures. Several schema systems exist to aid in the definition of XML-based languages. The XML specification is standardized by the W3C/TR/XML since 1998 as an open standard.

See also

Listings

Note

Listings is not supported for HTML.

List of Tables

Note

List of Tables is not supported for HTML.

List of Figures

Note

List of Figures is not supported for HTML.

List of Equations

Note

List of Equations is not supported for HTML.

List of Downloads

Legal Notice of Li-Pro.Net Sphinx Primer

All artifacts were selected and download by using this reference URLs:

List of Issues (To-Do)

Todo

activate “BibTeX Citations” extension.

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/lpn-doc-sphinx-primer/checkouts/0.0.4/source/extensions/bibtex.rst, line 28.)

Todo

activate “Block Diagram Family” extensions.

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/lpn-doc-sphinx-primer/checkouts/0.0.4/source/extensions/blockdiag.rst, line 9.)

Todo

activate “Activity Diagram” extension.

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/lpn-doc-sphinx-primer/checkouts/0.0.4/source/extensions/blockdiag/actdiag.rst, line 25.)

Todo

activate “Block Diagram” extension.

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/lpn-doc-sphinx-primer/checkouts/0.0.4/source/extensions/blockdiag/blockdiag.rst, line 25.)

Todo

activate “Network Diagram” extension.

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/lpn-doc-sphinx-primer/checkouts/0.0.4/source/extensions/blockdiag/nwdiag.rst, line 25.)

Todo

activate “Sequence Diagram” extension.

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/lpn-doc-sphinx-primer/checkouts/0.0.4/source/extensions/blockdiag/seqdiag.rst, line 25.)

Todo

activate “Email Obfuscate” extension.

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/lpn-doc-sphinx-primer/checkouts/0.0.4/source/extensions/email.rst, line 20.)

Todo

activate “LinuxDoc” extension.

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/lpn-doc-sphinx-primer/checkouts/0.0.4/source/extensions/linuxdoc.rst, line 25.)

Todo

activate “Mathematical Plots” extension.

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/lpn-doc-sphinx-primer/checkouts/0.0.4/source/extensions/matplotlib.rst, line 32.)

Todo

activate “Program Output” extension.

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/lpn-doc-sphinx-primer/checkouts/0.0.4/source/extensions/programoutput.rst, line 18.)

Todo

activate “Paneled Content” extension.

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/lpn-doc-sphinx-primer/checkouts/0.0.4/source/extensions/sphinx-panels.rst, line 31.)

Todo

activate “Tabbed Content” extension.

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/lpn-doc-sphinx-primer/checkouts/0.0.4/source/extensions/sphinx-tabs.rst, line 27.)

Todo

activate “PGF/TikZ LaTeX Pictures” extension.

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/lpn-doc-sphinx-primer/checkouts/0.0.4/source/extensions/tikz.rst, line 41.)

Bibliography

juh2019swdocwspx

Jan Ulrich Hasecke. Software-Dokumentation mit Sphinx. CreateSpace (was part of Amazon.com Inc.), today Kindle Direct Publishing (KDP), Seattle, United States of America, 2. edition, 2019. ISBN 1793008779. ISBN-10: 1-79300-877-9, ISBN-13: 978-1793008770, OCLC: 889425279, URL: https://www.amazon.com/dp/1793008779 (March 2020).

Version history

Li-Pro.Net Sphinx Primer Document Revisions

Version

Change

Passed

Date

0.0.4

initial content in chapters “Concepts”

Stephan Linz

2020-09-14

0.0.3

initial content in chapters “Extensions”

Stephan Linz

2020-09-11

0.0.2

initial content in chapters “Cheat Sheet” and “Themes”

Stephan Linz

2020-09-08

0.0.1

base document skeleton

Stephan Linz

2020-09-08

0.0

preliminary, project created

Stephan Linz

2020-09-05