First pass at Sphinx documentation. Most of it still needs to be written :)

This commit is contained in:
Georg Brandl
2008-03-09 21:32:24 +00:00
parent a686a5a03a
commit ccfd92e558
16 changed files with 1697 additions and 0 deletions

BIN
doc/.static/sphinx.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

60
doc/.templates/index.html Normal file
View File

@@ -0,0 +1,60 @@
{% extends "layout.html" %}
{% set title = 'Overview' %}
{% block body %}
<h1>Welcome</h1>
<p>
Sphinx is a tool that makes it easy to create intelligent and beautiful
documentation for Python projects, written by Georg Brandl. It was
originally created to translate <a href="http://docs.python.org/dev/">the
new Python documentation</a>, but has now been cleaned up in the hope that
it will be useful to many other projects. (Of course, this site is also
created from reStructuredText sources using Sphinx!)
</p>
<p>
Although it is still under constant development, the following features are
already present, work fine and can be seen &#8220;in action&#8221; in the
Python docs:
</p>
<ul>
<li><b>Output formats:</b> HTML (including Windows HTML Help) and LaTeX, for
printable PDF versions</li>
<li><b>Extensive cross-references:</b> semantic markup and automatic links
for functions, classes, glossary terms and similar pieces of information</li>
<li><b>Hierarchical structure:</b> easy definition of a document tree, with
automatic links to siblings, parents and children</li>
<li><b>Automatic indices:</b> general index as well as a module index</li>
<li><b>Code handling:</b> automatic highlighting using the <a
href="http://pygments.org">Pygments</a> highlighter</li>
</ul>
<p>
Sphinx uses <a href="http://docutils.sf.net/rst.html">reStructuredText</a>
as its markup language, and many of its strengths come from the power and
straightforwardness of reStructuredText and its parsing and translating
suite, the <a href="http://docutils.sf.net/">Docutils</a>.
</p>
<h2>Documentation</h2>
<table class="contentstable" align="center" style="margin-left: 30px"><tr>
<td width="50%">
<p class="biglink"><a class="biglink" href="{{ pathto("contents") }}">Contents</a><br>
<span class="linkdescr">for a complete overview</span></p>
<p class="biglink"><a class="biglink" href="{{ pathto("search") }}">Search page</a><br>
<span class="linkdescr">search the documentation</span></p>
</td><td width="50%">
<p class="biglink"><a class="biglink" href="{{ pathto("genindex") }}">General Index</a><br>
<span class="linkdescr">all functions, classes, terms</span></p>
<p class="biglink"><a class="biglink" href="{{ pathto("modindex") }}">Module Index</a><br>
<span class="linkdescr">quick access to all documented modules</span></p>
</td></tr>
</table>
<h2>Get Sphinx</h2>
<p>
Sphinx is available as an <a
href="http://peak.telecommunity.com/DevCenter/EasyInstall">easy-install</a>able
package on the <a href="http://pypi.python.org/pypi/Sphinx">Python Package
Index</a>.
</p>
{% endblock %}

View File

@@ -0,0 +1,9 @@
<h3>Download</h3>
<p>Get Sphinx from the <a href="http://pypi.python.org/pypi/Sphinx">Python Package
Index</a>.</p>
<h3>Questions? Suggestions?</h3>
<p>Send them to <nobr>&lt;georg at python org&gt;</nobr>, or come to the
<tt>#python-docs</tt> channel on FreeNode.</p>

View File

@@ -0,0 +1,12 @@
{% extends "!layout.html" %}
{% block rootrellink %}
<li><a href="{{ pathto('index') }}">Sphinx home </a> |&nbsp;</li>
<li><a href="{{ pathto('contents') }}">Documentation </a> &raquo;</li>
{% endblock %}
{% block beforerelbar %}
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<img src="{{ pathto("static/sphinx.png", 1) }}">
</div>
{% endblock %}

9
doc/builders.rst Normal file
View File

@@ -0,0 +1,9 @@
.. _builders:
Builders and the environment
============================
.. module:: sphinx.builder
:synopsis: Available built-in builder classes.

14
doc/concepts.rst Normal file
View File

@@ -0,0 +1,14 @@
.. _concepts:
Sphinx concepts
===============
The TOC tree
------------
Document names
--------------

125
doc/conf.py Normal file
View File

