diff options
| author | Yoshiki Shibukawa <yoshiki@shibu.jp> | 2014-01-22 00:10:09 -0800 |
|---|---|---|
| committer | Yoshiki Shibukawa <yoshiki@shibu.jp> | 2014-01-22 00:10:09 -0800 |
| commit | 5a6a7d60281dbbb7b46e560766e5490147126bdc (patch) | |
| tree | 8d1543c47b5b9a73fd30c04db50937d6f28e67b4 /doc | |
| parent | 6fb5828937fcf407d3931d98e57bfc98f37aafc8 (diff) | |
| parent | 930d996dbe5bcccbb0d86de5940376b70ed7c3db (diff) | |
| download | sphinx-5a6a7d60281dbbb7b46e560766e5490147126bdc.tar.gz | |
merge default
Diffstat (limited to 'doc')
| -rw-r--r-- | doc/Makefile | 160 | ||||
| -rw-r--r-- | doc/conf.py | 1 | ||||
| -rw-r--r-- | doc/config.rst | 54 | ||||
| -rw-r--r-- | doc/contents.rst | 1 | ||||
| -rw-r--r-- | doc/devguide.rst | 31 | ||||
| -rw-r--r-- | doc/ext/autodoc.rst | 24 | ||||
| -rw-r--r-- | doc/ext/example_google.py | 223 | ||||
| -rw-r--r-- | doc/ext/example_google.rst | 15 | ||||
| -rw-r--r-- | doc/ext/example_numpy.py | 272 | ||||
| -rw-r--r-- | doc/ext/example_numpy.rst | 15 | ||||
| -rw-r--r-- | doc/ext/napoleon.rst | 375 | ||||
| -rw-r--r-- | doc/extdev/appapi.rst (renamed from doc/ext/appapi.rst) | 89 | ||||
| -rw-r--r-- | doc/extdev/builderapi.rst (renamed from doc/ext/builderapi.rst) | 4 | ||||
| -rw-r--r-- | doc/extdev/domainapi.rst | 14 | ||||
| -rw-r--r-- | doc/extdev/envapi.rst | 54 | ||||
| -rw-r--r-- | doc/extdev/index.rst | 33 | ||||
| -rw-r--r-- | doc/extdev/markupapi.rst | 11 | ||||
| -rw-r--r-- | doc/extdev/nodes.rst | 57 | ||||
| -rw-r--r-- | doc/extdev/tutorial.rst (renamed from doc/ext/tutorial.rst) | 79 | ||||
| -rw-r--r-- | doc/extensions.rst | 33 | ||||
| -rw-r--r-- | doc/install.rst | 6 | ||||
| -rw-r--r-- | doc/intro.rst | 2 | ||||
| -rw-r--r-- | doc/invocation.rst | 4 | ||||
| -rw-r--r-- | doc/markup/code.rst | 19 | ||||
| -rw-r--r-- | doc/markup/toctree.rst | 9 |
25 files changed, 1297 insertions, 288 deletions
diff --git a/doc/Makefile b/doc/Makefile index 831c12c5..55909649 100644 --- a/doc/Makefile +++ b/doc/Makefile @@ -4,157 +4,15 @@ # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = python ../sphinx-build.py -PAPER = - -PAPEROPT_a4 = -D latex_paper_size=a4 -PAPEROPT_letter = -D latex_paper_size=letter -ALLSPHINXOPTS = -d _build/doctrees $(PAPEROPT_$(PAPER)) \ - $(SPHINXOPTS) $(O) . -I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) $(O) . - -.PHONY: help clean html dirhtml singlehtml text man pickle json htmlhelp \ - qthelp devhelp epub latex latexpdf changes linkcheck doctest xml \ - pseudoxml +SPHINXPROJ = sphinx +SOURCEDIR = . +BUILDDIR = _build +# Has to be explicit, otherwise we don't get "make" without targets right. help: - @echo "Please use \`make <target>' where <target> is one of" - @echo " html to make standalone HTML files" - @echo " dirhtml to make HTML files called index.html in directories" - @echo " singlehtml to make one big HTML file" - @echo " text to make text files" - @echo " man to make manual pages" - @echo " pickle to make pickle files" - @echo " json to make json files" - @echo " htmlhelp to make HTML files and a HTML help project" - @echo " qthelp to make Qt help files and project" - @echo " devhelp to make Devhelp files and project" - @echo " epub to make an epub file" - @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" - @echo " latexpdf to make LaTeX files and run pdflatex" - @echo " texinfo to make Texinfo files" - @echo " info to make Texinfo files and run them through makeinfo" - @echo " gettext to make PO message catalogs" - @echo " changes to make an overview over all changed/added/deprecated items" - @echo " linkcheck to check all external links for integrity" - -clean: - rm -rf _build/* - -html: - $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) _build/html - @echo - @echo "Build finished. The HTML pages are in _build/html." - -dirhtml: - $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) _build/dirhtml - @echo - @echo "Build finished. The HTML pages are in _build/dirhtml." - -singlehtml: - $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) _build/singlehtml - @echo - @echo "Build finished. The HTML page is in _build/singlehtml." - -text: - $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) _build/text - @echo - @echo "Build finished." - -man: - $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) _build/man - @echo - @echo "Build finished." - -pickle: - $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) _build/pickle - @echo - @echo "Build finished." - -json: - $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) _build/json - @echo - @echo "Build finished." - -htmlhelp: - $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) _build/htmlhelp - @echo - @echo "Build finished; now you can run HTML Help Workshop with the" \ - ".hhp project file in _build/htmlhelp." - -qthelp: - $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) _build/qthelp - @echo - @echo "Build finished; now you can run qcollectiongenerator with the" \ - ".qhcp project file in build/qthelp." - @echo "# qcollectiongenerator _build/qthelp/Sphinx.qhcp" - @echo "To view the help collection:" - @echo "# assistant -collectionFile _build/qthelp/Sphinx.qhc" - -devhelp: - $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) _build/devhelp - @echo - @echo "Build finished." - @echo "To view the help file:" - @echo "# mkdir -p $$HOME/.local/share/devhelp/sphinx" - @echo "# ln -s _build/devhelp $$HOME/.local/share/devhelp/sphinx" - @echo "# devhelp" - -epub: - $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) _build/epub - @echo - @echo "Build finished. The epub file is in _build/epub." - -latex: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) _build/latex - @echo - @echo "Build finished; the LaTeX files are in _build/latex." - @echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \ - "run these through (pdf)latex." - -latexpdf: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) _build/latex - @echo "Running LaTeX files through pdflatex..." - make -C _build/latex all-pdf - @echo "pdflatex finished; the PDF files are in _build/latex." - -gettext: - $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) _build/locale - @echo - @echo "Build finished. The message catalogs are in _build/locale." - -changes: - $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) _build/changes - @echo - @echo "The overview file is in _build/changes." - -linkcheck: - $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) _build/linkcheck - @echo - @echo "Link check complete; look for any errors in the above output " \ - "or in _build/linkcheck/output.txt." - -doctest: - $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) _build/doctest - -texinfo: - $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) _build/texinfo - @echo - @echo "Build finished. The Texinfo files are in _build/texinfo." - @echo "Run \`make' in that directory to run these through makeinfo" \ - "(use \`make info' here to do that automatically)." - -info: - $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) _build/texinfo - @echo "Running Texinfo files through makeinfo..." - make -C _build/texinfo info - @echo "makeinfo finished; the Info files are in _build/texinfo." - -xml: - $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) _build/xml - @echo - @echo "Build finished. The XML files are in _build/XML." + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) -pseudoxml: - $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) _build/pseudoxml - @echo - @echo "Build finished. The pseudo-XML files are in _build/pseudoxml." +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) diff --git a/doc/conf.py b/doc/conf.py index 08149fba..9932c8ed 100644 --- a/doc/conf.py +++ b/doc/conf.py @@ -5,6 +5,7 @@ import re import sphinx + extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.todo', 'sphinx.ext.autosummary', 'sphinx.ext.extlinks'] diff --git a/doc/config.rst b/doc/config.rst index 181ef2a4..1b196abb 100644 --- a/doc/config.rst +++ b/doc/config.rst @@ -45,7 +45,8 @@ Important points to note: * There is a special object named ``tags`` available in the config file. It can be used to query and change the tags (see :ref:`tags`). Use ``tags.has('tag')`` to query, ``tags.add('tag')`` and ``tags.remove('tag')`` - to change. + to change. Only tags set via the ``-t`` command-line option or via + ``tags.add('tag')`` can be queried using ``tags.has('tag')``. General configuration @@ -113,38 +114,6 @@ General configuration .. versionadded:: 1.0 -.. 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. - - .. deprecated:: 1.0 - Use :confval:`exclude_patterns` or :ref:`metadata` instead. - -.. confval:: exclude_trees - - A list of directory paths, relative to the source directory, that are to be - recursively excluded from the search for source files, that is, their - subdirectories won't be searched too. The default is ``[]``. - - .. versionadded:: 0.4 - - .. deprecated:: 1.0 - Use :confval:`exclude_patterns` instead. - -.. confval:: exclude_dirnames - - A list of directory names that are to be excluded from any recursive - operation Sphinx performs (e.g. searching for source files or copying static - files). This is useful, for example, to exclude version-control-specific - directories like ``'CVS'``. The default is ``[]``. - - .. versionadded:: 0.5 - - .. deprecated:: 1.0 - Use :confval:`exclude_patterns` instead. - .. confval:: templates_path A list of paths that contain extra templates (or templates that overwrite @@ -496,22 +465,25 @@ that use Sphinx' HTMLWriter class. .. confval:: html_logo - If given, this must be the name of an image file that is the logo of the - docs. It is placed at the top of the sidebar; its width should therefore not - exceed 200 pixels. Default: ``None``. + If given, this must be the name of an image file (path relative to the + :term:`configuration directory`) that is the logo of the docs. It is placed + at the top of the sidebar; its width should therefore not exceed 200 pixels. + Default: ``None``. .. versionadded:: 0.4.1 The image file will be copied to the ``_static`` directory of the output - HTML, so an already existing file with that name will be overwritten. + HTML, but only if the file does not already exist there. .. confval:: html_favicon - If given, this must be the name of an image file (within the static path, see - below) that is the favicon of the docs. Modern browsers use this as icon for - tabs, windows and bookmarks. It should be a Windows-style icon file - (``.ico``), which is 16x16 or 32x32 pixels large. Default: ``None``. + If given, this must be the name of an image file (path relative to the + :term:`configuration directory`) that is the favicon of the docs. Modern browsers use this + as icon for tabs, windows and bookmarks. It should be a Windows-style icon + file (``.ico``), which is 16x16 or 32x32 pixels large. Default: ``None``. .. versionadded:: 0.4 + The image file will be copied to the ``_static`` directory of the output + HTML, but only if the file does not already exist there. .. confval:: html_static_path diff --git a/doc/contents.rst b/doc/contents.rst index 5e0ae6c1..d3fd3c8e 100644 --- a/doc/contents.rst +++ b/doc/contents.rst @@ -18,6 +18,7 @@ Sphinx documentation contents theming templating extensions + extdev/index websupport faq diff --git a/doc/devguide.rst b/doc/devguide.rst index b23acb1c..fccdd3fa 100644 --- a/doc/devguide.rst +++ b/doc/devguide.rst @@ -80,7 +80,7 @@ These are the basic steps needed to start developing on Sphinx. For new features or other substantial changes that should wait until the next major release, use the ``default`` branch. -#. Setup your Python environment. :: +#. Optional: setup a virtual environment. :: virtualenv ~/sphinxenv . ~/sphinxenv/bin/activate @@ -90,32 +90,33 @@ These are the basic steps needed to start developing on Sphinx. For tips on working with the code, see the `Coding Guide`_. -#. Test, test, test. +#. Test, test, test. Possible steps: - Run the unit tests:: + * Run the unit tests:: - pip install nose + pip install nose mock make test - Build the documentation and check the output for different builders:: + * Build the documentation and check the output for different builders:: - cd docs - make clean html text man info latexpdf + cd doc + make clean html latexpdf - Run the unit tests under different Python environments using - :program:`tox`:: + * Run the unit tests under different Python environments using + :program:`tox`:: pip install tox tox -v - Add a new unit test in the ``tests`` directory if you can. + * Add a new unit test in the ``tests`` directory if you can. - For bug fixes, first add a test that fails without your changes and passes - after they are applied. + * For bug fixes, first add a test that fails without your changes and passes + after they are applied. -#. Commit your changes. :: +#. Please add a bullet point to :file:`CHANGES` if the fix or feature is not trivial + (small doc updates, typo fixes). Then commit:: - hg commit -m 'Add useful new feature that does this.' + hg commit -m '#42: Add useful new feature that does this.' BitBucket recognizes `certain phrases`__ that can be used to automatically update the issue tracker. @@ -214,7 +215,7 @@ Coding Guide generated output. * When adding a new configuration variable, be sure to document it and update - :file:`sphinx/quickstart.py`. + :file:`sphinx/quickstart.py` if it's important enough. * Use the included :program:`utils/check_sources.py` script to check for common formatting issues (trailing whitespace, lengthy lines, etc). diff --git a/doc/ext/autodoc.rst b/doc/ext/autodoc.rst index c92fe0c4..38d7700e 100644 --- a/doc/ext/autodoc.rst +++ b/doc/ext/autodoc.rst @@ -26,6 +26,16 @@ hand-written documentation, this technique eases the pain of having to maintain two locations for documentation, while at the same time avoiding auto-generated-looking pure API documentation. +If you prefer `NumPy`_ or `Google`_ style docstrings over reStructuredText, +you can also enable the :mod:`napoleon <sphinx.ext.napoleon>` extension. +:mod:`napoleon <sphinx.ext.napoleon>` is a preprocessor that converts your +docstrings to correct reStructuredText before :mod:`autodoc` processes them. + +.. _Google: + http://google-styleguide.googlecode.com/svn/trunk/pyguide.html#Comments +.. _NumPy: + https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt + :mod:`autodoc` provides several directives that are versions of the usual :rst:dir:`py:module`, :rst:dir:`py:class` and so forth. On parsing time, they import the corresponding module and extract the docstring of the given objects, @@ -195,6 +205,12 @@ inserting them into the page source under a suitable :rst:dir:`py:module`, .. versionadded:: 1.2 + * Add a list of modules in the :confval:`autodoc_mock_imports` to prevent + import errors to halt the building process when some external dependencies + are not importable at build time. + + .. versionadded:: 1.3 + .. rst:directive:: autofunction autodata @@ -335,6 +351,14 @@ There are also new config values that you can set: .. versionadded:: 1.1 +.. confval:: autodoc_mock_imports + + This value contains a list of modules to be mocked up. This is useful when + some external dependencies are not met at build time and break the building + process. + + .. versionadded:: 1.3 + Docstring preprocessing ----------------------- diff --git a/doc/ext/example_google.py b/doc/ext/example_google.py new file mode 100644 index 00000000..c94dcdf1 --- /dev/null +++ b/doc/ext/example_google.py @@ -0,0 +1,223 @@ +# -*- coding: utf-8 -*- +"""Example Google style docstrings. + +This module demonstrates documentation as specified by the `Google Python +Style Guide`_. Docstrings may extend over multiple lines. Sections are created +with a section header and a colon followed by a block of indented text. + +Example: + Examples can be given using either the ``Example`` or ``Examples`` + sections. Sections support any reStructuredText formatting, including + literal blocks:: + + $ python example_google.py + +Section breaks are created by simply resuming unindented text. Section breaks +are also implicitly created anytime a new section starts. + +Attributes: + module_level_variable (int): Module level variables may be documented in + either the ``Attributes`` section of the module docstring, or in an + inline docstring immediately following the variable. + + Either form is acceptable, but the two should not be mixed. Choose + one convention to document module level variables and be consistent + with it. + +.. _Google Python Style Guide: + http://google-styleguide.googlecode.com/svn/trunk/pyguide.html + +""" + +module_level_variable = 12345 + + +def module_level_function(param1, param2=None, *args, **kwargs): + """This is an example of a module level function. + + Function parameters should be documented in the ``Args`` section. The name + of each parameter is required. The type and description of each parameter + is optional, but should be included if not obvious. + + If the parameter itself is optional, it should be noted by adding + ", optional" to the type. If \*args or \*\*kwargs are accepted, they + should be listed as \*args and \*\*kwargs. + + The format for a parameter is:: + + name (type): description + The description may span multiple lines. Following + lines should be indented. + + Multiple paragraphs are supported in parameter + descriptions. + + Args: + param1 (int): The first parameter. + param2 (str, optional): The second parameter. Defaults to None. + Second line of description should be indented. + *args: Variable length argument list. + **kwargs: Arbitrary keyword arguments. + + Returns: + bool: True if successful, False otherwise. + + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } + + Raises: + AttributeError: The ``Raises`` section is a list of all exceptions + that are relevant to the interface. + ValueError: If `param2` is equal to `param1`. + + """ + if param1 == param2: + raise ValueError('param1 may not be equal to param2') + return True + + +def example_generator(n): + """Generators have a ``Yields`` section instead of a ``Returns`` section. + + Args: + n (int): The upper limit of the range to generate, from 0 to `n` - 1 + + Yields: + int: The next number in the range of 0 to `n` - 1 + + Examples: + Examples should be written in doctest format, and should illustrate how + to use the function. + + >>> print [i for i in example_generator(4)] + [0, 1, 2, 3] + + """ + for i in range(n): + yield i + + +class ExampleError(Exception): + """Exceptions are documented in the same way as classes. + + The __init__ method may be documented in either the class level + docstring, or as a docstring on the __init__ method itself. + + Either form is acceptable, but the two should not be mixed. Choose one + convention to document the __init__ method and be consistent with it. + + Note: + Do not include the `self` parameter in the ``Args`` section. + + Args: + msg (str): Human readable string describing the exception. + code (int, optional): Error code, defaults to 2. + + Attributes: + msg (str): Human readable string describing the exception. + code (int): Exception error code. + + """ + def __init__(self, msg, code=2): + self.msg = msg + self.code = code + + +class ExampleClass(object): + """The summary line for a class docstring should fit on one line. + + If the class has public attributes, they should be documented here + in an ``Attributes`` section and follow the same formatting as a + function's ``Args`` section. + + Attributes: + attr1 (str): Description of `attr1`. + attr2 (list of str): Description of `attr2`. + attr3 (int): Description of `attr3`. + + """ + def __init__(self, param1, param2, param3=0): + """Example of docstring on the __init__ method. + + The __init__ method may be documented in either the class level + docstring, or as a docstring on the __init__ method itself. + + Either form is acceptable, but the two should not be mixed. Choose one + convention to document the __init__ method and be consistent with it. + + Note: + Do not include the `self` parameter in the ``Args`` section. + + Args: + param1 (str): Description of `param1`. + param2 (list of str): Description of `param2`. Multiple + lines are supported. + param3 (int, optional): Description of `param3`, defaults to 0. + + """ + self.attr1 = param1 + self.attr2 = param2 + self.attr3 = param3 + + def example_method(self, param1, param2): + """Class methods are similar to regular functions. + + Note: + Do not include the `self` parameter in the ``Args`` section. + + Args: + param1: The first parameter. + param2: The second parameter. + + Returns: + True if successful, False otherwise. + + """ + return True + + def __special__(self): + """By default special members with docstrings are included. + + Special members are any methods or attributes that start with and + end with a double underscore. Any special member with a docstring + will be included in the output. + + This behavior can be disabled by changing the following setting in + Sphinx's conf.py:: + + napoleon_include_special_with_doc = False + + """ + pass + + def __special_without_docstring__(self): + pass + + def _private(self): + """By default private members are not included. + + Private members are any methods or attributes that start with an + underscore and are *not* special. By default they are not included + in the output. + + This behavior can be changed such that private members *are* included + by changing the following setting in Sphinx's conf.py:: + + napoleon_include_private_with_doc = True + + """ + pass + + def _private_without_docstring(self): + pass diff --git a/doc/ext/example_google.rst b/doc/ext/example_google.rst new file mode 100644 index 00000000..06508082 --- /dev/null +++ b/doc/ext/example_google.rst @@ -0,0 +1,15 @@ +:orphan: + +.. _example_google: + +Example Google Style Python Docstrings +====================================== + +.. seealso:: + + :ref:`example_numpy` + +Download: :download:`example_google.py <example_google.py>` + +.. literalinclude:: example_google.py + :language: python diff --git a/doc/ext/example_numpy.py b/doc/ext/example_numpy.py new file mode 100644 index 00000000..df1d20e6 --- /dev/null +++ b/doc/ext/example_numpy.py @@ -0,0 +1,272 @@ +# -*- coding: utf-8 -*- +"""Example NumPy style docstrings. + +This module demonstrates documentation as specified by the `NumPy +Documentation HOWTO`_. Docstrings may extend over multiple lines. Sections +are created with a section header followed by an underline of equal length. + +Example +------- +Examples can be given using either the ``Example`` or ``Examples`` +sections. Sections support any reStructuredText formatting, including +literal blocks:: + + $ python example_numpy.py + + +Section breaks are created with two blank lines. Section breaks are also +implicitly created anytime a new section starts. Section bodies *may* be +indented: + +Notes +----- + This is an example of an indented section. It's like any other section, + but the body is indented to help it stand out from surrounding text. + +If a section is indented, then a section break is created simply by +resuming unindented text. + +Attributes +---------- +module_level_variable : int + Module level variables may be documented in either the ``Attributes`` + section of the module docstring, or in an inline docstring immediately + following the variable. + + Either form is acceptable, but the two should not be mixed. Choose + one convention to document module level variables and be consistent + with it. + +.. _NumPy Documentation HOWTO: + https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt + +""" + +module_level_variable = 12345 + + +def module_level_function(param1, param2=None, *args, **kwargs): + """This is an example of a module level function. + + Function parameters should be documented in the ``Parameters`` section. + The name of each parameter is required. The type and description of each + parameter is optional, but should be included if not obvious. + + If the parameter itself is optional, it should be noted by adding + ", optional" to the type. If \*args or \*\*kwargs are accepted, they + should be listed as \*args and \*\*kwargs. + + The format for a parameter is:: + + name : type + description + + The description may span multiple lines. Following lines + should be indented to match the first line of the description. + + Multiple paragraphs are supported in parameter + descriptions. + + Parameters + ---------- + param1 : int + The first parameter. + param2 : str, optional + The second parameter, defaults to None. + *args + Variable length argument list. + **kwargs + Arbitrary keyword arguments. + + Returns + ------- + bool + True if successful, False otherwise. + + The return type is not optional. The ``Returns`` section may span + multiple lines and paragraphs. Following lines should be indented to + match the first line of the description. + + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } + + Raises + ------ + AttributeError + The ``Raises`` section is a list of all exceptions + that are relevant to the interface. + ValueError + If `param2` is equal to `param1`. + + """ + if param1 == param2: + raise ValueError('param1 may not be equal to param2') + return True + + +def example_generator(n): + """Generators have a ``Yields`` section instead of a ``Returns`` section. + + Parameters + ---------- + n : int + The upper limit of the range to generate, from 0 to `n` - 1 + + Yields + ------ + int + The next number in the range of 0 to `n` - 1 + + Examples + -------- + Examples should be written in doctest format, and should illustrate how + to use the function. + + >>> print [i for i in example_generator(4)] + [0, 1, 2, 3] + + """ + for i in range(n): + yield i + + +class ExampleError(Exception): + """Exceptions are documented in the same way as classes. + + The __init__ method may be documented in either the class level + docstring, or as a docstring on the __init__ method itself. + + Either form is acceptable, but the two should not be mixed. Choose one + convention to document the __init__ method and be consistent with it. + + Note + ---- + Do not include the `self` parameter in the ``Parameters`` section. + + Parameters + ---------- + msg : str + Human readable string describing the exception. + code : int, optional + Error code, defaults to 2. + + Attributes + ---------- + msg : str + Human readable string describing the exception. + code : int + Exception error code. + + """ + def __init__(self, msg, code=2): + self.msg = msg + self.code = code + + +class ExampleClass(object): + """The summary line for a class docstring should fit on one line. + + If the class has public attributes, they should be documented here + in an ``Attributes`` section and follow the same formatting as a + function's ``Parameters`` section. + + Attributes + ---------- + attr1 : str + Description of `attr1`. + attr2 : list of str + Description of `attr2`. + attr3 : int + Description of `attr3`. + + """ + def __init__(self, param1, param2, param3=0): + """Example of docstring on the __init__ method. + + The __init__ method may be documented in either the class level + docstring, or as a docstring on the __init__ method itself. + + Either form is acceptable, but the two should not be mixed. Choose one + convention to document the __init__ method and be consistent with it. + + Note + ---- + Do not include the `self` parameter in the ``Parameters`` section. + + Parameters + ---------- + param1 : str + Description of `param1`. + param2 : list of str + Description of `param2`. Multiple + lines are supported. + param3 : int, optional + Description of `param3`, defaults to 0. + + """ + self.attr1 = param1 + self.attr2 = param2 + self.attr3 = param3 + + def example_method(self, param1, param2): + """Class methods are similar to regular functions. + + Note + ---- + Do not include the `self` parameter in the ``Parameters`` section. + + Parameters + ---------- + param1 + The first parameter. + param2 + The second parameter. + + Returns + ------- + bool + True if successful, False otherwise. + + """ + return True + + def __special__(self): + """By default special members with docstrings are included. + + Special members are any methods or attributes that start with and + end with a double underscore. Any special member with a docstring + will be included in the output. + + This behavior can be disabled by changing the following setting in + Sphinx's conf.py:: + + napoleon_include_special_with_doc = False + + """ + pass + + def __special_without_docstring__(self): + pass + + def _private(self): + """By default private members are not included. + + Private members are any methods or attributes that start with an + underscore and are *not* special. By default they are not included + in the output. + + This behavior can be changed such that private members *are* included + by changing the following setting in Sphinx's conf.py:: + + napoleon_include_private_with_doc = True + + """ + pass + + def _private_without_docstring(self): + pass diff --git a/doc/ext/example_numpy.rst b/doc/ext/example_numpy.rst new file mode 100644 index 00000000..a3b41613 --- /dev/null +++ b/doc/ext/example_numpy.rst @@ -0,0 +1,15 @@ +:orphan: + +.. _example_numpy: + +Example NumPy Style Python Docstrings +====================================== + +.. seealso:: + + :ref:`example_google` + +Download: :download:`example_numpy.py <example_numpy.py>` + +.. literalinclude:: example_numpy.py + :language: python diff --git a/doc/ext/napoleon.rst b/doc/ext/napoleon.rst new file mode 100644 index 00000000..32deecb8 --- /dev/null +++ b/doc/ext/napoleon.rst @@ -0,0 +1,375 @@ +:mod:`sphinx.ext.napoleon` -- Support for NumPy and Google style docstrings +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. module:: sphinx.ext.napoleon + :synopsis: Support for NumPy and Google style docstrings + +.. moduleauthor:: Rob Ruana + +.. versionadded:: 1.3 + +Napoleon - *Marching toward legible docstrings* +=============================================== + +Are you tired of writing docstrings that look like this:: + + :param path: The path of the file to wrap + :type path: str + :param field_storage: The :class:`FileStorage` instance to wrap + :type field_storage: FileStorage + :param temporary: Whether or not to delete the file when the File + instance is destructed + :type temporary: bool + :returns: A buffered writable file descriptor + :rtype: BufferedFileStorage + +`ReStructuredText`_ is great, but it creates visually dense, hard to read +`docstrings`_. Compare the jumble above to the same thing rewritten +according to the `Google Python Style Guide`_:: + + Args: + path (str): The path of the file to wrap + field_storage (FileStorage): The :class:`FileStorage` instance to wrap + temporary (bool): Whether or not to delete the file when the File + instance is destructed + + Returns: + BufferedFileStorage: A buffered writable file descriptor + +Much more legible, no? + +Napoleon is a Sphinx extension that allows you to write readable API +documentation in your source code. Napoleon understands both `NumPy`_ and +`Google`_ style docstrings - the style recommended by `Khan Academy`_. + +.. _ReStructuredText: http://docutils.sourceforge.net/rst.html +.. _docstrings: http://www.python.org/dev/peps/pep-0287/ +.. _Google Python Style Guide: + http://google-styleguide.googlecode.com/svn/trunk/pyguide.html +.. _Google: + http://google-styleguide.googlecode.com/svn/trunk/pyguide.html#Comments +.. _NumPy: + https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt +.. _Khan Academy: + https://sites.google.com/a/khanacademy.org/forge/for-developers/styleguide/python#TOC-Docstrings + +Getting Started +--------------- + +1. After `setting up Sphinx`_ to build your docs, enable napoleon in the + Sphinx `conf.py` file:: + + # conf.py + + # Add autodoc and napoleon to the extensions list + extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon'] + +2. Use `sphinx-apidoc` to build your API documentation:: + + $ sphinx-apidoc -f -o docs/source projectdir + +.. _setting up Sphinx: http://sphinx-doc.org/tutorial.html + +Docstrings +---------- + +Napoleon interprets every docstring that :mod:`autodoc <sphinx.ext.autodoc>` +can find, including docstrings on: ``modules``, ``classes``, ``attributes``, +``methods``, ``functions``, and ``variables``. Inside each docstring, +specially formatted `Sections`_ are parsed and converted to +reStructuredText. + +All standard reStructuredText formatting still works as expected. + + +.. _Sections: + +Docstring Sections +------------------ + +All of the following section headers are supported: + + * ``Args`` *(alias of Parameters)* + * ``Arguments`` *(alias of Parameters)* + * ``Attributes`` + * ``Example`` + * ``Examples`` + * ``Keyword Args`` *(alias of Keyword Arguments)* + * ``Keyword Arguments`` + * ``Methods`` + * ``Note`` + * ``Notes`` + * ``Other Parameters`` + * ``Parameters`` + * ``Return`` *(alias of Returns)* + * ``Returns`` + * ``Raises`` + * ``References`` + * ``See Also`` + * ``Warning`` + * ``Warnings`` *(alias of Warning)* + * ``Warns`` + * ``Yields`` + +Google vs NumPy +--------------- + +Napoleon supports two styles of docstrings: `Google`_ and `NumPy`_. The +main difference between the two styles is that Google uses indention to +separate sections, whereas NumPy uses underlines. + +Google style:: + + def func(arg1, arg2): + """Summary line. + + Extended description of function. + + Args: + arg1 (int): Description of arg1 + arg2 (str): Description of arg2 + + Returns: + bool: Description of return value + + """ + return True + +NumPy style:: + + def func(arg1, arg2): + """Summary line. + + Extended description of function. + + Parameters + ---------- + arg1 : int + Description of arg1 + arg2 : str + Description of arg2 + + Returns + ------- + bool + Description of return value + + """ + return True + +NumPy style tends to require more vertical space, whereas Google style +tends to use more horizontal space. Google style tends to be easier to +read for short and simple docstrings, whereas NumPy style tends be easier +to read for long and in-depth docstrings. + +The `Khan Academy`_ recommends using Google style. + +The choice between styles is largely aesthetic, but the two styles should +not be mixed. Choose one style for your project and be consistent with it. + +.. seealso:: + + For complete examples: + + * :ref:`example_google` + * :ref:`example_numpy` + + +Configuration +============= + +Listed below are all the settings used by napoleon and their default +values. These settings can be changed in the Sphinx `conf.py` file. Make +sure that both "sphinx.ext.autodoc" and "sphinx.ext.napoleon" are +enabled in `conf.py`:: + + # conf.py + + # Add any Sphinx extension module names here, as strings + extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon'] + + # Napoleon settings + napoleon_google_docstring = True + napoleon_numpy_docstring = True + napoleon_include_private_with_doc = False + napoleon_include_special_with_doc = True + napoleon_use_admonition_for_examples = False + napoleon_use_admonition_for_notes = False + napoleon_use_admonition_for_references = False + napoleon_use_ivar = False + napoleon_use_param = False + napoleon_use_rtype = False + +.. _Google style: + http://google-styleguide.googlecode.com/svn/trunk/pyguide.html +.. _NumPy style: + https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt + + + +.. confval:: napoleon_google_docstring + + True to parse `Google style`_ docstrings. False to disable support + for Google style docstrings. *Defaults to True.* + +.. confval:: napoleon_numpy_docstring + + True to parse `NumPy style`_ docstrings. False to disable support + for NumPy style docstrings. *Defaults to True.* + +.. confval:: napoleon_include_private_with_doc + + True to include private members (like ``_membername``) with docstrings + in the documentation. False to fall back to Sphinx's default behavior. + *Defaults to False.* + + **If True**:: + + def _included(self): + """ + This will be included in the docs because it has a docstring + """ + pass + + def _skipped(self): + # This will NOT be included in the docs + pass + +.. confval:: napoleon_include_special_with_doc + + True to include special members (like ``__membername__``) with + docstrings in the documentation. False to fall back to Sphinx's + default behavior. *Defaults to True.* + + **If True**:: + + def __str__(self): + """ + This will be included in the docs because it has a docstring + """ + return unicode(self).encode('utf-8') + + def __unicode__(self): + # This will NOT be included in the docs + return unicode(self.__class__.__name__) + +.. confval:: napoleon_use_admonition_for_examples + + True to use the ``.. admonition::`` directive for the **Example** and + **Examples** sections. False to use the ``.. rubric::`` directive + instead. One may look better than the other depending on what HTML + theme is used. *Defaults to False.* + + This `NumPy style`_ snippet will be converted as follows:: + + Example + ------- + This is just a quick example + + **If True**:: + + .. admonition:: Example + + This is just a quick example + + **If False**:: + + .. rubric:: Example + + This is just a quick example + +.. confval:: napoleon_use_admonition_for_notes + + True to use the ``.. admonition::`` directive for **Notes** sections. + False to use the ``.. rubric::`` directive instead. *Defaults to False.* + + .. note:: The singular **Note** section will always be converted to a + ``.. note::`` directive. + + .. seealso:: + + :attr:`napoleon_use_admonition_for_examples` + +.. confval:: napoleon_use_admonition_for_references + + True to use the ``.. admonition::`` directive for **References** + sections. False to use the ``.. rubric::`` directive instead. + *Defaults to False.* + + .. seealso:: + + :attr:`napoleon_use_admonition_for_examples` + +.. confval:: napoleon_use_ivar + + True to use the ``:ivar:`` role for instance variables. False to use + the ``.. attribute::`` directive instead. *Defaults to False.* + + This `NumPy style`_ snippet will be converted as follows:: + + Attributes + ---------- + attr1 : int + Description of `attr1` + + **If True**:: + + :ivar attr1: Description of `attr1` + :vartype attr1: int + + **If False**:: + + .. attribute:: attr1 + :annotation: int + + Description of `attr1` + +.. confval:: napoleon_use_param + + True to use a ``:param:`` role for each function parameter. False to + use a single ``:parameters:`` role for all the parameters. + *Defaults to False.* + + This `NumPy style`_ snippet will be converted as follows:: + + Parameters + ---------- + arg1 : str + Description of `arg1` + arg2 : int, optional + Description of `arg2`, defaults to 0 + + **If True**:: + + :param arg1: Description of `arg1` + :type arg1: str + :param arg2: Description of `arg2`, defaults to 0 + :type arg2: int, optional + + **If False**:: + + :parameters: * **arg1** (*str*) -- + Description of `arg1` + * **arg2** (*int, optional*) -- + Description of `arg2`, defaults to 0 + +.. confval:: napoleon_use_rtype + + True to use the ``:rtype:`` role for the return type. False to output + the return type inline with the description. *Defaults to False.* + + This `NumPy style`_ snippet will be converted as follows:: + + Returns + ------- + bool + True if successful, False otherwise + + **If True**:: + + :returns: True if successful, False otherwise + :rtype: bool + + **If False**:: + + :returns: *bool* -- True if successful, False otherwise diff --git a/doc/ext/appapi.rst b/doc/extdev/appapi.rst index 156dede8..eca191bb 100644 --- a/doc/ext/appapi.rst +++ b/doc/extdev/appapi.rst @@ -1,14 +1,27 @@ .. highlight:: rest -Extension API -============= +Application API +=============== + +.. module:: sphinx.application + :synopsis: Application class and extensibility interface. -.. currentmodule:: sphinx.application 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: +application object representing the Sphinx process. + +.. class:: Sphinx + + This application object has the public API described in the following. + +Extension setup +--------------- + +These methods are usually called in an extension's ``setup()`` function. + +Examples of using the Sphinx extension API can be seen in the :mod:`sphinx.ext` +package. .. method:: Sphinx.setup_extension(name) @@ -296,6 +309,14 @@ the following public API: .. versionadded:: 1.1 +.. method:: Sphinx.require_sphinx(version) + + Compare *version* (which must be a ``major.minor`` version string, + e.g. ``'1.1'``) with the version of the running Sphinx, and abort the build + when it is too old. + + .. versionadded:: 1.0 + .. method:: Sphinx.connect(event, callback) Register *callback* to be called when *event* is emitted. For details on @@ -309,6 +330,16 @@ the following public API: Unregister callback *listener_id*. + +.. exception:: ExtensionError + + All these methods raise this exception if something went wrong with the + extension API. + + +Emitting events +--------------- + .. method:: Sphinx.emit(event, *arguments) Emit *event* and pass *arguments* to the callback functions. Return the @@ -322,22 +353,21 @@ the following public API: .. versionadded:: 0.5 -.. method:: Sphinx.require_sphinx(version) - Compare *version* (which must be a ``major.minor`` version string, - e.g. ``'1.1'``) with the version of the running Sphinx, and abort the build - when it is too old. +Producing messages / logging +---------------------------- - .. versionadded:: 1.0 +The application object also provides support for emitting leveled messages. +.. automethod:: Sphinx.warn -.. exception:: ExtensionError +.. automethod:: Sphinx.info - All these functions raise this exception if something went wrong with the - extension API. +.. automethod:: Sphinx.verbose -Examples of using the Sphinx extension API can be seen in the :mod:`sphinx.ext` -package. +.. automethod:: Sphinx.debug + +.. automethod:: Sphinx.debug2 .. _events: @@ -481,28 +511,27 @@ Use this to adapt your extension to API changes in Sphinx. Before version 1.2, check the string ``sphinx.__version__``. -.. _template-bridge: +The Config object +----------------- -The template bridge -------------------- - -.. currentmodule:: sphinx.application +.. module:: sphinx.config -.. autoclass:: TemplateBridge - :members: +.. class:: Config + The config object makes the values of all config values available as + attributes. -.. _domain-api: + It is available as the ``config`` attribute on the application and + environment objects. For example, to get the value of :confval:`language`, + use either ``app.config.language`` or ``env.config.language``. -Domain API ----------- -.. module:: sphinx.domains +.. _template-bridge: -.. autoclass:: Domain - :members: +The template bridge +------------------- -.. autoclass:: ObjType +.. currentmodule:: sphinx.application -.. autoclass:: Index +.. autoclass:: TemplateBridge :members: diff --git a/doc/ext/builderapi.rst b/doc/extdev/builderapi.rst index 3ace2687..cd8688a3 100644 --- a/doc/ext/builderapi.rst +++ b/doc/extdev/builderapi.rst @@ -1,7 +1,7 @@ .. _writing-builders: -Writing new builders -==================== +Builder API +=========== .. todo:: Expand this. diff --git a/doc/extdev/domainapi.rst b/doc/extdev/domainapi.rst new file mode 100644 index 00000000..d6ecf063 --- /dev/null +++ b/doc/extdev/domainapi.rst @@ -0,0 +1,14 @@ +.. _domain-api: + +Domain API +---------- + +.. module:: sphinx.domains + +.. autoclass:: Domain + :members: + +.. autoclass:: ObjType + +.. autoclass:: Index + :members: diff --git a/doc/extdev/envapi.rst b/doc/extdev/envapi.rst new file mode 100644 index 00000000..56771f73 --- /dev/null +++ b/doc/extdev/envapi.rst @@ -0,0 +1,54 @@ +Build environment API +===================== + +.. module:: sphinx.environment + +.. class:: BuildEnvironment + + **Attributes** + + .. attribute:: app + + Reference to the application object. + + .. attribute:: config + + Reference to the :class:`.Config` object. + + .. attribute:: srcdir + + Source directory (the directory containing ``conf.py``). + + .. attribute:: doctreedir + + Directory for storing pickled doctrees. + + .. attribute:: found_docs + + A set of all existing docnames. + + .. attribute:: metadata + + Dictionary mapping docnames to "metadata" (see :ref:`metadata`). + + .. attribute:: titles + + Dictionary mapping docnames to the docutils node for their main title. + + .. autoattribute:: docname + + **Utility methods** + + .. automethod:: warn + + .. automethod:: warn_node + + .. automethod:: doc2path + + .. automethod:: relfn2path + + .. automethod:: note_dependency + + .. automethod:: new_serialno + + .. automethod:: note_reread diff --git a/doc/extdev/index.rst b/doc/extdev/index.rst new file mode 100644 index 00000000..b76928c0 --- /dev/null +++ b/doc/extdev/index.rst @@ -0,0 +1,33 @@ +.. _dev-extensions: + +Developing extensions for Sphinx +================================ + +Since many projects will need special features in their documentation, Sphinx is +designed to be extensible on several levels. + +This is what you can do in an extension: 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. + +An extension is simply a Python module. When an extension is loaded, Sphinx +imports this module and executes its ``setup()`` function, which in turn +notifies Sphinx of everything the extension offers -- see the extension tutorial +for examples. + +The configuration file itself can be treated as an extension if it contains a +``setup()`` function. All other extensions to load must be listed in the +:confval:`extensions` configuration value. + +.. toctree:: + + tutorial + appapi + envapi + builderapi + markupapi + domainapi + nodes diff --git a/doc/extdev/markupapi.rst b/doc/extdev/markupapi.rst new file mode 100644 index 00000000..8f6c29b1 --- /dev/null +++ b/doc/extdev/markupapi.rst @@ -0,0 +1,11 @@ +Docutils markup API +=================== + +Roles +----- + + +Directives +---------- + +TODO. diff --git a/doc/extdev/nodes.rst b/doc/extdev/nodes.rst new file mode 100644 index 00000000..e67fa3da --- /dev/null +++ b/doc/extdev/nodes.rst @@ -0,0 +1,57 @@ +.. _nodes: + +Doctree node classes added by Sphinx +==================================== + +.. module:: sphinx.addnodes + +Nodes for domain-specific object descriptions +--------------------------------------------- + +.. autoclass:: desc +.. autoclass:: desc_signature +.. autoclass:: desc_addname +.. autoclass:: desc_type +.. autoclass:: desc_returns +.. autoclass:: desc_name +.. autoclass:: desc_parameterlist +.. autoclass:: desc_parameter +.. autoclass:: desc_optional +.. autoclass:: desc_annotation +.. autoclass:: desc_content + +New admonition-like constructs +------------------------------ + +.. autoclass:: versionmodified +.. autoclass:: seealso + +Other paragraph-level nodes +------------------------------- + +.. autoclass:: compact_paragraph + +New inline nodes +---------------- + +.. autoclass:: index +.. autoclass:: pending_xref +.. autoclass:: literal_emphasis +.. autoclass:: abbreviation +.. autoclass:: download_reference + +Special nodes +------------- + +.. autoclass:: only +.. autoclass:: meta +.. autoclass:: highlightlang + +You should not need to generate the nodes below in extensions. + +.. autoclass:: glossary +.. autoclass:: toctree +.. autoclass:: start_of_file +.. autoclass:: productionlist +.. autoclass:: production +.. autoclass:: termsep diff --git a/doc/ext/tutorial.rst b/doc/extdev/tutorial.rst index c09be29a..38264190 100644 --- a/doc/ext/tutorial.rst +++ b/doc/extdev/tutorial.rst @@ -12,6 +12,50 @@ include todo entries in the documentation, and collecting these in a central place. (A similar "todo" extension is distributed with Sphinx.) +Important objects +----------------- + +There are several key objects whose API you will use while writing an +extension. These are: + +**Application** + The application object (usually called ``app``) is an instance of + :class:`.Sphinx`. It controls the most high-level functionality, such as the + setup of extensions, event dispatching and producing output (logging). + + If you have the environment object, the application is available as + ``env.app``. + +**Environment** + The build environment object (usually called ``env``) is an instance of + :class:`.BuildEnvironment`. It is responsible for parsing the source + documents stores all metadata about the document collection and is serialized + after each build. + + Its API provides methods to do with access to metadata, resolving references, + etc. It can also be used by extensions to cache information that should + persist for incremental rebuilds. + + If you have the application or builder object, the environment is available + as ``app.env`` or ``builder.env``. + +**Builder** + The builder object (usually called ``builder``) is an instance of a specific + subclass of :class:`.Builder`. Each builder class knows how to convert the + parsed documents into an output format, or otherwise process them (e.g. check + external links). + + If you have the application object, the environment is available as + ``app.builder``. + +**Config** + The config object (usually called ``config``) provides the values of + configuration values set in :file:`conf.py` as attributes. It is an instance + of :class:`.Config`. + + The config is available as ``app.config`` or ``env.config``. + + Build Phases ------------ @@ -29,11 +73,15 @@ in which a Sphinx project is built: this works in several phases. In Phase 1, all source files (and on subsequent builds, those that are new or changed) are read and parsed. This is the phase where directives and roles - are encountered by the docutils, and the corresponding functions are called. - The output of this phase is a *doctree* for each source files, that is a tree - of docutils nodes. For document elements that aren't fully known until all + are encountered by the docutils, and the corresponding code is executed. The + output of this phase is a *doctree* for each source files, that is a tree of + docutils nodes. For document elements that aren't fully known until all existing files are read, temporary nodes are created. + There are nodes provided by docutils, which are documented `in the docutils + documentation <http://docutils.sourceforge.net/docs/ref/doctree.html>`__. + Additional nodes are provided by Sphinx and :ref:`documented here <nodes>`. + During reading, the build environment is updated with all meta- and cross reference data of the read documents, such as labels, the names of headings, described Python objects and index entries. This will later be used to @@ -165,21 +213,26 @@ docutils classes defined in :mod:`docutils.nodes`. ``todo`` inherits from ``Admonition`` because it should be handled like a note or warning, ``todolist`` is just a "general" node. +.. note:: + + Many extensions will not have to create their own node classes and work fine + with the nodes already provided by `docutils + <http://docutils.sourceforge.net/docs/ref/doctree.html>`__ and :ref:`Sphinx + <nodes>`. + The Directive Classes --------------------- A directive class is a class deriving usually from -``docutils.parsers.rst.Directive``. Since the class-based directive interface -doesn't exist yet in Docutils 0.4, Sphinx has another base class called -``sphinx.util.compat.Directive`` that you can derive your directive from, and it -will work with both Docutils 0.4 and 0.5 upwards. The directive interface is -covered in detail in the `docutils documentation`_; the important thing is that the -class has a method ``run`` that returns a list of nodes. +``docutils.parsers.rst.Directive``. The directive interface is covered in +detail in the `docutils documentation`_; the important thing is that the class +has attributes that configure the allowed markup and a method ``run`` that +returns a list of nodes. The ``todolist`` directive is quite simple:: - from sphinx.util.compat import Directive + from docutils.parsers.rst import Directive class TodolistDirective(Directive): @@ -224,9 +277,9 @@ to the build environment instance using ``self.state.document.settings.env``. Then, to act as a link target (from the todolist), the todo directive needs to return a target node in addition to the todo node. The target ID (in HTML, this -will be the anchor name) is generated by using ``env.new_serialno`` which is -returns a new integer directive on each call and therefore leads to unique -target names. The target node is instantiated without any text (the first two +will be the anchor name) is generated by using ``env.new_serialno`` which +returns a new unique integer on each call and therefore leads to unique target +names. The target node is instantiated without any text (the first two arguments). An admonition is created using a standard docutils function (wrapped in Sphinx diff --git a/doc/extensions.rst b/doc/extensions.rst index 7597f281..b0d98e38 100644 --- a/doc/extensions.rst +++ b/doc/extensions.rst @@ -3,34 +3,12 @@ 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. - -This is what you can do in an extension: 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. - -An extension is simply a Python module. When an extension is loaded, Sphinx -imports this module and executes its ``setup()`` function, which in turn -notifies Sphinx of everything the extension offers -- see the extension tutorial -for examples. - -The configuration file itself can be treated as an extension if it contains a -``setup()`` function. All other extensions to load must be listed in the -:confval:`extensions` configuration value. - -.. toctree:: - - ext/tutorial - ext/appapi - ext/builderapi +Since many projects will need special features in their documentation, Sphinx +allows to add "extensions" to the build process, each of which can modify almost +any aspect of document processing. +This chapter describes the extensions bundled with Sphinx. For the API +documentation on writing your own extension, see :ref:`dev-extensions`. Builtin Sphinx extensions ------------------------- @@ -53,6 +31,7 @@ These extensions are built in and can be activated by respective entries in the ext/extlinks ext/viewcode ext/linkcode + ext/napoleon Third-party extensions diff --git a/doc/install.rst b/doc/install.rst index bf653872..71e37e9c 100644 --- a/doc/install.rst +++ b/doc/install.rst @@ -4,7 +4,7 @@ Installing Sphinx ================= Since Sphinx is written in the Python language, you need to install Python -(the required version is at least 2.5) and Sphinx. +(the required version is at least 2.6) and Sphinx. Sphinx packages are available on the `Python Package Index <https://pypi.python.org/pypi/Sphinx>`_. @@ -79,8 +79,8 @@ sidebar and under "Quick Links", click "Windows Installer" to download. .. note:: - Currently, Python offers two major versions, 2.x and 3.x. Sphinx 1.2 can run - under Python 2.5 to 2.7 and 3.1 to 3.3, with the recommended version being + Currently, Python offers two major versions, 2.x and 3.x. Sphinx 1.3 can run + under Python 2.6, 2.7, 3.2, 3.3, with the recommended version being 2.7. This chapter assumes you have installed Python 2.7. Follow the Windows installer for Python. diff --git a/doc/intro.rst b/doc/intro.rst index 66d0c58d..dd541bf1 100644 --- a/doc/intro.rst +++ b/doc/intro.rst @@ -54,7 +54,7 @@ See the :ref:`pertinent section in the FAQ list <usingwith>`. Prerequisites ------------- -Sphinx needs at least **Python 2.5** or **Python 3.1** to run, as well as the +Sphinx needs at least **Python 2.6** or **Python 3.2** to run, as well as the docutils_ and Jinja2_ libraries. Sphinx should work with docutils version 0.7 or some (not broken) SVN trunk snapshot. If you like to have source code highlighting support, you must also install the Pygments_ library. diff --git a/doc/invocation.rst b/doc/invocation.rst index f831dc0a..dca02793 100644 --- a/doc/invocation.rst +++ b/doc/invocation.rst @@ -159,8 +159,8 @@ The :program:`sphinx-build` script has several options: .. option:: -v - Increase verbosity. This option can be given up to three times to get more - debug output. It implies :option:`-T`. + Increase verbosity (loglevel). This option can be given up to three times + to get more debug logging output. It implies :option:`-T`. .. versionadded:: 1.2 diff --git a/doc/markup/code.rst b/doc/markup/code.rst index 6e707e00..e9f8f1da 100644 --- a/doc/markup/code.rst +++ b/doc/markup/code.rst @@ -188,6 +188,25 @@ Includes The ``prepend`` and ``append`` options, as well as ``tab-width``. +Showing a file name +^^^^^^^^^^^^^^^^^^^ + +.. versionadded:: 1.3 + +A ``filename`` option can be given to show that name before the code block. For +example:: + + .. code-block:: python + :filename: this.py + + print 'Explicit is better than implicit.' + + +:rst:dir:`literalinclude` also supports the ``filename`` option, with the +additional feature that if you leave the value empty, the shown filename will be +exactly the one given as an argument. + + .. rubric:: Footnotes .. [1] There is a standard ``.. include`` directive, but it raises errors if the diff --git a/doc/markup/toctree.rst b/doc/markup/toctree.rst index fdecc37d..1d5d667a 100644 --- a/doc/markup/toctree.rst +++ b/doc/markup/toctree.rst @@ -141,9 +141,12 @@ tables of contents. The ``toctree`` directive is the central element. In the end, all documents in the :term:`source directory` (or subdirectories) must occur in some ``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. Use :ref:`metadata` to remove the - warning, and :confval:`exclude_patterns` to explicitly exclude documents or - directories from building. + be reachable through standard navigation. + + Use :confval:`exclude_patterns` to explicitly exclude documents or + directories from building completely. Use :ref:`the "orphan" metadata + <metadata>` to let a document be built, but notify Sphinx that it is not + reachable via a toctree. The "master document" (selected by :confval:`master_doc`) is the "root" of the TOC tree hierarchy. It can be used as the documentation's main page, or |
