Professional Documents
Culture Documents
Sphinx Rest Memo
Sphinx Rest Memo
Release 1.0
Marc Zonzon
CONTENTS
reST reStructuredText 1.1 Structural elements . 1.2 Inline markup . . . . 1.3 Lists . . . . . . . . 1.4 Blocks . . . . . . . 1.5 Tables . . . . . . . . 1.6 Explicit Markup . . 1.7 Directives . . . . . . 1.8 Sphinx Source Code 1.9 Sphinx . . . . . . . 1.10 References . . . . . Indices and tables
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
3 3 4 4 6 8 11 14 19 23 26 29 31 33 35
ii
Contents:
CONTENTS
CONTENTS
CHAPTER
ONE
REST RESTRUCTUREDTEXT
A simple markup language for plain text les.
Titles are under- (and over-)lined (decorated) by =*-^"~:.# as below. The exact order of the decoration is not important, the one below is the Python convention.
#### Part #### ******* Chapter ******* Section ======= Subsection ---------Subsubsection ^^^^^^^^^^^^^ Paragraph """""""""
1.1.2 Transitions
Any repetition of 4 or more punctuation characters with preceding and trailing blank line is a transition, and looks like this: 3
The following example illustrates special cases: Asterisk *, back-quote and a markup.
1.3 Lists
1.3.1 Bullet list
Code for examples
- First item with some lengthy text wrapping hopefully across several lines. - Second item .. hlist:: :columns: 3 * * * * * list of short items that should be displayed horizontally
2. We start with point number 2 #. Automatically numbered item. a) Point a b) Point b #) Automatic point c.
First item with some lengthy text wrapping hopefully across several lines. Second item
what Denition of what. We add a few words to show the line wrapping. how Denition of how. why [cause] We dene why we do it. In many paragraphs.
Name Isaac Newton Long Here we insert more text to show the effect of many lines.
1.3. Lists
1.4 Blocks
1.4.1 Literal Blocks
Code for example
Block one:: **No** interpretation of |special| characters. Another block! :: In the text body, indentation is preserved
Warning: Sphinx use literal blocks to highlight source code, so the previous **No** is still written with a bold font.
A block which is not interpreted at all is preceded by a :: and a blank line. The block must be intended. If no white space is preceding the :: then it is displayed as :. Block one:
**No** interpretation of |special| characters.
Another block!
In the text body, indentation is preserved
In a line block every line is preceded with | and at least one space.
Line block New line and we are still on the same line Yet a new line
Block quotes are created by just indenting them more than the surrounding paragraphs. Neither from itself nor from another, Nor from both, Nor without a cause, Does anything whatever, anywhere arise. Nagarjuna - Mulamadhyamakakarika An optional attribution can be set by a line beginning by two or three minus signs ushed left at the level of the quote. There is also a pull-quote Just as a solid rock is not shaken by the storm, even so the wise are not affected by praise or blame. An epigraph and an highlights dont forget the nal s or you fall down on the Sphinx code highlighting directive. With these highlights we have completed the Rest blocks. They all generates an html <blockquote> but with a class of pull-quote, highlights or epigraph that your css may use but default css does not!
1.4. Blocks
1.4.4 Container
Code for example
.. container:: myclass There is also a general ...
There is also a general container directive whose unique effect is adding some class name to the block that your css may use. In html this paragraph is enclosed in a
<div class="myclass container"> ... </div>
1.5 Tables
1.5.1 Simple tables
Code for the examples
== aA cC == == bB dD == ====== Umlaut ====== ====== ====== Output -----A or B ====== False -----True True True ====== ================ | blah blah blah blah blah blah blah | blah blah We can wrap the text in source **aha** ================
===== ===== Inputs -----------A B ===== ===== False -----------True False False True True ============ =========== 1. Hallo
Simple tables (ref) are preceded and ended with a sequence of = to indicate the columns, e.g:
aA cC
bB dD
Column spans are followed by a sequence of - (except for the last header or last row of the table where we must have =), e.g: Inputs A B False True False False True True Output A or B False True True True
Simple table cells are treated like a small document on their own up to line breaks, but the rst column must contain a single line. e.g: 1. Hallo blah blah blah blah blah blah blah blah blah 2. Here 32. There We can wrap the text in source aha
Grid tables (ref) have a more difcult syntax but can express more complex tables. Header A B: *hey* Header with 2 cols C Lists: aha a block of text yes a break 1. hi
You can edit them under emacs with table.el (but be carefull about conicts with rst-mode) or use org tables with orgtbl-mode and export to table with org-table-convert or org-table-create-with-table.el ( bound to C-c ~ in org-mode, but not in orgtbl-mode)
1.5. Tables
A clear day with lots of sunshine. However, the strong breeze will bring down the temperatures. * - Tuesday ........
Table 1.1: Balance Sheet Description Travel Fees Grant Train Fare In Out 230.00 400.00 70.00 Balance -230.00 -630.00 70.00 0.00
700.00
The options are explained in the reference: rst directive: csv-table You can choose a delimiter with :delim: and source an external le with the option:
:file:/path/of/the/file
10
Table 1.2: Weather forecast Day Min Temp Max Temp 22C 10C Summary A clear day with lots of sunshine. However, the strong breeze will bring down the temperatures. Cloudy with rain, across many northern regions. Clear spells across most of Scotland and Northern Ireland, but rain reaching the far northwest.
As examples in this document the re:source code directives table source_code_directives which has a proper Sphinx automatic rendering in tabulary |L|L|, which adapt the column size with a wider left one. The two rst simple tables the csv table and the list table are also rendered in tabulary with a proper calculation of table width by latex. Rendering with tabular Tables that contain any kind of lists, such as object descriptions, blockquotes, or literal blocks are set by default with the tabular environment with equal column size, you can taylor the rendering by giving tabularcolumns directive which uses the p{width} column type. An example is the following source code include table which use both description and verbatim for wich the automatic Sphinx rendering in latex is:
\begin{tabular}{|p{0.475\linewidth}|p{0.475\linewidth}|}
1.6.1 Footnotes
11
Code
In the text [2]_. .. [2] In the footnote. First automatic [#]_. Another automatic [#]_. .. [#] The first automatic. .. [#] The other automatic. A labeled automatic [#one]_. Another of these [#two]_. .. [#one] footnote. .. [#two] labeled footnotes. An autosymbol [*]_. More autosymbol [*]_. .. rubric:: Footnotes .. [*] Footnotes can be put in a *Footnotes* rubric at end of document. .. [*] other labeled footnote.
..
In the text 1 . First automatic 2 . Another automatic 3 . A labeled automatic 4 . Another of these 5 . An autosymbol 6 . More autosymbol 7 . There is no labeled version of these autosymbol footnotes.
1.6.2 Citations
Code for example
We cite [REL09]_ or REL09_ or even rel09_. .. [REL09] Citation
.. [REL2009] is followed by the denition of the citation REL2009. It is referenced as [REL2009]_ or REL2009_. Citation labels can contain underlines, hyphens and fullstops. Case is not signicant. In Sphinx, denition and reference can reside in different les. We cite [REL09] or REL09 or even rel09.
1 2 3 4 5 6 7
In the footnote. The rst automatic. The other automatic. footnote. labeled footnotes. Footnotes can be put in a Footnotes rubric at end of document. other labeled footnote.
12
Citation style: A link to Sphinx Home in citation style. In printed documents the link will be listed similar as a citation, as opposed to HTML documents. In-line style: In-line versions are Sphinx Home or http://sphinx.pocoo.org or (in Sphinx) http://sphinx.pocoo.org Internal To dene a label for any text location, precede it with:
.. _label:
plus a blank line. A :name: option in any block is also an internal reference target. There are two ways of referencing a label. The reST way is:
label_
To reference label dened in any document of the project. If the label denition is followed by a section title then displayed text can be omitted and will be replaced by the title. E.g. this section is preceded with .. _internal:, so we have: Internal This section ref to a name
Section titles, footnotes, and citations automatically are link targets. Project_ produces Project. To reference a Python Enhancement Proposal use :pep, for a Request for Comments :rfc:
13
Extensions that dene new hyperlinks targets The extension intersphinx which generate automatic links to the documentation in other projects for objects not in your own project. It interprets the references to roles To congure it give in conf.py a dictionary like:
intersphinx_mapping = { python: (http://docs.python.org/3.2, None)}
The extension Sphinx: extlinks generates the previous link with the code :sphinx:extlinks and the conguration:
extlinks = {sphinx: (http://sphinx.pocoo.org/latest/%s, Sphinx: )}
1.7 Directives
Directives are a general-purpose extension mechanism. The general syntax is similar to Explicit Markup:
.. name:: argument 1 argument 2 :option 1: value body
They are detailled in the document reStructuredText Directives table of contents Create a table of contents containing (sub)titles ranging from level 1 to level number if you use the :local: option the TOC is local to the section where it appears, otherwise it is for the whole le, the title may be empty:
.. contents:: Table of contents :depth: number :local:
14
Other options are: :scale: <integer percentage>, :align: {top|middle|bottom|left|right} Include an image (see also images in the Sphinx documentation and ReST image directive )
You can click on this image to go to the target Wikipedia: Telepino Include a gure
Figure 1.1: Sphinx Hittite gures and LaTeX export The reST commant rst2latex use the width an hight of images and gures but the Sphinx laTeX exporter use also \includegraphics to import the gure; but (as a far as Sphinx 1.2pre) it does not use the width and height attribute. To get proper gure size in latex generated by Sphinx you may have either to resize the gure before including it, use the :scale: option that is supported and generates a latex \scalebox or put a distinct laTeX code in an raw:: latex directive that use something like:
\includegraphics[width=60mm, height=40mm]{myfig.png}
Latex does not support svg and it has to be converted to eps or pdf, pdf being the only one to support transparency. The conversion can be done with Inscape, it can be automated as explained by Johan B. C. Engelen. You can also use the ipe drawing editor. replacement General replacements:
.. |something| directive:: here we define what something is.
1.7. Directives
15
Here |<something>| will be replaced by its denition. Possible directives are replace or image more in directives manual It can be used like above for nesting inline markup. le include Including a reST le .. include:: file name> See also Source code include
Note: Dont use the same le name extension as your source les. Otherwise Sphinx will mistake this le as one of your regular source le.
sidebar, and topic A sidebar or a topic are treated like documents on their own:
.. sidebar:: Title body .. topic:: Topic Title :name: mytopic Subsequent indented lines comprise the body of the topic, and are interpreted as *body elements*.
Topic Title Subsequent indented lines comprise the body of the topic, and are interpreted as body elements.
16
table of contents Index and glossaries note, warning, seealso centered Selective inclusion
table of contents
.. toctree:: :maxdepth: depth :glob: file 1 without file name extension file 2 without file name extension
Create a table of contents across les A glob option enables to use wildcards in the lenames, e.g. /comp/* means all les under the directory comp. Relative names are relative to the document the directive occurs in, absolute names are relative to the source directory. The depth can be further restricted per le by inserting the following Field list type element in the very rst line of the le:
:tocdepth: depth
See Sphinx: Toc tree for other options. To get a table of content inside a le, use the reST table of contents Index and glossaries Entries in the index are created automatically from all information units like functions, classes or attributes but those with a :noindex: option. Explicit manual entries are made as:
.. index:: keyword 1, keyword 2, ... .. index:: single: keyword; sub-keyword .. index:: pair: keyword 1st part; keyword 2nd part
The rst two versions create single (sub-)entries, while the last version creates two entries keyword 1st part; keyword 2nd part and keyword 2nd part; keyword 1st part. A glossary is a reST denition list:
.. glossary:: name definition
1.7. Directives
17
Code
.. note:: text .. warning:: text .. seealso:: reST definition list
Note: This is a note. Warning: This is a warning. See Also: Apples A kind of fruit. centered A centered, boldface text block:
.. centered:: text block
This text is centered, boldface Selective inclusion A block may be included depending of the presence of some tag:
..only:: <expression>
The expression is made of tags like html and draft. You can dene tags via the -t command-line option of sphinx-build or in the conguration le use tags.has(tag) to query, tags.add(tag) and tags.remove(tag) to change.
18
1.7.4 python
role :py:mod: :py:func: :py:data: :py:const: :py:class: :py:meth: :py:attr: :py:exc: reference module function module-level variable. constant class 8 method 6 9 data attribute of an object exception 6
You may supply an explicit title and reference target: :role:title <target>
1.7.5 Comments
Code for example
.. Comment Even more comment Not comment anymore
Everything starting like a directive with two periods and a space but is followed by normal text is a comment. Mark the indentation in the example: Not comment anymore
The option language may be any of Pygment supported languages The additional linenothreshold option switches on line numbering for blocks of size beyond number lines. Specify the highlighting for a single literal block:
.. code-block:: language :linenos: body
The linenos option switches on line numbering. Details of options are in Sphinx Manual: code examples.
8 Class, 9 The
methods, exceptions may be dotted names. role text should include the type name and the method name
19
print("Hello {0}!".format("World"))
More Options: .. literalinclude:: filename :language: language :linenos: :lines: 1,3,5-10,20.. literalinclude:: example.py :pyobject: MyClass.some_method
The options language and linenos set the highlighting to language and enables line numbers respectively. You can select lines by the :lines: option or by start-after:<string> and/or end-before:<string> If it is a Python module, you can select a class, function or method to include using the pyobject option
Describes an object data attribute. Describes an object method. Describes a static method. Describes a class method.
1.8.4 autodoc
There is an autodoc version of the source code directives which include documentation from docstrings: automodule, autoclass, autoexception. They accept an option :members: to include a specic list of members, or all members when the :members: option is empty.
.. autoclass:: Noodle :members: eat, slurp
and attributes belonging to the class should be placed in this directives body.
20
Inside Python object description directives the following elds are recognized: param, arg, key, type, raises, raise, except, exception, var, ivar, cvar, returns, return, rtype reST.divide(i, j) divide two numbers Parameters i (int) numerator j denominator Returns quotient Return type integer Raises ZeroDivisionError
21
alternate syntax
def example(self, arg1, arg2): """Docstring example. :Parameters: - arg1 (float) - the first value - arg2 (float) - the second value :Returns: arg1/arg2 :Returns Type: float :Examples: >>> import template >>> a = MainClass() >>> a.example(6,2) 1.5 .. note:: can be useful to emphasize important features. .. seealso:: :py:exc:ZeroDivisionError .. warning:: arg2 must be non-zero. .. todo:: check that arg2 is non zero. """
You can use the previous elds or the alternate syntax docstring.example(self, arg1, arg2) Docstring example. Parameters arg1 (oat) - the rst value arg2 (oat) - the second value Returns arg1/arg2 Returns Type oat Examples
>>> import template >>> a = MainClass() >>> a.example(6,2) 1.5
Note: can be useful to emphasize important features. See Also: ZeroDivisionError Warning: arg2 must be non-zero.
22
1.9 Sphinx
1.9.1 Project
To start a Sphinx project use the interactive sphinx-quickstart command. This will ask you all the necessary questions.You can choose to build with a Makele. Customization is done in the le conf.py and the Makele. In the conf le you put the conguration of the extensions
1.9.2 Math
There is a mathematical typesetting Sphinx extension called sphinx.ext.pngmath based on LaTeX. To enable the extension, the following line has to appear in conf.py:
extensions = [sphinx.ext.pngmath]
Note: The sphinx.ext.pngmath extension needs dvipng. You then can type standard LaTeX math expressions, either inline:
:math:LaTeX math expression
or in display mode:
.. math:: LaTeX math expressions
E.g: Pythagoras a2 + b2 = c2
N
xn = y
n=0
Multiline Math
1.9. Sphinx
23
Sphinx Built-in Mechanism Several lines of math expressions can be entered by leaving a blank line between them. In addition there is something like an align environment syntax if lines are not separated by a blank line. a+b=c b = xn a = yn =cb Code for example
.. math:: \[a = b\] :nowrap:
or equivalently:
.. math:: :nowrap: \[a = b\]
Explicit LaTeX with amsmath mechanism If the option nowrap is specied then the full LaTeX code (including the math-environment) has to be given. We can assume that the amsmath package is loaded. This is not limited to math typesetting, any LaTeX construct can be rendered in this way. a=b or equivalenty a=b Equation Numbers Equations are labeled with the label option and referred to using:
:eq:label
24
E.g: a2 + b2 = c2 (1.1)
Undirected graph
.. graph:: foo "bar" -- "baz";
bar
baz
Directed graph
.. digraph:: foo "bar" -> "baz";
1.9. Sphinx
25
bar
baz
1.10 References
This doc is a fork of Cristoph Reller Memo adapted according to my needs, they have diverged now, but some part come from his work and I have adopted his layout. Sphinx documentation Sphinx reStructuredText Primer Documenting Your Project Using Sphinx from an example pypi projects Openalea project: How to use sphinx ? by Thomas Cokelaer, the author also gives a more recent version: Sphinx and RST syntax guide. The ReStructuredText Documentation Docutil reStructuredText Primer you may prefer the python the Sphinx nicely formated documentation cited above, also available with a distinct layout as docs.python: reStructuredText Primer Quick reStructuredText reStructuredText Markup Specication reST Directives Interpreted Text Roles ReStructuredText Demonstration Emacs Support for reStructuredText Epydoc reST markup Documenting Python Pylons Book: Documentation is itself a good example of sphinx documentation. sampledoc tutorial from matplotlib a python 2D plotting library. rst2pdf is a tool for transforming reStructuredText to PDF using ReportLab. It supports Sphinx. How to write docstrings: Look at examples in Ofcial list of projects using Sphinx The last parts of Documenting Python: function denitions and Full Code Example OpenAlea has a nice comparaison of three way of lling the docstring. The source is template.py Sources of mongo python driver are also a good example
26
Extending sphinx: Sphinx Tutorial: Writing a simple extension Dening Custom Roles in Sphinx a Sphinx blog post by Doug Hellmann Creating Interpreted Text Roles from docutils project. Creating reStructuredText Directives from docutils project.
1.10. References
27
28
CHAPTER
TWO
29
30
BIBLIOGRAPHY
[REL09] Citation
31
32
Bibliography
r
reST, 3
33
34
INDEX
B
block, 6 line, 6 literal, 6 quotes, 7 blockquotes, 7 epigraph, 7 highlights, 7 pull-quote, 7 bullet list, 4
Q
quotes block, 7 line block, 6
C
code, 4
R
reST (module), 3
D
denition list, 5 directive epigraph, 7 highlights, 7 pull-quote, 7
S
strong, 4
T
tables, 8 title, 3 hierarchy, 3
E
emacs mode, 3 emphasize, 4 enumerated list, 5
F
eld list, 5
H
horizontal list, 4
I
index (Rest), 17 inline markup, 4 code, 4 emphasize, 4 strong, 4
L
list, 4 bullet, 4 denition, 5 enumerated, 5 35