@@ -0,0 +1,125 @@
# -*- coding: utf-8 -*-
#
# Sphinx documentation build configuration file, created by
# sphinx-quickstart.py on Sat Mar 8 21:47:50 2008.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# The contents of this file are pickled, so don't put values in the namespace
# that aren't pickleable (module imports are okay, they're removed automatically).
#
# All configuration values have a default value; values that are commented out
# serve to show the default value.
import sys
# If your extensions are in another directory, add it here.
sys.path.append('.')
# General configuration
# ---------------------
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.addons.*') or your custom ones.
extensions = ['ext']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['.templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The master toctree document.
master_doc = 'contents'
# General substitutions.
project = 'Sphinx'
copyright = '2008, Georg Brandl'
# The default replacements for |version| and |release|, also used in various
# other places throughout the built documents.
#
# The short X.Y version.
version = '0.1'
# The full version, including alpha/beta/rc tags.
release = '0.1'
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
today_fmt = '%B %d, %Y'
# List of documents that shouldn't be included in the build.
#unused_docs = []
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
show_authors = True
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'friendly'
# Options for HTML output
# -----------------------
# The style sheet to use for HTML and HTML Help pages. A file of that name
# must exist either in Sphinx' static/ path, or in one of the custom paths
# given in html_static_path.
html_style = 'sphinxdoc.css'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['.static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Content template for the index page.
html_index = 'index.html'
# Custom sidebar templates, maps page names to templates.
html_sidebars = {'index': 'indexsidebar.html'}
# Additional templates that should be rendered to pages, maps page names to
# templates.
#html_additional_pages = {}
# If true, the reST sources are included in the HTML build as _sources/<name>.
#html_copy_source = True
# Output file base name for HTML help builder.
htmlhelp_basename = 'Sphinxdoc'
# Options for LaTeX output
# ------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, document class [howto/manual]).
latex_documents = [('contents', 'sphinx.tex', 'Sphinx Documentation',
'Georg Brandl', 'manual')]
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []

204
doc/config.rst Normal file
View File

@@ -0,0 +1,204 @@
.. highlightlang:: python
The build configuration file
============================
.. module:: conf
:synopsis: Build configuration file.
The :term:`documentation root` must contain a file named :file:`conf.py`. This
file (containing Python code) is called the "build configuration file" and
contains all configuration needed to customize Sphinx input and output behavior.
The configuration file if executed as Python code at build time (using
:func:`execfile`, and with the current directory set to the documentation root),
and therefore can execute arbitrarily complex code. Sphinx then reads simple
names from the file's namespace as its configuration.
Two conventions are important to keep in mind here: Relative paths are always
used relative to the documentation root, and document names must always be given
without file name extension.
The contents of the namespace are pickled (so that Sphinx can find out when
configuration changes), so it may not contain unpickleable values -- delete them
from the namespace with ``del`` if appropriate. Modules are removed
automatically, so you don't need to ``del`` your imports after use.
The configuration values can be separated in several groups. If not otherwise
documented, values must be strings, and their default is the empty string.
General configuration
---------------------
.. confval:: extensions
A list of strings that are module names of Sphinx extensions. These can be
extensions coming with Sphinx (named ``sphinx.addons.*``) or custom ones.
Note that you can extend :data:`sys.path` within the conf file if your
extensions live in another directory.
.. confval:: templates_path
A list of paths that contain extra templates (or templates that overwrite
builtin templates).
.. confval:: source_suffix
The file name extension of source files. Only files with this suffix will be
read as sources. Default is ``.rst``.
.. confval:: master_doc
The document name of the "master" document, that is, the document that
contains the root :dir:`toctree` directive. Default is ``'contents'``.
.. confval:: project
The documented project's name.
.. confval:: copyright
A copyright statement in the style ``'2008, Author Name'``.
.. confval:: version
The major project version, used as the replacement for ``|version|``. For
example, for the Python documentation, this may be something like ``2.6``.
.. confval:: release
The full project version, used as the replacement for ``|release|`` and
e.g. in the HTML templates. For example, for the Python documentation, this
may be something like ``2.6.0rc1``.
If you don't need the separation provided between :confval:`version` and
:confval:`release`, just set them both to the same value.
.. confval:: today
today_fmt
These values determine how to format the current date, used as the
replacement for ``|today|``.
* If you set :confval:`today` to a non-empty value, it is used.
* Otherwise, the current time is formatted using :func:`time.strftime` and
the format given in :confval:`today_fmt`.
The default is no :confval:`today` and a :confval:`today_fmt` of ``'%B %d,
%Y'``.
.. confval:: unused_docs
A list of document names that are present, but not currently included in the
toctree. Use this setting to suppress the warning that is normally emitted
in that case.
.. confval:: add_function_parentheses
A boolean that decides whether parentheses are appended to function and
method role text (e.g. the content of ``:func:`input```) to signify that the
name is callable. Default is ``True``.
.. confval:: add_module_names
A boolean that decides whether module names are prepended to all
:term:`description unit` titles, e.g. for :dir:`function` directives.
Default is ``True``.
.. confval:: show_authors
A boolean that decides whether :dir:`moduleauthor` and :dir:`sectionauthor`
directives produce any output in the built files.
.. confval:: pygments_style
The style name to use for Pygments highlighting of source code. Default is
``'sphinx'``, which is a builtin style designed to match Sphinx' default
style.
Options for HTML output
-----------------------
These options influence HTML as well as HTML Help output, and other builders
that use Sphinx' HTMLWriter class.
.. confval:: html_style
The style sheet to use for HTML pages. A file of that name must exist either
in Sphinx' :file:`static/` path, or in one of the custom paths given in
:confval:`html_static_path`. Default is ``'default.css'``.
.. confval:: html_static_path
A list of paths that contain custom static files (such as style sheets or
script files). They are copied to the output directory after the builtin
static files, so a file named :file:`default.css` will overwrite the builtin
:file:`default.css`.
.. confval:: html_last_updated_fmt
If this is not the empty string, a 'Last updated on:' timestamp is inserted
at every page bottom, using the given :func:`strftime` format. Default is
``'%b %d, %Y'``.
.. confval:: html_use_smartypants
If true, *SmartyPants* will be used to convert quotes and dashes to
typographically correct entities. Default: ``True``.
.. confval:: html_index
Content template for the index page, filename relative to this file. If this
is not the empty string, the "index" document will not be created from a
reStructuredText file but from this template.
.. confval:: html_sidebars
Custom sidebar templates, must be a dictionary that maps document names to
template names.
.. confval:: html_additional_pages
Additional templates that should be rendered to HTML pages, must be a
dictionary that maps document names to template names.
.. confval:: html_copy_source
If true, the reST sources are included in the HTML build as
:file:`_sources/{name}`.
.. confval:: htmlhelp_basename
Output file base name for HTML help builder. Default is ``'pydoc'``.
Options for LaTeX output
------------------------
These options influence LaTeX output.
.. confval:: latex_paper_size
The output paper size (``'letter'`` or ``'a4'``). Default is ``'letter'``.
.. confval:: latex_font_size
The font size ('10pt', '11pt' or '12pt'). Default is ``'10pt'``.
.. confval:: latex_documents
Grouping the document tree into LaTeX files. List of tuples (source start
file, target name, title, author, document class [howto/manual]).
XXX expand.
.. confval:: latex_appendices
Documents to append as an appendix to all manuals.
.. confval:: latex_preamble
Additional LaTeX markup for the preamble.

27
doc/contents.rst Normal file
View File

@@ -0,0 +1,27 @@
.. _contents:
Sphinx documentation contents
=============================
.. toctree::
:maxdepth: 1
intro.rst
concepts.rst
rest.rst
markup.rst
builders.rst
config.rst
templating.rst
extensions.rst
glossary.rst
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
* :ref:`glossary`

4
doc/ext.py Normal file
View File

@@ -0,0 +1,4 @@
def setup(app):
app.add_description_unit('directive', 'dir', 'directive')
app.add_description_unit('role', 'role', 'role')
app.add_description_unit('confval', 'confval', 'configuration value')

110
doc/extensions.rst Normal file
View File

@@ -0,0 +1,110 @@
.. _extensions:
Sphinx Extensions
=================
.. module:: sphinx.application
:synopsis: Application class and extensibility interface.
Since many projects will need special features in their documentation, Sphinx is
designed to be extensible on several levels.
First, you can add new :term:`builder`\s to support new output formats or
actions on the parsed documents. Then, it is possible to register custom
reStructuredText roles and directives, extending the markup. And finally, there
are so-called "hook points" at strategic places throughout the build process,
where an extension can register a hook and run specialized code.
Each Sphinx extension is a Python module with at least a :func:`setup` function.
This function is called at initialization time with one argument, the
application object representing the Sphinx process. This application object has
the following public API:
.. method:: Application.add_builder(builder)
Register a new builder. *builder* must be a class that inherits from
:class:`~sphinx.builder.Builder`.
.. method:: Application.add_config_value(name, default, rebuild_env)
Register a configuration value. This is necessary for Sphinx to recognize
new values and set default values accordingly. The *name* should be prefixed
with the extension name, to avoid clashes. The *default* value can be any
Python object. The boolean value *rebuild_env* must be ``True`` if a change
in the setting only takes effect when a document is parsed -- this means that
the whole environment must be rebuilt.
.. method:: Application.add_event(name)
Register an event called *name*.
.. method:: Application.add_node(node)
Register a Docutils node class. This is necessary for Docutils internals.
It may also be used in the future to validate nodes in the parsed documents.
.. method:: Application.add_directive(name, cls, content, arguments, **options)
Register a Docutils directive. *name* must be the prospective directive
name, *func* the directive function (see the Docutils documentation - XXX
ref) for details about the signature and return value. *content*,
*arguments* and *options* are set as attributes on the function and determine
whether the directive has content, arguments and options, respectively. For
their exact meaning, please consult the Docutils documentation.
.. method:: Application.add_role(name, role)
Register a Docutils role. *name* must be the role name that occurs in the
source, *role* the role function (see the Docutils documentation on details).
.. method:: Application.add_description_unit(directivename, rolename, indexdesc='', parse_node=None)
XXX
.. method:: Application.connect(event, callback)
Register *callback* to be called when *event* is emitted. For details on
available core events and the arguments of callback functions, please see
:ref:`events`.
The method returns a "listener ID" that can be used as an argument to
:meth:`disconnect`.
.. method:: Application.disconnect(listener_id)
Unregister callback *listener_id*.
.. method:: Application.emit(event, *arguments)
Emit *event* and pass *arguments* to the callback functions. Do not emit
core Sphinx events in extensions!
.. exception:: ExtensionError
All these functions raise this exception if something went wrong with the
extension API.
Examples of using the Sphinx extension API can be seen in the :mod:`sphinx.ext`
package.
.. _events:
Sphinx core events
------------------
These events are known to the core:
====================== =================================== =========
Event name Emitted when Arguments
====================== =================================== =========
``'builder-inited'`` the builder object has been created -none-
``'doctree-read'`` a doctree has been parsed and read *doctree*
by the environment, and is about to
be pickled
``'doctree-resolved'`` a doctree has been "resolved" by *doctree*, *docname*
the environment, that is, all
references and TOCs have been
inserted
====================== =================================== =========

22
doc/glossary.rst Normal file
View File

@@ -0,0 +1,22 @@
.. _glossary:
Glossary
========
.. glossary::
builder
A class (inheriting from :class:`~sphinx.builder.Builder`) that takes
parsed documents and performs an action on them. Normally, builders
translate the documents to an output format, but it is also possible to
use the builder builders that e.g. check for broken links in the
documentation, or build coverage information.
See :ref:`builders` for an overview over Sphinx' built-in builders.
description unit
XXX
documentation root
The directory which contains the documentation's :file:`conf.py` file and
is therefore seen as one Sphinx project.

11
doc/intro.rst Normal file
View File

@@ -0,0 +1,11 @@
Introduction
============
Prerequisites
-------------
Running a build
---------------

835
doc/markup.rst Normal file
View File

@@ -0,0 +1,835 @@
.. highlight:: rest
:linenothreshold: 5
.. XXX missing: glossary
Sphinx Markup Constructs
========================
Sphinx adds a lot of new directives and interpreted text roles to standard reST
markup. This section contains the reference material for these facilities.
File-wide metadata
------------------
reST has the concept of "field lists"; these are a sequence of fields marked up
like this::
:Field name: Field content
A field list at the very top of a file is parsed as the "docinfo", which in
normal documents can be used to record the author, date of publication and
other metadata. In Sphinx, the docinfo is used as metadata, too, but not
displayed in the output.
At the moment, only one metadata field is recognized:
``nocomments``
If set, the web application won't display a comment form for a page generated
from this source file.
Meta-information markup
-----------------------
.. directive:: sectionauthor
Identifies the author of the current section. The argument should include
the author's name such that it can be used for presentation and email
address. The domain name portion of the address should be lower case.
Example::
.. sectionauthor:: Guido van Rossum <guido@python.org>
By default, this markup isn't reflected in the output in any way (it helps
keep track of contributions), but you can set the configuration value
:confval:`show_authors` to True to make them produce a paragraph in the
output.
Module-specific markup
----------------------
The markup described in this section is used to provide information about a
module being documented. Each module should be documented in its own file.
Normally this markup appears after the title heading of that file; a typical
file might start like this::
:mod:`parrot` -- Dead parrot access
===================================
.. module:: parrot
:platform: Unix, Windows
:synopsis: Analyze and reanimate dead parrots.
.. moduleauthor:: Eric Cleese <eric@python.invalid>
.. moduleauthor:: John Idle <john@python.invalid>
As you can see, the module-specific markup consists of two directives, the
``module`` directive and the ``moduleauthor`` directive.
.. directive:: module
This directive marks the beginning of the description of a module (or package
submodule, in which case the name should be fully qualified, including the
package name).
The ``platform`` option, if present, is a comma-separated list of the
platforms on which the module is available (if it is available on all
platforms, the option should be omitted). The keys are short identifiers;
examples that are in use include "IRIX", "Mac", "Windows", and "Unix". It is
important to use a key which has already been used when applicable.
The ``synopsis`` option should consist of one sentence describing the
module's purpose -- it is currently only used in the Global Module Index.
The ``deprecated`` option can be given (with no value) to mark a module as
deprecated; it will be designated as such in various locations then.
.. directive:: moduleauthor
The ``moduleauthor`` directive, which can appear multiple times, names the
authors of the module code, just like ``sectionauthor`` names the author(s)
of a piece of documentation. It too only produces output if the
:confval:`show_authors` configuration value is True.
.. note::
It is important to make the section title of a module-describing file
meaningful since that value will be inserted in the table-of-contents trees
in overview files.
Information units
-----------------
There are a number of directives used to describe specific features provided by
modules. Each directive requires one or more signatures to provide basic
information about what is being described, and the content should be the
description. The basic version makes entries in the general index; if no index
entry is desired, you can give the directive option flag ``:noindex:``. The
following example shows all of the features of this directive type::
.. function:: spam(eggs)
ham(eggs)
:noindex:
Spam or ham the foo.
The signatures of object methods or data attributes should always include the
type name (``.. method:: FileInput.input(...)``), even if it is obvious from the
context which type they belong to; this is to enable consistent
cross-references. If you describe methods belonging to an abstract protocol,
such as "context managers", include a (pseudo-)type name too to make the
index entries more informative.
The directives are:
.. directive:: cfunction
Describes a C function. The signature should be given as in C, e.g.::
.. cfunction:: PyObject* PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
This is also used to describe function-like preprocessor macros. The names
of the arguments should be given so they may be used in the description.
Note that you don't have to backslash-escape asterisks in the signature,
as it is not parsed by the reST inliner.
.. directive:: cmember
Describes a C struct member. Example signature::
.. cmember:: PyObject* PyTypeObject.tp_bases
The text of the description should include the range of values allowed, how
the value should be interpreted, and whether the value can be changed.
References to structure members in text should use the ``member`` role.
.. directive:: cmacro
Describes a "simple" C macro. Simple macros are macros which are used
for code expansion, but which do not take arguments so cannot be described as
functions. This is not to be used for simple constant definitions. Examples
of its use in the Python documentation include :cmacro:`PyObject_HEAD` and
:cmacro:`Py_BEGIN_ALLOW_THREADS`.
.. directive:: ctype
Describes a C type. The signature should just be the type name.
.. directive:: cvar
Describes a global C variable. The signature should include the type, such
as::
.. cvar:: PyObject* PyClass_Type
.. directive:: data
Describes global data in a module, including both variables and values used
as "defined constants." Class and object attributes are not documented
using this environment.
.. directive:: exception
Describes an exception class. The signature can, but need not include
parentheses with constructor arguments.
.. directive:: function
Describes a module-level function. The signature should include the
parameters, enclosing optional parameters in brackets. Default values can be
given if it enhances clarity. For example::
.. function:: Timer.repeat([repeat=3[, number=1000000]])
Object methods are not documented using this directive. Bound object methods
placed in the module namespace as part of the public interface of the module
are documented using this, as they are equivalent to normal functions for
most purposes.
The description should include information about the parameters required and
how they are used (especially whether mutable objects passed as parameters
are modified), side effects, and possible exceptions. A small example may be
provided.
.. directive:: class
Describes a class. The signature can include parentheses with parameters
which will be shown as the constructor arguments.
.. directive:: attribute
Describes an object data attribute. The description should include
information about the type of the data to be expected and whether it may be
changed directly.
.. directive:: method
Describes an object method. The parameters should not include the ``self``
parameter. The description should include similar information to that
described for ``function``.
.. directive:: opcode
Describes a Python bytecode instruction (this is not very useful for projects
other than Python itself).
.. directive:: cmdoption
Describes a command line option or switch. Option argument names should be
enclosed in angle brackets. Example::
.. cmdoption:: -m <module>
Run a module as a script.
.. directive:: envvar
Describes an environment variable that the documented code uses or defines.
There is also a generic version of these directives:
.. directive:: describe
This directive produces the same formatting as the specific ones explained
above but does not create index entries or cross-referencing targets. It is
used, for example, to describe the directives in this document. Example::
.. describe:: opcode
Describes a Python bytecode instruction.
Showing code examples
---------------------
Examples of Python source code or interactive sessions are represented using
standard reST literal blocks. They are started by a ``::`` at the end of the
preceding paragraph and delimited by indentation.
Representing an interactive session requires including the prompts and output
along with the Python code. No special markup is required for interactive
sessions. After the last line of input or output presented, there should not be
an "unused" primary prompt; this is an example of what *not* to do::
>>> 1 + 1
2
>>>
Syntax highlighting is handled in a smart way:
* There is a "highlighting language" for each source file. Per default,
this is ``'python'`` as the majority of files will have to highlight Python
snippets.
* Within Python highlighting mode, interactive sessions are recognized
automatically and highlighted appropriately.
* The highlighting language can be changed using the ``highlightlang``
directive, used as follows::
.. highlightlang:: c
This language is used until the next ``highlightlang`` directive is
encountered.
* The valid values for the highlighting language are:
* ``python`` (the default)
* ``c``
* ``rest``
* ``none`` (no highlighting)
* If highlighting with the current language fails, the block is not highlighted
in any way.
Longer displays of verbatim text may be included by storing the example text in
an external file containing only plain text. The file may be included using the
``literalinclude`` directive. [1]_ For example, to include the Python source file
:file:`example.py`, use::
.. literalinclude:: example.py
The file name is relative to the current file's path. Documentation-specific
include files should be placed in the ``Doc/includes`` subdirectory.
Inline markup
-------------
As said before, Sphinx uses interpreted text roles to insert semantic markup in
documents.
Variable names are an exception, they should be marked simply with ``*var*``.
For all other roles, you have to write ``:rolename:`content```.
.. note::
For all cross-referencing roles, if you prefix the content with ``!``, no
reference/hyperlink will be created.
The following roles refer to objects in modules and are possibly hyperlinked if
a matching identifier is found:
.. role:: mod
The name of a module; a dotted name may be used. This should also be used for
package names.
.. role:: func
The name of a Python function; dotted names may be used. The role text
should include trailing parentheses to enhance readability. The parentheses
are stripped when searching for identifiers.
.. role:: data
The name of a module-level variable.
.. role:: const
The name of a "defined" constant. This may be a C-language ``#define``
or a Python variable that is not intended to be changed.
.. role:: class
A class name; a dotted name may be used.
.. role:: meth
The name of a method of an object. The role text should include the type
name, method name and the trailing parentheses. A dotted name may be used.
.. role:: attr
The name of a data attribute of an object.
.. role:: exc
The name of an exception. A dotted name may be used.
The name enclosed in this markup can include a module name and/or a class name.
For example, ``:func:`filter``` could refer to a function named ``filter`` in
the current module, or the built-in function of that name. In contrast,
``:func:`foo.filter``` clearly refers to the ``filter`` function in the ``foo``
module.
Normally, names in these roles are searched first without any further
qualification, then with the current module name prepended, then with the
current module and class name (if any) prepended. If you prefix the name with a
dot, this order is reversed. For example, in the documentation of the
:mod:`codecs` module, ``:func:`open``` always refers to the built-in function,
while ``:func:`.open``` refers to :func:`codecs.open`.
A similar heuristic is used to determine whether the name is an attribute of
the currently documented class.
The following roles create cross-references to C-language constructs if they
are defined in the API documentation:
.. role:: cdata
The name of a C-language variable.
.. role:: cfunc
The name of a C-language function. Should include trailing parentheses.
.. role:: cmacro
The name of a "simple" C macro, as defined above.
.. role:: ctype
The name of a C-language type.
The following roles do possibly create a cross-reference, but do not refer
to objects:
.. role:: token
The name of a grammar token (used in the reference manual to create links
between production displays).
.. role:: keyword
The name of a keyword in Python. This creates a link to a reference label
with that name, if it exists.
The following role creates a cross-reference to the term in the glossary:
.. role:: term
Reference to a term in the glossary. The glossary is created using the
``glossary`` directive containing a definition list with terms and
definitions. It does not have to be in the same file as the ``term`` markup,
for example the Python docs have one global glossary in the ``glossary.rst``
file.
If you use a term that's not explained in a glossary, you'll get a warning
during build.
---------
The following roles don't do anything special except formatting the text
in a different style:
.. role:: command
The name of an OS-level command, such as ``rm``.
.. role:: dfn
Mark the defining instance of a term in the text. (No index entries are
generated.)
.. role:: envvar
An environment variable. Index entries are generated.
.. role:: file
The name of a file or directory. Within the contents, you can use curly
braces to indicate a "variable" part, for example::
... is installed in :file:`/usr/lib/python2.{x}/site-packages` ...
In the built documentation, the ``x`` will be displayed differently to
indicate that it is to be replaced by the Python minor version.
.. role:: guilabel
Labels presented as part of an interactive user interface should be marked
using ``guilabel``. This includes labels from text-based interfaces such as
those created using :mod:`curses` or other text-based libraries. Any label
used in the interface should be marked with this role, including button
labels, window titles, field names, menu and menu selection names, and even
values in selection lists.
.. role:: kbd
Mark a sequence of keystrokes. What form the key sequence takes may depend
on platform- or application-specific conventions. When there are no relevant
conventions, the names of modifier keys should be spelled out, to improve
accessibility for new users and non-native speakers. For example, an
*xemacs* key sequence may be marked like ``:kbd:`C-x C-f```, but without
reference to a specific application or platform, the same sequence should be
marked as ``:kbd:`Control-x Control-f```.
.. role:: mailheader
The name of an RFC 822-style mail header. This markup does not imply that
the header is being used in an email message, but can be used to refer to any
header of the same "style." This is also used for headers defined by the
various MIME specifications. The header name should be entered in the same
way it would normally be found in practice, with the camel-casing conventions
being preferred where there is more than one common usage. For example:
``:mailheader:`Content-Type```.
.. role:: makevar
The name of a :command:`make` variable.
.. role:: manpage
A reference to a Unix manual page including the section,
e.g. ``:manpage:`ls(1)```.
.. role:: menuselection
Menu selections should be marked using the ``menuselection`` role. This is
used to mark a complete sequence of menu selections, including selecting
submenus and choosing a specific operation, or any subsequence of such a
sequence. The names of individual selections should be separated by
``-->``.
For example, to mark the selection "Start > Programs", use this markup::
:menuselection:`Start --> Programs`
When including a selection that includes some trailing indicator, such as the
ellipsis some operating systems use to indicate that the command opens a
dialog, the indicator should be omitted from the selection name.
.. role:: mimetype
The name of a MIME type, or a component of a MIME type (the major or minor
portion, taken alone).
.. role:: newsgroup
The name of a Usenet newsgroup.
.. role:: option
A command-line option to an executable program. The leading hyphen(s) must
be included.
.. role:: program
The name of an executable program. This may differ from the file name for
the executable for some platforms. In particular, the ``.exe`` (or other)
extension should be omitted for Windows programs.
.. role:: regexp
A regular expression. Quotes should not be included.
.. role:: samp
A piece of literal text, such as code. Within the contents, you can use
curly braces to indicate a "variable" part, as in ``:file:``.
If you don't need the "variable part" indication, use the standard
````code```` instead.
.. role:: var
A Python or C variable or parameter name.
The following roles generate external links:
.. role:: pep
A reference to a Python Enhancement Proposal. This generates appropriate
index entries. The text "PEP *number*\ " is generated; in the HTML output,
this text is a hyperlink to an online copy of the specified PEP.
.. role:: rfc
A reference to an Internet Request for Comments. This generates appropriate
index entries. The text "RFC *number*\ " is generated; in the HTML output,
this text is a hyperlink to an online copy of the specified RFC.
Note that there are no special roles for including hyperlinks as you can use
the standard reST markup for that purpose.
.. _doc-ref-role:
Cross-linking markup
--------------------
.. XXX add new :ref: syntax alternative
To support cross-referencing to arbitrary sections in the documentation, the
standard reST labels are "abused" a bit: Every label must precede a section
title; and every label name must be unique throughout the entire documentation
source.
You can then reference to these sections using the ``:ref:`label-name``` role.
Example::
.. _my-reference-label:
Section to cross-reference
--------------------------
This is the text of the section.
It refers to the section itself, see :ref:`my-reference-label`.
The ``:ref:`` invocation is replaced with the section title.
Paragraph-level markup
----------------------
These directives create short paragraphs and can be used inside information
units as well as normal text:
.. directive:: note
An especially important bit of information about an API that a user should be
aware of when using whatever bit of API the note pertains to. The content of
the directive should be written in complete sentences and include all
appropriate punctuation.
Example::
.. note::
This function is not suitable for sending spam e-mails.
.. directive:: warning
An important bit of information about an API that a user should be very aware
of when using whatever bit of API the warning pertains to. The content of
the directive should be written in complete sentences and include all
appropriate punctuation. This differs from ``note`` in that it is recommended
over ``note`` for information regarding security.
.. directive:: versionadded
This directive documents the version of the project which added the described
feature to the library or C API. When this applies to an entire module, it
should be placed at the top of the module section before any prose.
The first argument must be given and is the version in question; you can add
a second argument consisting of a *brief* explanation of the change.
Example::
.. versionadded:: 2.5
The `spam` parameter.
Note that there must be no blank line between the directive head and the
explanation; this is to make these blocks visually continuous in the markup.
.. directive:: versionchanged
Similar to ``versionadded``, but describes when and what changed in the named
feature in some way (new parameters, changed side effects, etc.).
--------------
.. directive:: seealso
Many sections include a list of references to module documentation or
external documents. These lists are created using the ``seealso`` directive.
The ``seealso`` directive is typically placed in a section just before any
sub-sections. For the HTML output, it is shown boxed off from the main flow
of the text.
The content of the ``seealso`` directive should be a reST definition list.
Example::
.. seealso::
Module :mod:`zipfile`
Documentation of the :mod:`zipfile` standard module.
`GNU tar manual, Basic Tar Format <http://link>`_
Documentation for tar archive files, including GNU tar extensions.
.. directive:: rubric
This directive creates a paragraph heading that is not used to create a
table of contents node. It is currently used for the "Footnotes" caption.
.. directive:: centered
This directive creates a centered boldfaced paragraph. Use it as follows::
.. centered::
Paragraph contents.
Table-of-contents markup
------------------------
Since reST does not have facilities to interconnect several documents, or split
documents into multiple output files, Sphinx uses a custom directive to add
relations between the single files the documentation is made of, as well as
tables of contents. The ``toctree`` directive is the central element.
.. directive:: toctree
This directive inserts a "TOC tree" at the current location, using the
individual TOCs (including "sub-TOC trees") of the files given in the
directive body. A numeric ``maxdepth`` option may be given to indicate the
depth of the tree; by default, all levels are included.
Consider this example (taken from the library reference index)::
.. toctree::
:maxdepth: 2
intro.rst
strings.rst
datatypes.rst
numeric.rst
(many more files listed here)
This accomplishes two things:
* Tables of contents from all those files are inserted, with a maximum depth
of two, that means one nested heading. ``toctree`` directives in those
files are also taken into account.
* Sphinx knows that the relative order of the files ``intro.rst``,
``strings.rst`` 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 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 ``contents.rst`` at the root of the source directory is the
"root" of the TOC tree hierarchy; from it the "Contents" page is generated.
Index-generating markup
-----------------------
Sphinx automatically creates index entries from all information units (like
functions, classes or attributes) like discussed before.
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, such as the language reference.
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
module: __main__
module: sys
triple: module; search; path
This directive contains five entries, which will be converted to entries in the
generated index which link to the exact location of the index statement (or, in
case of offline media, the corresponding page number).
The possible entry types are:
single
Creates a single index entry. Can be made a subentry by separating the
subentry text with a semicolon (this notation is also used below to describe
what entries are created).
pair
``pair: loop; statement`` is a shortcut that creates two index entries,
namely ``loop; statement`` and ``statement; loop``.
triple
Likewise, ``triple: module; search; path`` is a shortcut that creates three
index entries, which are ``module; search path``, ``search; path, module`` and
``path; module search``.
module, keyword, operator, object, exception, statement, builtin
These all create two index entries. For example, ``module: hashlib`` creates
the entries ``module; hashlib`` and ``hashlib; module``.
For index directives containing only "single" entries, there is a shorthand
notation::
.. index:: BNF, grammar, syntax, notation
This creates four index entries.
Grammar production displays
---------------------------
Special markup is available for displaying the productions of a formal grammar.
The markup is simple and does not attempt to model all aspects of BNF (or any
derived forms), but provides enough to allow context-free grammars to be
displayed in a way that causes uses of a symbol to be rendered as hyperlinks to
the definition of the symbol. There is this directive:
.. directive:: productionlist
This directive is used to enclose a group of productions. Each production is
given on a single line and consists of a name, separated by a colon from the
following definition. If the definition spans multiple lines, each
continuation line must begin with a colon placed at the same column as in the
first line.
Blank lines are not allowed within ``productionlist`` directive arguments.
The definition can contain token names which are marked as interpreted text
(e.g. ``sum ::= `integer` "+" `integer```) -- this generates cross-references
to the productions of these tokens.
Note that no further reST parsing is done in the production, so that you
don't have to escape ``*`` or ``|`` characters.
.. XXX describe optional first parameter
The following is an example taken from the Python Reference Manual::
.. productionlist::
try_stmt: try1_stmt | try2_stmt
try1_stmt: "try" ":" `suite`
: ("except" [`expression` ["," `target`]] ":" `suite`)+
: ["else" ":" `suite`]
: ["finally" ":" `suite`]
try2_stmt: "try" ":" `suite`
: "finally" ":" `suite`
Substitutions
-------------
The documentation system provides three substitutions that are defined by default.
They are set in the build configuration file, see :ref:`doc-build-config`.
.. describe:: |release|
Replaced by the project release the documentation refers to. This is meant
to be the full version string including alpha/beta/release candidate tags,
e.g. ``2.5.2b3``.
.. describe:: |version|
Replaced by the project version the documentation refers to. This is meant to
consist only of the major and minor version parts, e.g. ``2.5``, even for
version 2.5.1.
.. describe:: |today|
Replaced by either today's date, or the date set in the build configuration
file. Normally has the format ``April 14, 2007``.
.. rubric:: Footnotes
.. [1] There is a standard ``.. include`` directive, but it raises errors if the
file is not found. This one only emits a warning.

251
doc/rest.rst Normal file
View File

@@ -0,0 +1,251 @@
.. highlightlang:: rest
reStructuredText Primer
=======================
This section is a brief introduction to reStructuredText (reST) concepts and
syntax, intended to provide authors with enough information to author documents
productively. Since reST was designed to be a simple, unobtrusive markup
language, this will not take too long.
.. seealso::
The authoritative `reStructuredText User
Documentation <http://docutils.sourceforge.net/rst.html>`_.
Paragraphs
----------
The paragraph is the most basic block in a reST document. Paragraphs are simply
chunks of text separated by one or more blank lines. As in Python, indentation
is significant in reST, so all lines of the same paragraph must be left-aligned
to the same level of indentation.
Inline markup
-------------
The standard reST inline markup is quite simple: use
* one asterisk: ``*text*`` for emphasis (italics),
* two asterisks: ``**text**`` for strong emphasis (boldface), and
* backquotes: ````text```` for code samples.
If asterisks or backquotes appear in running text and could be confused with
inline markup delimiters, they have to be escaped with a backslash.
Be aware of some restrictions of this markup:
* it may not be nested,
* content may not start or end with whitespace: ``* text*`` is wrong,
* it must be separated from surrounding text by non-word characters. Use a
backslash escaped space to work around that: ``thisis\ *one*\ word``.
These restrictions may be lifted in future versions of the docutils.
reST also allows for custom "interpreted text roles"', which signify 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```.
Lists and Quotes
----------------
List markup is natural: just place an asterisk at the start of a paragraph and
indent properly. The same goes for numbered lists; they can also be
autonumbered using a ``#`` sign::
* This is a bulleted list.
* It has two items, the second
item uses two lines.
1. This is a numbered list.
2. It has two items too.
#. This is a numbered list.
#. It has two items too.
Note that Sphinx disables the use of enumerated lists introduced by alphabetic
or roman numerals, such as ::
A. First item
B. Second item
Nested lists are possible, but be aware that they must be separated from the
parent list items by blank lines::
* this is
* a list
* with a nested list
* and some subitems
* and here the parent list continues
Definition lists are created as follows::
term (up to a line of text)
Definition of the term, which must be indented
and can even consist of multiple paragraphs
next term
Description.
Paragraphs are quoted by just indenting them more than the surrounding
paragraphs.
Source Code
-----------
Literal code blocks are introduced by ending a paragraph with the special marker
``::``. The literal block must be indented, to be able to include blank lines::
This is a normal text paragraph. The next paragraph is a code sample::
It is not processed in any way, except
that the indentation is removed.
It can span multiple lines.
This is a normal text paragraph again.
The handling of the ``::`` marker is smart:
* If it occurs as a paragraph of its own, that paragraph is completely left
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 second sentence in the above example's first paragraph would be
rendered as "The next paragraph is a code sample:".
Hyperlinks
----------
External links
^^^^^^^^^^^^^^
Use ```Link text <http://target>`_`` for inline web links. If the link text
should be the web address, you don't need special markup at all, the parser
finds links and mail addresses in ordinary text.
Internal links
^^^^^^^^^^^^^^
Internal linking is done via a special reST role, see the section on specific
markup, :ref:`doc-ref-role`.
Sections
--------
Section headers are created by underlining (and optionally overlining) the
section title with a punctuation character, at least as long as the text::
=================
This is a heading
=================
Normally, there are no heading levels assigned to certain characters as the
structure is determined from the succession of headings. However, for the
Python documentation, this convention is used which you may follow:
* ``#`` with overline, for parts
* ``*`` with overline, for chapters
* ``=``, for sections
* ``-``, for subsections
* ``^``, for subsubsections
* ``"``, for paragraphs
Explicit Markup
---------------
"Explicit markup" is used in reST for most constructs that need special
handling, such as footnotes, specially-highlighted paragraphs, comments, and
generic directives.
An explicit markup block begins with a line starting with ``..`` followed by
whitespace and is terminated by the next paragraph at the same level of
indentation. (There needs to be a blank line between explicit markup and normal
paragraphs. This may all sound a bit complicated, but it is intuitive enough
when you write it.)
Directives
----------
A directive is a generic block of explicit markup. Besides roles, it is one of
the extension mechanisms of reST, 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 the next chapter describing custom
directives.) Looking at this example, ::
.. function:: foo(x)
foo(y, z)
:bar: no
Return a line of text input from the user.
``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 ``bar``
(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.
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, like so::
Lorem ipsum [#]_ dolor sit amet ... [#]_
.. rubric:: Footnotes
.. [#] Text of the first footnote.
.. [#] Text of the second footnote.
You can also explicitly number the footnotes for better context.
Comments
--------
Every explicit markup block which isn't a valid markup construct (like the
footnotes above) is regarded as a comment.
Source encoding
---------------
Since the easiest way to include special characters like em dashes or copyright
signs in reST is to directly write them as Unicode characters, one has to
specify an encoding:
All documentation source files must be in UTF-8 encoding, and the HTML
documents written from them will be in that encoding as well.
Gotchas
-------
There are some problems one commonly runs into while authoring reST documents:
* **Separation of inline markup:** As said above, inline markup spans must be
separated from the surrounding text by non-word characters, you have to use
an escaped space to get around that.
.. XXX more?

4
doc/templating.rst Normal file
View File

@@ -0,0 +1,4 @@
.. _templating:
Templating
==========