diff --git a/CHANGES b/CHANGES index e7e191f15..3f92b3398 100644 --- a/CHANGES +++ b/CHANGES @@ -33,6 +33,7 @@ Deprecated * ``sphinx.locale.l_()`` is deprecated * #2157: helper function ``warn()`` for HTML themes is deprecated * ``env._nitpick_ignore`` is deprecated +* ``app.override_domain()`` is deprecated * ``Config.__init__()`` has changed; the *dirname*, *filename* and *tags* argument has been deprecated * ``Config.check_types()`` is deprecated @@ -56,6 +57,10 @@ Features added * helper function ``warning()`` for HTML themes is added * Add ``Domain.enumerable_nodes`` to manage own enumerable nodes for domains (experimental) +* Add a new keyword argument ``override`` to Application APIs +* LaTeX: new key ``'fvset'`` for :confval:`latex_elements`. For + XeLaTeX/LuaLaTeX its default sets ``fanvyvrb`` to use normal, not small, + fontsize in code-blocks (refs: #4793) * Add ``Config.from_conf_py()`` classmethod to create a new config object from configuration file diff --git a/doc/conf.py b/doc/conf.py index 3c8b9eae1..f5708465d 100644 --- a/doc/conf.py +++ b/doc/conf.py @@ -58,6 +58,7 @@ latex_logo = '_static/sphinx.png' latex_elements = { 'fontpkg': '\\usepackage{palatino}', 'passoptionstopackages': '\\PassOptionsToPackage{svgnames}{xcolor}', + 'preamble': '\\DeclareUnicodeCharacter{229E}{\\ensuremath{\\boxplus}}', # fix missing index entry due to RTD doing only once pdflatex after makeindex 'printindex': r''' \IfFileExists{\jobname.ind} diff --git a/doc/config.rst b/doc/config.rst index 7bcae99f5..79d9554b0 100644 --- a/doc/config.rst +++ b/doc/config.rst @@ -216,12 +216,12 @@ General configuration .. index:: default; domain primary; domain - The name of the default :ref:`domain `. Can also be ``None`` to - disable a default domain. The default is ``'py'``. Those objects in other - domains (whether the domain name is given explicitly, or selected by a - :rst:dir:`default-domain` directive) will have the domain name explicitly - prepended when named (e.g., when the default domain is C, Python functions - will be named "Python function", not just "function"). + The name of the default :doc:`domain `. + Can also be ``None`` to disable a default domain. The default is ``'py'``. + Those objects in other domains (whether the domain name is given explicitly, + or selected by a :rst:dir:`default-domain` directive) will have the domain + name explicitly prepended when named (e.g., when the default domain is C, + Python functions will be named "Python function", not just "function"). .. versionadded:: 1.0 @@ -1998,7 +1998,16 @@ These options influence LaTeX output. See further :doc:`latex`. differently or append some content after the index. For example ``'\\footnotesize\\raggedright\\printindex'`` is advisable when the index is full of long entries. + ``'fvset'`` + Customization of ``fancyvrb`` LaTeX package. Defaults to + ``'\\fvset{fontsize=\\small}'``, because default font (Courier) used in + code-blocks is wider and taller than default text font (Times). + For ``'xelatex'`` and ``'lualatex'``, defaults to + ``'\\fvset{fontsize=auto}'``, because the default fonts are part of + one unified typeface family (Latin Modern OpenType). + + .. versionadded:: 1.8 * Keys that are set by other options and therefore should not be overridden are: diff --git a/doc/contents.rst b/doc/contents.rst index 886861fba..3af0aa58c 100644 --- a/doc/contents.rst +++ b/doc/contents.rst @@ -9,12 +9,10 @@ Sphinx documentation contents usage/installation usage/quickstart + usage/restructuredtext/index intro man/index - rest - markup/index - domains builders config intl diff --git a/doc/extdev/index.rst b/doc/extdev/index.rst index 7ca0c6f2e..7ca085c44 100644 --- a/doc/extdev/index.rst +++ b/doc/extdev/index.rst @@ -129,6 +129,11 @@ The following is a list of deprecated interface. - 3.0 - ``Config.from_conf_py()`` + * - ``sphinx.application.Sphinx.override_domain()`` + - 1.8 + - 3.0 + - :meth:`~sphinx.application.Sphinx.add_domain()` + * - ``BuildEnvironment._nitpick_ignore`` - 1.8 - 3.0 diff --git a/doc/glossary.rst b/doc/glossary.rst index acac3a590..167edb8d4 100644 --- a/doc/glossary.rst +++ b/doc/glossary.rst @@ -32,7 +32,7 @@ Glossary Content of the directive. - See :ref:`directives` for more information. + See :ref:`rst-directives` for more information. document name Since reST source files can have different extensions (some people like @@ -56,8 +56,9 @@ Glossary Having domains means that there are no naming problems when one set of documentation wants to refer to e.g. C++ and Python classes. It also means that extensions that support the documentation of whole new - languages are much easier to write. For more information about domains, - see the chapter :ref:`domains`. + languages are much easier to write. + + For more information, refer to :doc:`/usage/restructuredtext/domains`. environment A structure where information about all documents under the root is saved, @@ -81,7 +82,7 @@ Glossary role A reStructuredText markup element that allows marking a piece of text. Like directives, roles are extensible. The basic syntax looks like this: - ``:rolename:`content```. See :ref:`inlinemarkup` for details. + ``:rolename:`content```. See :ref:`rst-inline-markup` for details. source directory The directory which, including its subdirectories, contains all source diff --git a/doc/latex.rst b/doc/latex.rst index 87117c164..f8e275020 100644 --- a/doc/latex.rst +++ b/doc/latex.rst @@ -385,13 +385,6 @@ Macros multiple paragraphs in header cells of tables. .. versionadded:: 1.6.3 ``\sphinxstylecodecontinued`` and ``\sphinxstylecodecontinues``. -- by default the Sphinx style file ``sphinx.sty`` executes the command - ``\fvset{fontsize=\small}`` as part of its configuration of - ``fancyvrb.sty``. This may be overriden for example via - ``\fvset{fontsize=auto}`` which will let code listings use the ambient font - size. Refer to ``fancyvrb.sty``'s documentation for further keys. - - .. versionadded:: 1.5 - the table of contents is typeset via ``\sphinxtableofcontents`` which is a wrapper (whose definition can be found in :file:`sphinxhowto.cls` or in :file:`sphinxmanual.cls`) of standard ``\tableofcontents``. diff --git a/doc/markup/code.rst b/doc/markup/code.rst deleted file mode 100644 index 19ec0cc4c..000000000 --- a/doc/markup/code.rst +++ /dev/null @@ -1,270 +0,0 @@ -.. highlight:: rest - -.. _code-examples: - -Showing code examples ---------------------- - -.. index:: pair: code; examples - single: sourcecode - -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 done with `Pygments `_ and 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, - but the doc-wide default can be set with the :confval:`highlight_language` - config value. - -* Within Python highlighting mode, interactive sessions are recognized - automatically and highlighted appropriately. Normal Python code is only - highlighted if it is parseable (so you can use Python as the default, but - interspersed snippets of shell commands or other code blocks will not be - highlighted as Python). - -* The highlighting language can be changed using the ``highlight`` directive, - used as follows: - - .. rst:directive:: .. highlight:: language - - Example:: - - .. highlight:: c - - This language is used until the next ``highlight`` directive is encountered. - -* For documents that have to show snippets in different languages, there's also - a :rst:dir:`code-block` directive that is given the highlighting language - directly: - - .. rst:directive:: .. code-block:: language - - Use it like this:: - - .. code-block:: ruby - - Some Ruby code. - - The directive's alias name :rst:dir:`sourcecode` works as well. - -* The valid values for the highlighting language are: - - * ``none`` (no highlighting) - * ``python`` (the default when :confval:`highlight_language` isn't set) - * ``guess`` (let Pygments guess the lexer based on contents, only works with - certain well-recognizable languages) - * ``rest`` - * ``c`` - * ... and any other `lexer alias that Pygments supports - `_. - -* If highlighting with the selected language fails (i.e. Pygments emits an - "Error" token), the block is not highlighted in any way. - -Line numbers -^^^^^^^^^^^^ - -Pygments can generate line numbers for code blocks. For -automatically-highlighted blocks (those started by ``::``), line numbers must be -switched on in a :rst:dir:`highlight` directive, with the ``linenothreshold`` -option:: - - .. highlight:: python - :linenothreshold: 5 - -This will produce line numbers for all code blocks longer than five lines. - -For :rst:dir:`code-block` blocks, a ``linenos`` flag option can be given to -switch on line numbers for the individual block:: - - .. code-block:: ruby - :linenos: - - Some more Ruby code. - -The first line number can be selected with the ``lineno-start`` option. If -present, ``linenos`` flag is automatically activated:: - - .. code-block:: ruby - :lineno-start: 10 - - Some more Ruby code, with line numbering starting at 10. - -Additionally, an ``emphasize-lines`` option can be given to have Pygments -emphasize particular lines:: - - .. code-block:: python - :emphasize-lines: 3,5 - - def some_function(): - interesting = False - print 'This line is highlighted.' - print 'This one is not...' - print '...but this one is.' - -.. versionchanged:: 1.1 - ``emphasize-lines`` has been added. - -.. versionchanged:: 1.3 - ``lineno-start`` has been added. - -.. versionchanged:: 1.6.6 - LaTeX supports the ``emphasize-lines`` option. - -Includes -^^^^^^^^ - -.. rst:directive:: .. literalinclude:: filename - - 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 usually relative to the current file's path. However, if it - is absolute (starting with ``/``), it is relative to the top source - directory. - - Tabs in the input are expanded if you give a ``tab-width`` option with the - desired tab width. - - Like :rst:dir:`code-block`, the directive supports the ``linenos`` flag - option to switch on line numbers, the ``lineno-start`` option to select the - first line number, the ``emphasize-lines`` option to emphasize particular - lines, and a ``language`` option to select a language different from the - current file's standard language. Example with options:: - - .. literalinclude:: example.rb - :language: ruby - :emphasize-lines: 12,15-18 - :linenos: - - Include files are assumed to be encoded in the :confval:`source_encoding`. - If the file has a different encoding, you can specify it with the - ``encoding`` option:: - - .. literalinclude:: example.py - :encoding: latin-1 - - The directive also supports including only parts of the file. If it is a - Python module, you can select a class, function or method to include using - the ``pyobject`` option:: - - .. literalinclude:: example.py - :pyobject: Timer.start - - This would only include the code lines belonging to the ``start()`` method in - the ``Timer`` class within the file. - - Alternately, you can specify exactly which lines to include by giving a - ``lines`` option:: - - .. literalinclude:: example.py - :lines: 1,3,5-10,20- - - This includes the lines 1, 3, 5 to 10 and lines 20 to the last line. - - Another way to control which part of the file is included is to use the - ``start-after`` and ``end-before`` options (or only one of them). If - ``start-after`` is given as a string option, only lines that follow the first - line containing that string are included. If ``end-before`` is given as a - string option, only lines that precede the first lines containing that string - are included. - - With lines selected using ``start-after`` it is still possible to use - ``lines``, the first allowed line having by convention the line number ``1``. - - When lines have been selected in any of the ways described above, the - line numbers in ``emphasize-lines`` refer to those selected lines, counted - consecutively starting at ``1``. - - When specifying particular parts of a file to display, it can be useful to - display the original line numbers. This can be done using the - ``lineno-match`` option, which is however allowed only when the selection - consists of contiguous lines. - - You can prepend and/or append a line to the included code, using the - ``prepend`` and ``append`` option, respectively. This is useful e.g. for - highlighting PHP code that doesn't include the ```` markers. - - - If you want to show the diff of the code, you can specify the old - file by giving a ``diff`` option:: - - .. literalinclude:: example.py - :diff: example.py.orig - - This shows the diff between example.py and example.py.orig with unified diff - format. - - .. versionadded:: 0.4.3 - The ``encoding`` option. - .. versionadded:: 0.6 - The ``pyobject``, ``lines``, ``start-after`` and ``end-before`` options, - as well as support for absolute filenames. - .. versionadded:: 1.0 - The ``prepend`` and ``append`` options, as well as ``tab-width``. - .. versionadded:: 1.3 - The ``diff`` option. - The ``lineno-match`` option. - .. versionchanged:: 1.6 - With both ``start-after`` and ``lines`` in use, the first line as per - ``start-after`` is considered to be with line number ``1`` for ``lines``. - -Caption and name -^^^^^^^^^^^^^^^^ - -.. versionadded:: 1.3 - -A ``caption`` option can be given to show that name before the code block. -A ``name`` option can be provided implicit target name that can be referenced -by using :rst:role:`ref`. -For example:: - - .. code-block:: python - :caption: this.py - :name: this-py - - print 'Explicit is better than implicit.' - - -:rst:dir:`literalinclude` also supports the ``caption`` and ``name`` option. -``caption`` has an additional feature that if you leave the value empty, the shown -filename will be exactly the one given as an argument. - - -Dedent -^^^^^^ - -.. versionadded:: 1.3 - -A ``dedent`` option can be given to strip indentation characters from the code -block. For example:: - - .. literalinclude:: example.rb - :language: ruby - :dedent: 4 - :lines: 10-15 - -:rst:dir:`code-block` also supports the ``dedent`` option. - - -.. 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. diff --git a/doc/markup/index.rst b/doc/markup/index.rst deleted file mode 100644 index ca70b9581..000000000 --- a/doc/markup/index.rst +++ /dev/null @@ -1,19 +0,0 @@ -.. _sphinxmarkup: - -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. - -.. toctree:: - - toctree - para - code - inline - misc - -More markup is added by :ref:`domains`. - -.. _standard reST markup: http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html diff --git a/doc/markup/misc.rst b/doc/markup/misc.rst deleted file mode 100644 index 51e3a405c..000000000 --- a/doc/markup/misc.rst +++ /dev/null @@ -1,344 +0,0 @@ -.. highlight:: rest - -Miscellaneous markup -==================== - -.. _metadata: - -File-wide metadata ------------------- - -reST has the concept of "field lists"; these are a sequence of fields marked up -like this:: - - :fieldname: Field content - -A field list near the top of a file is parsed by docutils as the "docinfo" -which is normally used to record the author, date of publication and other -metadata. *In Sphinx*, a field list preceding any other markup is moved from -the docinfo to the Sphinx environment as document metadata and is not displayed -in the output; a field list appearing after the document title will be part of -the docinfo as normal and will be displayed in the output. - -At the moment, these metadata fields are recognized: - -``tocdepth`` - The maximum depth for a table of contents of this file. - - .. versionadded:: 0.4 - -``nocomments`` - If set, the web application won't display a comment form for a page generated - from this source file. - -``orphan`` - If set, warnings about this file not being included in any toctree will be - suppressed. - - .. versionadded:: 1.0 - - -Meta-information markup ------------------------ - -.. rst:directive:: .. sectionauthor:: name - - 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 - - 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. - - -.. rst:directive:: .. codeauthor:: name - - The :rst:dir:`codeauthor` directive, which can appear multiple times, names - the authors of the described code, just like :rst:dir:`sectionauthor` names - the author(s) of a piece of documentation. It too only produces output if - the :confval:`show_authors` configuration value is ``True``. - - -Index-generating markup ------------------------ - -Sphinx automatically creates index entries from all object descriptions (like -functions, classes or attributes) like discussed in :ref:`domains`. - -However, there is also explicit markup 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. - -.. rst:directive:: .. index:: - - This directive 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 - - The execution context - --------------------- - - ... - - 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). - - Since index directives generate cross-reference targets at their location in - the source, it makes sense to put them *before* the thing they refer to -- - e.g. a heading, as in the example above. - - 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``. - see - ``see: entry; other`` creates an index entry that refers from ``entry`` to - ``other``. - seealso - Like ``see``, but inserts "see also" instead of "see". - 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``. (These - are Python-specific and therefore deprecated.) - - You can mark up "main" index entries by prefixing them with an exclamation - mark. The references to "main" entries are emphasized in the generated - index. For example, if two pages contain :: - - .. index:: Python - - and one page contains :: - - .. index:: ! Python - - then the backlink to the latter page is emphasized among the three backlinks. - - For index directives containing only "single" entries, there is a shorthand - notation:: - - .. index:: BNF, grammar, syntax, notation - - This creates four index entries. - - .. versionchanged:: 1.1 - Added ``see`` and ``seealso`` types, as well as marking main entries. - -.. rst:role:: index - - While the :rst:dir:`index` directive is a block-level markup and links to the - beginning of the next paragraph, there is also a corresponding role that sets - the link target directly where it is used. - - The content of the role can be a simple phrase, which is then kept in the - text and used as an index entry. It can also be a combination of text and - index entry, styled like with explicit targets of cross-references. In that - case, the "target" part can be a full entry as described for the directive - above. For example:: - - This is a normal reST :index:`paragraph` that contains several - :index:`index entries `. - - .. versionadded:: 1.1 - - -.. _tags: - -Including content based on tags -------------------------------- - -.. rst:directive:: .. only:: - - Include the content of the directive only if the *expression* is true. The - expression should consist of tags, like this:: - - .. only:: html and draft - - Undefined tags are false, defined tags (via the ``-t`` command-line option or - within :file:`conf.py`, see :ref:`here `) are true. Boolean - expressions, also using parentheses (like ``html and (latex or draft)``) are - supported. - - The *format* and the *name* of the current builder (``html``, ``latex`` or - ``text``) are always set as a tag [#]_. To make the distinction between - format and name explicit, they are also added with the prefix ``format_`` and - ``builder_``, e.g. the epub builder defines the tags ``html``, ``epub``, - ``format_html`` and ``builder_epub``. - - These standard tags are set *after* the configuration file is read, so they - are not available there. - - All tags must follow the standard Python identifier syntax as set out in - the `Identifiers and keywords - `_ - documentation. That is, a tag expression may only consist of tags that - conform to the syntax of Python variables. In ASCII, this consists of the - uppercase and lowercase letters ``A`` through ``Z``, the underscore ``_`` - and, except for the first character, the digits ``0`` through ``9``. - - .. versionadded:: 0.6 - .. versionchanged:: 1.2 - Added the name of the builder and the prefixes. - - .. warning:: - - This directive is designed to control only content of document. It could - not control sections, labels and so on. - - -Tables ------- - -Use :ref:`reStructuredText tables `, i.e. either - -- grid table syntax (:duref:`ref `), -- simple table syntax (:duref:`ref `), -- :dudir:`csv-table` syntax, -- or :dudir:`list-table` syntax. - -The :dudir:`table` directive serves as optional wrapper of the *grid* and -*simple* syntaxes. - -They work fine in -HTML output, however there are some gotchas when using tables in LaTeX: the -column width is hard to determine correctly automatically. For this reason, the -following directive exists: - -.. rst:directive:: .. tabularcolumns:: column spec - - This directive gives a "column spec" for the next table occurring in the - source file. The spec is the second argument to the LaTeX ``tabulary`` - package's environment (which Sphinx uses to translate tables). It can have - values like :: - - |l|l|l| - - which means three left-adjusted, nonbreaking columns. For columns with - longer text that should automatically be broken, use either the standard - ``p{width}`` construct, or tabulary's automatic specifiers: - - +-----+------------------------------------------+ - |``L``| flush left column with automatic width | - +-----+------------------------------------------+ - |``R``| flush right column with automatic width | - +-----+------------------------------------------+ - |``C``| centered column with automatic width | - +-----+------------------------------------------+ - |``J``| justified column with automatic width | - +-----+------------------------------------------+ - - The automatic widths of the ``LRCJ`` columns are attributed by ``tabulary`` - in proportion to the observed shares in a first pass where the table cells - are rendered at their natural "horizontal" widths. - - By default, Sphinx uses a table layout with ``J`` for every column. - - .. versionadded:: 0.3 - - .. versionchanged:: 1.6 - Merged cells may now contain multiple paragraphs and are much better - handled, thanks to custom Sphinx LaTeX macros. This novel situation - motivated the switch to ``J`` specifier and not ``L`` by default. - - .. hint:: - - Sphinx actually uses ``T`` specifier having done ``\newcolumntype{T}{J}``. - To revert to previous default, insert ``\newcolumntype{T}{L}`` in the - LaTeX preamble (see :confval:`latex_elements`). - - A frequent issue with tabulary is that columns with little contents are - "squeezed". The minimal column width is a tabulary parameter called - ``\tymin``. You may set it globally in the LaTeX preamble via - ``\setlength{\tymin}{40pt}`` for example. - - Else, use the :rst:dir:`tabularcolumns` directive with an explicit - ``p{40pt}`` (for example) for that column. You may use also ``l`` - specifier but this makes the task of setting column widths more difficult - if some merged cell intersects that column. - - .. warning:: - - Tables with more than 30 rows are rendered using ``longtable``, not - ``tabulary``, in order to allow pagebreaks. The ``L``, ``R``, ... specifiers - do not work for these tables. - - Tables that contain list-like elements such as object descriptions, - blockquotes or any kind of lists cannot be set out of the box with - ``tabulary``. They are therefore set with the standard LaTeX ``tabular`` (or - ``longtable``) environment if you don't give a ``tabularcolumns`` directive. - If you do, the table will be set with ``tabulary`` but you must use the - ``p{width}`` construct (or Sphinx's ``\X`` and ``\Y`` specifiers described - below) for the columns containing these elements. - - Literal blocks do not work with ``tabulary`` at all, so tables containing - a literal block are always set with ``tabular``. The verbatim environment - used for literal blocks only works in ``p{width}`` (and ``\X`` or ``\Y``) - columns, hence Sphinx generates such column specs for tables containing - literal blocks. - - Since Sphinx 1.5, the ``\X{a}{b}`` specifier is used (there *is* a backslash - in the specifier letter). It is like ``p{width}`` with the width set to a - fraction ``a/b`` of the current line width. You can use it in the - :rst:dir:`tabularcolumns` (it is not a problem if some LaTeX macro is also - called ``\X``.) - - It is *not* needed for ``b`` to be the total number of columns, nor for the - sum of the fractions of the ``\X`` specifiers to add up to one. For example - ``|\X{2}{5}|\X{1}{5}|\X{1}{5}|`` is legitimate and the table will occupy - 80% of the line width, the first of its three columns having the same width - as the sum of the next two. - - This is used by the ``:widths:`` option of the :dudir:`table` directive. - - Since Sphinx 1.6, there is also the ``\Y{f}`` specifier which admits a - decimal argument, such has ``\Y{0.15}``: this would have the same effect as - ``\X{3}{20}``. - - .. versionchanged:: 1.6 - - Merged cells from complex grid tables (either multi-row, multi-column, or - both) now allow blockquotes, lists, literal blocks, ... as do regular cells. - - Sphinx's merged cells interact well with ``p{width}``, ``\X{a}{b}``, ``Y{f}`` - and tabulary's columns. - - .. note:: - - :rst:dir:`tabularcolumns` conflicts with ``:widths:`` option of table - directives. If both are specified, ``:widths:`` option will be ignored. - -Math ----- - -See :ref:`math-support`. - -.. rubric:: Footnotes - -.. [#] For most builders name and format are the same. At the moment only - builders derived from the html builder distinguish between the builder - format and the builder name. - - Note that the current builder tag is not available in ``conf.py``, it is - only available after the builder is initialized. - diff --git a/doc/markup/para.rst b/doc/markup/para.rst deleted file mode 100644 index ba2cc52f5..000000000 --- a/doc/markup/para.rst +++ /dev/null @@ -1,253 +0,0 @@ -.. highlight:: rest - -Paragraph-level markup ----------------------- - -.. index:: note, warning - pair: changes; in version - -These directives create short paragraphs and can be used inside information -units as well as normal text: - -.. rst: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. - -.. rst: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 :rst:dir:`note` in that it is - recommended over :rst:dir:`note` for information regarding security. - -.. rst:directive:: .. versionadded:: version - - 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. - -.. rst:directive:: .. versionchanged:: version - - Similar to :rst:dir:`versionadded`, but describes when and what changed in - the named feature in some way (new parameters, changed side effects, etc.). - -.. rst:directive:: .. deprecated:: version - - Similar to :rst:dir:`versionchanged`, but describes when the feature was - deprecated. An explanation can also be given, for example to inform the - reader what should be used instead. Example:: - - .. deprecated:: 3.1 - Use :func:`spam` instead. - - --------------- - -.. rst:directive:: seealso - - Many sections include a list of references to module documentation or - external documents. These lists are created using the :rst:dir:`seealso` - directive. - - The :rst:dir:`seealso` directive is typically placed in a section just before - any subsections. For the HTML output, it is shown boxed off from the main - flow of the text. - - The content of the :rst:dir:`seealso` directive should be a reST definition - list. Example:: - - .. seealso:: - - Module :py:mod:`zipfile` - Documentation of the :py:mod:`zipfile` standard module. - - `GNU tar manual, Basic Tar Format `_ - Documentation for tar archive files, including GNU tar extensions. - - There's also a "short form" allowed that looks like this:: - - .. seealso:: modules :py:mod:`zipfile`, :py:mod:`tarfile` - - .. versionadded:: 0.5 - The short form. - -.. rst:directive:: .. rubric:: title - - This directive creates a paragraph heading that is not used to create a - table of contents node. - - .. note:: - - If the *title* of the rubric is "Footnotes" (or the selected language's - equivalent), this rubric is ignored by the LaTeX writer, since it is - assumed to only contain footnote definitions and therefore would create an - empty heading. - - -.. rst:directive:: centered - - This directive creates a centered boldfaced line of text. Use it as - follows:: - - .. centered:: LICENSE AGREEMENT - - .. deprecated:: 1.1 - This presentation-only directive is a legacy from older versions. Use a - :rst:dir:`rst-class` directive instead and add an appropriate style. - - -.. rst:directive:: hlist - - This directive must contain a bullet list. It will transform it into a more - compact list by either distributing more than one item horizontally, or - reducing spacing between items, depending on the builder. - - For builders that support the horizontal distribution, there is a ``columns`` - option that specifies the number of columns; it defaults to 2. Example:: - - .. hlist:: - :columns: 3 - - * A list of - * short items - * that should be - * displayed - * horizontally - - .. versionadded:: 0.6 - - -Table-of-contents markup ------------------------- - -The :rst:dir:`toctree` directive, which generates tables of contents of -subdocuments, is described in :ref:`toctree-directive`. - -For local tables of contents, use the standard reST :dudir:`contents directive -`. - - -.. _glossary-directive: - -Glossary --------- - -.. rst:directive:: .. glossary:: - - This directive must contain a reST definition-list-like markup with terms and - definitions. The definitions will then be referencable with the - :rst:role:`term` role. Example:: - - .. glossary:: - - environment - A structure where information about all documents under the root is - saved, and used for cross-referencing. The environment is pickled - after the parsing stage, so that successive runs only need to read - and parse new and changed documents. - - source directory - The directory which, including its subdirectories, contains all - source files for one Sphinx project. - - In contrast to regular definition lists, *multiple* terms per entry are - allowed, and inline markup is allowed in terms. You can link to all of the - terms. For example:: - - .. glossary:: - - term 1 - term 2 - Definition of both terms. - - (When the glossary is sorted, the first term determines the sort order.) - - If you want to specify "grouping key" for general index entries, you can put a "key" - as "term : key". For example:: - - .. glossary:: - - term 1 : A - term 2 : B - Definition of both terms. - - Note that "key" is used for grouping key as is. - The "key" isn't normalized; key "A" and "a" become different groups. - The whole characters in "key" is used instead of a first character; it is used for - "Combining Character Sequence" and "Surrogate Pairs" grouping key. - - In i18n situation, you can specify "localized term : key" even if original text only - have "term" part. In this case, translated "localized term" will be categorized in - "key" group. - - .. versionadded:: 0.6 - You can now give the glossary directive a ``:sorted:`` flag that will - automatically sort the entries alphabetically. - - .. versionchanged:: 1.1 - Now supports multiple terms and inline markup in terms. - - .. versionchanged:: 1.4 - Index key for glossary term should be considered *experimental*. - -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: - -.. rst:directive:: .. productionlist:: [name] - - 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. - - The argument to :rst:dir:`productionlist` serves to distinguish different - sets of production lists that belong to different grammars. - - 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. Outside of the production list, you can - reference to token productions using :rst:role:`token`. - - Note that no further reST parsing is done in the production, so that you - don't have to escape ``*`` or ``|`` characters. - -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` diff --git a/doc/markup/toctree.rst b/doc/markup/toctree.rst deleted file mode 100644 index 78a72c1b4..000000000 --- a/doc/markup/toctree.rst +++ /dev/null @@ -1,242 +0,0 @@ -.. highlight:: rst -.. _toctree-directive: - -The TOC tree -============ - -.. index:: pair: table of; contents - -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. - -.. note:: - - Simple "inclusion" of one file in another can be done with the - :dudir:`include` directive. - -.. rst:directive:: toctree - - This directive inserts a "TOC tree" at the current location, using the - individual TOCs (including "sub-TOC trees") of the documents given in the - directive body. Relative document names (not beginning with a slash) are - relative to the document the directive occurs in, absolute names are relative - to the source directory. 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 Python docs' library reference index):: - - .. toctree:: - :maxdepth: 2 - - intro - strings - datatypes - numeric - (many more documents listed here) - - This accomplishes two things: - - * Tables of contents from all those documents are inserted, with a maximum - depth of two, that means one nested heading. ``toctree`` directives in - those documents are also taken into account. - * Sphinx knows the relative order of the documents ``intro``, - ``strings`` and so forth, and it knows that they are children of the shown - document, the library index. From this information it generates "next - chapter", "previous chapter" and "parent chapter" links. - - **Entries** - - Document titles in the :rst:dir:`toctree` will be automatically read from the - title of the referenced document. If that isn't what you want, you can - specify an explicit title and target using a similar syntax to reST - hyperlinks (and Sphinx's :ref:`cross-referencing syntax `). This - looks like:: - - .. toctree:: - - intro - All about strings - datatypes - - The second line above will link to the ``strings`` document, but will use the - title "All about strings" instead of the title of the ``strings`` document. - - You can also add external links, by giving an HTTP URL instead of a document - name. - - **Section numbering** - - If you want to have section numbers even in HTML output, give the - **toplevel** toctree a ``numbered`` option. For example:: - - .. toctree:: - :numbered: - - foo - bar - - Numbering then starts at the heading of ``foo``. Sub-toctrees are - automatically numbered (don't give the ``numbered`` flag to those). - - Numbering up to a specific depth is also possible, by giving the depth as a - numeric argument to ``numbered``. - - **Additional options** - - You can use ``caption`` option to provide a toctree caption and you can use - ``name`` option to provide implicit target name that can be referenced by - using :rst:role:`ref`:: - - .. toctree:: - :caption: Table of Contents - :name: mastertoc - - foo - - If you want only the titles of documents in the tree to show up, not other - headings of the same level, you can use the ``titlesonly`` option:: - - .. toctree:: - :titlesonly: - - foo - bar - - You can use "globbing" in toctree directives, by giving the ``glob`` flag - option. All entries are then matched against the list of available - documents, and matches are inserted into the list alphabetically. Example:: - - .. toctree:: - :glob: - - intro* - recipe/* - * - - This includes first all documents whose names start with ``intro``, then all - documents in the ``recipe`` folder, then all remaining documents (except the - one containing the directive, of course.) [#]_ - - The special entry name ``self`` stands for the document containing the - toctree directive. This is useful if you want to generate a "sitemap" from - the toctree. - - You can use the ``reversed`` flag option to reverse the order of the entries - in the list. This can be useful when using the ``glob`` flag option to - reverse the ordering of the files. Example:: - - .. toctree:: - :glob: - :reversed: - - recipe/* - - You can also give a "hidden" option to the directive, like this:: - - .. toctree:: - :hidden: - - doc_1 - doc_2 - - This will still notify Sphinx of the document hierarchy, but not insert links - into the document at the location of the directive -- this makes sense if you - intend to insert these links yourself, in a different style, or in the HTML - sidebar. - - In cases where you want to have only one top-level toctree and hide all other - lower level toctrees you can add the "includehidden" option to the top-level - toctree entry:: - - .. toctree:: - :includehidden: - - doc_1 - doc_2 - - All other toctree entries can then be eliminated by the "hidden" option. - - 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 :confval:`exclude_patterns` to explicitly exclude documents or - directories from building completely. Use :ref:`the "orphan" 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 - as a "full table of contents" if you don't give a ``maxdepth`` option. - - .. versionchanged:: 0.3 - Added "globbing" option. - - .. versionchanged:: 0.6 - Added "numbered" and "hidden" options as well as external links and - support for "self" references. - - .. versionchanged:: 1.0 - Added "titlesonly" option. - - .. versionchanged:: 1.1 - Added numeric argument to "numbered". - - .. versionchanged:: 1.2 - Added "includehidden" option. - - .. versionchanged:: 1.3 - Added "caption" and "name" option. - -Special names -------------- - -Sphinx reserves some document names for its own use; you should not try to -create documents with these names -- it will cause problems. - -The special document names (and pages generated for them) are: - -* ``genindex``, ``modindex``, ``search`` - - These are used for the general index, the Python module index, and the search - page, respectively. - - The general index is populated with entries from modules, all index-generating - :ref:`object descriptions `, and from :rst:dir:`index` - directives. - - The Python module index contains one entry per :rst:dir:`py:module` directive. - - The search page contains a form that uses the generated JSON search index and - JavaScript to full-text search the generated documents for search words; it - should work on every major browser that supports modern JavaScript. - -* every name beginning with ``_`` - - Though only few such names are currently used by Sphinx, you should not create - documents or document-containing directories with such names. (Using ``_`` as - a prefix for a custom template directory is fine.) - -.. warning:: - - Be careful with unusual characters in filenames. Some formats may interpret - these characters in unexpected ways: - - * Do not use the colon ``:`` for HTML based formats. Links to other parts - may not work. - - * Do not use the plus ``+`` for the ePub format. Some resources may not be - found. - -.. rubric:: Footnotes - -.. [#] The LaTeX writer only refers the ``maxdepth`` option of first toctree - directive in the document. - -.. [#] A note on available globbing syntax: you can use the standard shell - constructs ``*``, ``?``, ``[...]`` and ``[!...]`` with the feature that - these all don't match slashes. A double star ``**`` can be used to match - any sequence of characters *including* slashes. diff --git a/doc/usage/installation.rst b/doc/usage/installation.rst index 23f1aef98..4bbd42a09 100644 --- a/doc/usage/installation.rst +++ b/doc/usage/installation.rst @@ -108,7 +108,7 @@ Windows Most Windows users do not have Python installed by default, so we begin with the installation of Python itself. If you are unsure, open the *Command -Prompt* (:kbd:`Control-r` and type :command:`cmd`). Once the command prompt is +Prompt* (:kbd:`⊞Win-r` and type :command:`cmd`). Once the command prompt is open, type :command:`python --version` and press Enter. If Python is available, you will see the version of Python printed to the screen. If you do not have Python installed, refer to the `Hitchhikers Guide to Python's`__ @@ -140,7 +140,7 @@ On Linux or MacOS, you should open your terminal and run the following command. $ pip install -U sphinx -On Windows, you should open *Command Prompt* (:kbd:`Control-r` and type +On Windows, you should open *Command Prompt* (:kbd:`⊞Win-r` and type :command:`cmd`) and run the same command. .. code-block:: bat diff --git a/doc/usage/quickstart.rst b/doc/usage/quickstart.rst index 650410333..3c8941e10 100644 --- a/doc/usage/quickstart.rst +++ b/doc/usage/quickstart.rst @@ -108,9 +108,8 @@ for this document -- use the "Show Source" link in the sidebar. .. todo:: Update the below link when we add new guides on these. -|more| See :ref:`rst-primer` for a more in-depth introduction to -reStructuredText and :ref:`sphinxmarkup` for a full list of markup added by -Sphinx. +|more| See :doc:`/usage/restructuredtext/index` for a more in-depth +introduction to reStructuredText, including markup added by Sphinx. Running the build @@ -211,8 +210,8 @@ Each domain will have special rules for how the signatures can look like, and make the formatted output look pretty, or add specific features like links to parameter types, e.g. in the C/C++ domains. -|more| See :ref:`domains` for all the available domains and their -directives/roles. +|more| See :doc:`/usage/restructuredtext/domains` for all the available domains +and their directives/roles. Basic configuration @@ -308,8 +307,8 @@ cross-reference that has no matching target in the current documentation set, will be looked up in the documentation sets configured in :confval:`intersphinx_mapping` (this needs access to the URL in order to download the list of valid targets). Intersphinx also works for some other -:ref:`domains' ` roles including ``:ref:``, however it doesn't work -for ``:doc:`` as that is non-domain role. +:term:`domain`\'s roles including ``:ref:``, however it doesn't work for +``:doc:`` as that is non-domain role. |more| See :mod:`sphinx.ext.intersphinx` for the complete description of the features of intersphinx. diff --git a/doc/rest.rst b/doc/usage/restructuredtext/basics.rst similarity index 74% rename from doc/rest.rst rename to doc/usage/restructuredtext/basics.rst index b059b873b..8d1576861 100644 --- a/doc/rest.rst +++ b/doc/usage/restructuredtext/basics.rst @@ -1,12 +1,12 @@ -.. highlightlang:: rest - -.. _rst-primer: +.. highlightlang:: rst +======================= reStructuredText Primer ======================= -This section is a brief introduction to reStructuredText (reST) concepts and -syntax, intended to provide authors with enough information to author documents +reStructuredText is the default plaintext markup language used by Sphinx. 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. @@ -27,7 +27,7 @@ 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. -.. _inlinemarkup: +.. _rst-inline-markup: Inline markup ------------- @@ -50,30 +50,16 @@ Be aware of some restrictions of this markup: 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```. - -Standard reST provides the following roles: - -* :durole:`emphasis` -- alternate spelling for ``*emphasis*`` -* :durole:`strong` -- alternate spelling for ``**strong**`` -* :durole:`literal` -- alternate spelling for ````literal```` -* :durole:`subscript` -- subscript text -* :durole:`superscript` -- superscript text -* :durole:`title-reference` -- for titles of books, periodicals, and other - materials - -See :ref:`inline-markup` for roles added by Sphinx. +It is also possible to replace or expand upon some of this inline markup with +roles. Refer to :ref:`rst-roles-alt` for more information. Lists and Quote-like blocks --------------------------- List markup (:duref:`ref `) 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:: +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 @@ -85,7 +71,6 @@ they can also be autonumbered using a ``#`` sign:: #. This is a numbered list. #. It has two items too. - Nested lists are possible, but be aware that they must be separated from the parent list items by blank lines:: @@ -120,18 +105,22 @@ Line blocks (:duref:`ref `) are a way of preserving line breaks:: There are also several more special blocks available: -* field lists (:duref:`ref `) +* field lists (:duref:`ref `, with caveats noted in + :ref:`rst-field-lists`) * option lists (:duref:`ref `) * quoted literal blocks (:duref:`ref `) * doctest blocks (:duref:`ref `) -Source Code ------------ +.. _rst-literal-blocks: + +Literal blocks +-------------- Literal code blocks (:duref:`ref `) are introduced by ending a paragraph with the special marker ``::``. The literal block must be indented -(and, like all paragraphs, separated from the surrounding ones by blank lines):: +(and, like all paragraphs, separated from the surrounding ones by blank +lines):: This is a normal text paragraph. The next paragraph is a code sample:: @@ -144,8 +133,8 @@ paragraph with the special marker ``::``. The literal block must be indented 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 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. @@ -153,15 +142,33 @@ The handling of the ``::`` marker is smart: That way, the second sentence in the above example's first paragraph would be rendered as "The next paragraph is a code sample:". +Code highlighting can be enabled for these literal blocks on a document-wide +basis using the :rst:dir:`highlight` directive and on a project-wide basis +using the :confval:`highlight_language` configuration option. The +:rst:dir:`code-block` directive can be used to set highlighting on a +block-by-block basis. These directives are discussed later. + + +.. _rst-doctest-blocks: + +Doctest blocks +-------------- + +Doctest blocks (:duref:`ref `) are interactive Python sessions +cut-and-pasted into docstrings. They do not require the +:ref:`literal blocks ` syntax. The doctest block must end +with a blank line and should *not* end with with an unused prompt:: + + >>> 1 + 1 + 2 .. _rst-tables: Tables ------ -For *grid tables* (:duref:`ref -`), you have to "paint" the cell grid yourself. They look like -this:: +For *grid tables* (:duref:`ref `), you have to "paint" the cell +grid yourself. They look like this:: +------------------------+------------+----------+----------+ | Header row, column 1 | Header 2 | Header 3 | Header 4 | @@ -186,17 +193,18 @@ contain multiple lines. They look like this:: ===== ===== ======= Two more syntaxes are supported: *CSV tables* and *List tables*. They use an -*explicit markup block*, see `Directives`_ section. +*explicit markup block*. Refer to :ref:`table-directives` for more information. + Hyperlinks ---------- External links -^^^^^^^^^^^^^^ +~~~~~~~~~~~~~~ -Use ```Link text `_`` 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. +Use ```Link text `_`` 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. .. important:: There must be a space between the link text and the opening \< for the URL. @@ -207,9 +215,8 @@ You can also separate the link and the target definition (:duref:`ref .. _a link: https://domain.invalid/ - Internal links -^^^^^^^^^^^^^^ +~~~~~~~~~~~~~~ Internal linking is done via a special reST role provided by Sphinx, see the section on specific markup, :ref:`ref-role`. @@ -244,6 +251,59 @@ documentation), and use a deeper nesting level, but keep in mind that most target formats (HTML, LaTeX) have a limited supported nesting depth. +.. _rst-field-lists: + +Field Lists +----------- + +Field lists (:duref:`ref `) are sequences of fields marked up like +this:: + + :fieldname: Field content + +They are commonly used in Python documentation:: + + def my_function(my_arg, my_other_arg): + """A function just for me. + + :param my_arg: The first of my arguments. + :param my_other_arg: The second of my arguments. + + :returns: A message (just for me, of course). + """ + +Sphinx extends standard docutils behavior and intercepts field lists specified +at the beginning of documents. Refer to :doc:`field-lists` for more +information. + + +.. TODO This ref should be 'rst-roles', but that already exists. Rename the +.. other ones + +.. _rst-roles-alt: + +Roles +----- + +A role or "custom interpreted text role" (:duref:`ref `) is an inline +piece of explicit markup. It signifies that 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```. + +Docutils supports the following roles: + +* :durole:`emphasis` -- equivalent of ``*emphasis*`` +* :durole:`strong` -- equivalent of ``**strong**`` +* :durole:`literal` -- equivalent of ````literal```` +* :durole:`subscript` -- subscript text +* :durole:`superscript` -- superscript text +* :durole:`title-reference` -- for titles of books, periodicals, and other + materials + +Refer to :doc:`roles` for roles added by Sphinx. + + Explicit Markup --------------- @@ -253,19 +313,19 @@ 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.) +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: +.. _rst-directives: Directives ---------- A directive (:duref:`ref `) 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. +Along with roles, it is one of the extension mechanisms of reST, and Sphinx +makes heavy use of it. Docutils supports the following directives: @@ -303,9 +363,9 @@ Docutils supports the following directives: * Special directives: - :dudir:`raw ` (include raw target-format markup) - - :dudir:`include` (include reStructuredText from another file) - -- in Sphinx, when given an absolute include file path, this directive takes - it as relative to the source directory + - :dudir:`include` (include reStructuredText from another file) -- in Sphinx, + when given an absolute include file path, this directive takes it as + relative to the source directory - :dudir:`class` (assign a class attribute to the next element) [1]_ * HTML specifics: @@ -321,14 +381,16 @@ Docutils supports the following directives: Since these are only per-file, better use Sphinx's facilities for setting the :confval:`default_role`. -Do *not* use the directives :dudir:`sectnum`, :dudir:`header` and -:dudir:`footer`. +.. warning:: -Directives added by Sphinx are described in :ref:`sphinxmarkup`. + Do *not* use the directives :dudir:`sectnum`, :dudir:`header` and + :dudir:`footer`. -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, :: +Directives added by Sphinx are described in :doc:`directives`. + +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) @@ -338,12 +400,12 @@ directives.) Looking at this example, :: ``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 -``module`` (as you can see, options are given in the lines immediately following -the arguments and indicated by the colons). Options must be indented to the -same level as the directive content. +``module`` (as you can see, options are given in the lines immediately +following the arguments and indicated by the colons). Options must be indented +to the same level as the directive content. -The directive content follows after a blank line and is indented relative to the -directive start. +The directive content follows after a blank line and is indented relative to +the directive start. Images @@ -356,8 +418,8 @@ reST supports an image directive (:dudir:`ref `), used like so:: When used within Sphinx, the file name given (here ``gnu.png``) must either be relative to the source file, or absolute which means that they are relative to -the top source directory. For example, the file ``sketch/spam.rst`` could refer -to the image ``images/spam.png`` as ``../images/spam.png`` or +the top source directory. For example, the file ``sketch/spam.rst`` could +refer to the image ``images/spam.png`` as ``../images/spam.png`` or ``/images/spam.png``. Sphinx will automatically copy image files over to a subdirectory of the output @@ -365,21 +427,22 @@ directory on building (e.g. the ``_static`` directory for HTML output.) Interpretation of image size options (``width`` and ``height``) is as follows: if the size has no unit or the unit is pixels, the given size will only be -respected for output channels that support pixels. Other units (like ``pt`` -for points) will be used for HTML and LaTeX output (the latter replaces ``pt`` -by ``bp`` as this is the TeX unit such that ``72bp=1in``). +respected for output channels that support pixels. Other units (like ``pt`` for +points) will be used for HTML and LaTeX output (the latter replaces ``pt`` by +``bp`` as this is the TeX unit such that ``72bp=1in``). Sphinx extends the standard docutils behavior by allowing an asterisk for the extension:: .. image:: gnu.* -Sphinx then searches for all images matching the provided pattern and determines -their type. Each builder then chooses the best image out of these candidates. -For instance, if the file name ``gnu.*`` was given and two files :file:`gnu.pdf` -and :file:`gnu.png` existed in the source tree, the LaTeX builder would choose -the former, while the HTML builder would prefer the latter. -Supported image types and choosing priority are defined at :ref:`builders`. +Sphinx then searches for all images matching the provided pattern and +determines their type. Each builder then chooses the best image out of these +candidates. For instance, if the file name ``gnu.*`` was given and two files +:file:`gnu.pdf` and :file:`gnu.png` existed in the source tree, the LaTeX +builder would choose the former, while the HTML builder would prefer the +latter. Supported image types and choosing priority are defined at +:ref:`builders`. Note that image file names should not contain spaces. @@ -446,8 +509,8 @@ for details. If you want to use some substitutions for all documents, put them into :confval:`rst_prolog` or put them into a separate file and include it into all documents you want to use them in, using the :rst:dir:`include` directive. (Be -sure to give the include file a file name extension differing from that of other -source files, to avoid Sphinx finding it as a standalone document.) +sure to give the include file a file name extension differing from that of +other source files, to avoid Sphinx finding it as a standalone document.) Sphinx defines some default substitutions, see :ref:`default-substitutions`. @@ -486,8 +549,8 @@ 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 a - backslash-escaped space to get around that. See - :duref:`the reference ` for the details. + backslash-escaped space to get around that. See :duref:`the reference + ` for the details. * **No nested inline markup:** Something like ``*see :func:`foo`*`` is not possible. diff --git a/doc/usage/restructuredtext/directives.rst b/doc/usage/restructuredtext/directives.rst new file mode 100644 index 000000000..1a41dbef1 --- /dev/null +++ b/doc/usage/restructuredtext/directives.rst @@ -0,0 +1,1070 @@ +.. highlight:: rst + +========== +Directives +========== + +:ref:`As previously discussed `, a directive is a generic block +of explicit markup. While Docutils provides a number of directives, Sphinx +provides many more and uses directives as one of the primary extension +mechanisms. + +See :doc:`/usage/restructuredtext/domains` for roles added by domains. + +.. seealso:: + + Refer to the :ref:`reStructuredText Primer ` for an overview + of the directives provided by Docutils. + + +.. _toctree-directive: + +Table of contents +----------------- + +.. index:: pair: table of; contents + +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. + +.. note:: + + Simple "inclusion" of one file in another can be done with the + :dudir:`include` directive. + +.. note:: + + For local tables of contents, use the standard reST :dudir:`contents + directive `. + +.. rst:directive:: toctree + + This directive inserts a "TOC tree" at the current location, using the + individual TOCs (including "sub-TOC trees") of the documents given in the + directive body. Relative document names (not beginning with a slash) are + relative to the document the directive occurs in, absolute names are relative + to the source directory. 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 Python docs' library reference index):: + + .. toctree:: + :maxdepth: 2 + + intro + strings + datatypes + numeric + (many more documents listed here) + + This accomplishes two things: + + * Tables of contents from all those documents are inserted, with a maximum + depth of two, that means one nested heading. ``toctree`` directives in + those documents are also taken into account. + * Sphinx knows the relative order of the documents ``intro``, + ``strings`` and so forth, and it knows that they are children of the shown + document, the library index. From this information it generates "next + chapter", "previous chapter" and "parent chapter" links. + + **Entries** + + Document titles in the :rst:dir:`toctree` will be automatically read from the + title of the referenced document. If that isn't what you want, you can + specify an explicit title and target using a similar syntax to reST + hyperlinks (and Sphinx's :ref:`cross-referencing syntax `). This + looks like:: + + .. toctree:: + + intro + All about strings + datatypes + + The second line above will link to the ``strings`` document, but will use the + title "All about strings" instead of the title of the ``strings`` document. + + You can also add external links, by giving an HTTP URL instead of a document + name. + + **Section numbering** + + If you want to have section numbers even in HTML output, give the + **toplevel** toctree a ``numbered`` option. For example:: + + .. toctree:: + :numbered: + + foo + bar + + Numbering then starts at the heading of ``foo``. Sub-toctrees are + automatically numbered (don't give the ``numbered`` flag to those). + + Numbering up to a specific depth is also possible, by giving the depth as a + numeric argument to ``numbered``. + + **Additional options** + + You can use ``caption`` option to provide a toctree caption and you can use + ``name`` option to provide implicit target name that can be referenced by + using :rst:role:`ref`:: + + .. toctree:: + :caption: Table of Contents + :name: mastertoc + + foo + + If you want only the titles of documents in the tree to show up, not other + headings of the same level, you can use the ``titlesonly`` option:: + + .. toctree:: + :titlesonly: + + foo + bar + + You can use "globbing" in toctree directives, by giving the ``glob`` flag + option. All entries are then matched against the list of available + documents, and matches are inserted into the list alphabetically. Example:: + + .. toctree:: + :glob: + + intro* + recipe/* + * + + This includes first all documents whose names start with ``intro``, then all + documents in the ``recipe`` folder, then all remaining documents (except the + one containing the directive, of course.) [#]_ + + The special entry name ``self`` stands for the document containing the + toctree directive. This is useful if you want to generate a "sitemap" from + the toctree. + + You can use the ``reversed`` flag option to reverse the order of the entries + in the list. This can be useful when using the ``glob`` flag option to + reverse the ordering of the files. Example:: + + .. toctree:: + :glob: + :reversed: + + recipe/* + + You can also give a "hidden" option to the directive, like this:: + + .. toctree:: + :hidden: + + doc_1 + doc_2 + + This will still notify Sphinx of the document hierarchy, but not insert links + into the document at the location of the directive -- this makes sense if you + intend to insert these links yourself, in a different style, or in the HTML + sidebar. + + In cases where you want to have only one top-level toctree and hide all other + lower level toctrees you can add the "includehidden" option to the top-level + toctree entry:: + + .. toctree:: + :includehidden: + + doc_1 + doc_2 + + All other toctree entries can then be eliminated by the "hidden" option. + + 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 :confval:`exclude_patterns` to explicitly exclude documents or + directories from building completely. Use :ref:`the "orphan" 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 + as a "full table of contents" if you don't give a ``maxdepth`` option. + + .. versionchanged:: 0.3 + Added "globbing" option. + + .. versionchanged:: 0.6 + Added "numbered" and "hidden" options as well as external links and + support for "self" references. + + .. versionchanged:: 1.0 + Added "titlesonly" option. + + .. versionchanged:: 1.1 + Added numeric argument to "numbered". + + .. versionchanged:: 1.2 + Added "includehidden" option. + + .. versionchanged:: 1.3 + Added "caption" and "name" option. + +Special names +^^^^^^^^^^^^^ + +Sphinx reserves some document names for its own use; you should not try to +create documents with these names -- it will cause problems. + +The special document names (and pages generated for them) are: + +* ``genindex``, ``modindex``, ``search`` + + These are used for the general index, the Python module index, and the search + page, respectively. + + The general index is populated with entries from modules, all + index-generating :ref:`object descriptions `, and from + :rst:dir:`index` directives. + + The Python module index contains one entry per :rst:dir:`py:module` + directive. + + The search page contains a form that uses the generated JSON search index and + JavaScript to full-text search the generated documents for search words; it + should work on every major browser that supports modern JavaScript. + +* every name beginning with ``_`` + + Though only few such names are currently used by Sphinx, you should not + create documents or document-containing directories with such names. (Using + ``_`` as a prefix for a custom template directory is fine.) + +.. warning:: + + Be careful with unusual characters in filenames. Some formats may interpret + these characters in unexpected ways: + + * Do not use the colon ``:`` for HTML based formats. Links to other parts + may not work. + + * Do not use the plus ``+`` for the ePub format. Some resources may not be + found. + + +Paragraph-level markup +---------------------- + +.. index:: note, warning + pair: changes; in version + +These directives create short paragraphs and can be used inside information +units as well as normal text. + +.. rst: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. + +.. rst: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 :rst:dir:`note` in that it is + recommended over :rst:dir:`note` for information regarding security. + +.. rst:directive:: .. versionadded:: version + + 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. + +.. rst:directive:: .. versionchanged:: version + + Similar to :rst:dir:`versionadded`, but describes when and what changed in + the named feature in some way (new parameters, changed side effects, etc.). + +.. rst:directive:: .. deprecated:: version + + Similar to :rst:dir:`versionchanged`, but describes when the feature was + deprecated. An explanation can also be given, for example to inform the + reader what should be used instead. Example:: + + .. deprecated:: 3.1 + Use :func:`spam` instead. + +.. rst:directive:: seealso + + Many sections include a list of references to module documentation or + external documents. These lists are created using the :rst:dir:`seealso` + directive. + + The :rst:dir:`seealso` directive is typically placed in a section just before + any subsections. For the HTML output, it is shown boxed off from the main + flow of the text. + + The content of the :rst:dir:`seealso` directive should be a reST definition + list. Example:: + + .. seealso:: + + Module :py:mod:`zipfile` + Documentation of the :py:mod:`zipfile` standard module. + + `GNU tar manual, Basic Tar Format `_ + Documentation for tar archive files, including GNU tar extensions. + + There's also a "short form" allowed that looks like this:: + + .. seealso:: modules :py:mod:`zipfile`, :py:mod:`tarfile` + + .. versionadded:: 0.5 + The short form. + +.. rst:directive:: .. rubric:: title + + This directive creates a paragraph heading that is not used to create a + table of contents node. + + .. note:: + + If the *title* of the rubric is "Footnotes" (or the selected language's + equivalent), this rubric is ignored by the LaTeX writer, since it is + assumed to only contain footnote definitions and therefore would create an + empty heading. + +.. rst:directive:: centered + + This directive creates a centered boldfaced line of text. Use it as + follows:: + + .. centered:: LICENSE AGREEMENT + + .. deprecated:: 1.1 + This presentation-only directive is a legacy from older versions. Use a + :rst:dir:`rst-class` directive instead and add an appropriate style. + +.. rst:directive:: hlist + + This directive must contain a bullet list. It will transform it into a more + compact list by either distributing more than one item horizontally, or + reducing spacing between items, depending on the builder. + + For builders that support the horizontal distribution, there is a ``columns`` + option that specifies the number of columns; it defaults to 2. Example:: + + .. hlist:: + :columns: 3 + + * A list of + * short items + * that should be + * displayed + * horizontally + + .. versionadded:: 0.6 + + +.. _code-examples: + +Showing code examples +--------------------- + +.. index:: pair: code; examples + single: sourcecode + +There are multiple ways to show syntax-highlighted literal code blocks in +Sphinx: using :ref:`reST doctest blocks `; using :ref:`reST +literal blocks `, optionally in combination with the +:rst:dir:`highlight` directive; using the :rst:dir:`code-block` directive; and +using the :rst:dir:`literalinclude` directive. Doctest blocks can only be used +to show interactive Python sessions, while the remaining three can be used for +other languages. Of these three, literal blocks are useful when an entire +document, or at least large sections of it, use code blocks with the same +syntax and which should be styled in the same manner. On the other hand, the +:rst:dir:`code-block` directive makes more sense when you want more fine-tuned +control over the styling of each block or when you have a document containing +code blocks using multiple varied syntaxes. Finally, the +:rst:dir:`literalinclude` directive is useful for including entire code files +in your documentation. + +In all cases, Syntax highlighting is provided by `Pygments +`_. When using literal blocks, this is configured using +any :rst:dir:`highlight` directives in the source file. When a ``highlight`` +directive is encountered, it is used until the next ``highlight`` directive is +encountered. If there is no ``highlight`` directive in the file, the global +highlighting language is used. This defaults to ``python`` but can be +configured using the :confval:`highlight_language` config value. The following +values are supported: + +* ``none`` (no highlighting) +* ``default`` (similar to ``python3`` but with a fallback to ``none`` without + warning highlighting fails; the default when :confval:`highlight_language` + isn't set) +* ``guess`` (let Pygments guess the lexer based on contents, only works with + certain well-recognizable languages) +* ``python`` +* ``rest`` +* ``c`` +* ... and any other `lexer alias that Pygments supports`__ + +If highlighting with the selected language fails (i.e. Pygments emits an +"Error" token), the block is not highlighted in any way. + +.. important:: + + The list of lexer aliases supported is tied to the Pygment version. If you + want to ensure consistent highlighting, you should fix your version of + Pygments. + +__ http://pygments.org/docs/lexers/ + +.. rst:directive:: .. highlight:: language + + Example:: + + .. highlight:: c + + This language is used until the next ``highlight`` directive is encountered. + As discussed previously, *language* can be any lexer alias supported by + Pygments. + + **Additional options** + + Pygments can generate line numbers for code blocks. To enable this, use the + ``linenothreshold`` option. :: + + .. highlight:: python + :linenothreshold: 5 + + This will produce line numbers for all code blocks longer than five lines. + +.. rst:directive:: .. code-block:: language + + Example:: + + .. code-block:: ruby + + Some Ruby code. + + The directive's alias name :rst:dir:`sourcecode` works as well. As with + :rst:dir:`highlight`\ 's ``language`` option, ``language`` can be any lexer + alias supported by Pygments. + + **Additional options** + + Pygments can generate line numbers for code blocks. To enable this for, use + the ``linenos`` flag option. :: + + .. code-block:: ruby + :linenos: + + Some more Ruby code. + + The first line number can be selected with the ``lineno-start`` option. If + present, ``linenos`` flag is automatically activated:: + + .. code-block:: ruby + :lineno-start: 10 + + Some more Ruby code, with line numbering starting at 10. + + Additionally, an ``emphasize-lines`` option can be given to have Pygments + emphasize particular lines:: + + .. code-block:: python + :emphasize-lines: 3,5 + + def some_function(): + interesting = False + print 'This line is highlighted.' + print 'This one is not...' + print '...but this one is.' + + A ``caption`` option can be given to show that name before the code block. + A ``name`` option can be provided implicit target name that can be + referenced by using :rst:role:`ref`. For example:: + + .. code-block:: python + :caption: this.py + :name: this-py + + print 'Explicit is better than implicit.' + + A ``dedent`` option can be given to strip indentation characters from the + code block. For example:: + + .. code-block:: ruby + :dedent: 4 + + some ruby code + + .. versionchanged:: 1.1 + The ``emphasize-lines`` option has been added. + + .. versionchanged:: 1.3 + The ``lineno-start``, ``caption``, ``name`` and ``dedent`` options have + been added. + + .. versionchanged:: 1.6.6 + LaTeX supports the ``emphasize-lines`` option. + +.. rst:directive:: .. literalinclude:: filename + + 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. [#]_ For example, to include the + Python source file :file:`example.py`, use:: + + .. literalinclude:: example.py + + The file name is usually relative to the current file's path. However, if + it is absolute (starting with ``/``), it is relative to the top source + directory. + + **Additional options** + + Like :rst:dir:`code-block`, the directive supports the ``linenos`` flag + option to switch on line numbers, the ``lineno-start`` option to select the + first line number, the ``emphasize-lines`` option to emphasize particular + lines, the ``name`` option to provide an implicit target name, the + ``dedent`` option to strip indentation characters for the code block, and a + ``language`` option to select a language different from the current file's + standard language. In addition, it supports the ``caption`` option; however, + this can be provided with no argument to use the filename as the caption. + Example with options:: + + .. literalinclude:: example.rb + :language: ruby + :emphasize-lines: 12,15-18 + :linenos: + + Tabs in the input are expanded if you give a ``tab-width`` option with the + desired tab width. + + Include files are assumed to be encoded in the :confval:`source_encoding`. + If the file has a different encoding, you can specify it with the + ``encoding`` option:: + + .. literalinclude:: example.py + :encoding: latin-1 + + The directive also supports including only parts of the file. If it is a + Python module, you can select a class, function or method to include using + the ``pyobject`` option:: + + .. literalinclude:: example.py + :pyobject: Timer.start + + This would only include the code lines belonging to the ``start()`` method + in the ``Timer`` class within the file. + + Alternately, you can specify exactly which lines to include by giving a + ``lines`` option:: + + .. literalinclude:: example.py + :lines: 1,3,5-10,20- + + This includes the lines 1, 3, 5 to 10 and lines 20 to the last line. + + Another way to control which part of the file is included is to use the + ``start-after`` and ``end-before`` options (or only one of them). If + ``start-after`` is given as a string option, only lines that follow the + first line containing that string are included. If ``end-before`` is given + as a string option, only lines that precede the first lines containing that + string are included. + + With lines selected using ``start-after`` it is still possible to use + ``lines``, the first allowed line having by convention the line number + ``1``. + + When lines have been selected in any of the ways described above, the line + numbers in ``emphasize-lines`` refer to those selected lines, counted + consecutively starting at ``1``. + + When specifying particular parts of a file to display, it can be useful to + display the original line numbers. This can be done using the + ``lineno-match`` option, which is however allowed only when the selection + consists of contiguous lines. + + You can prepend and/or append a line to the included code, using the + ``prepend`` and ``append`` option, respectively. This is useful e.g. for + highlighting PHP code that doesn't include the ```` markers. + + If you want to show the diff of the code, you can specify the old file by + giving a ``diff`` option:: + + .. literalinclude:: example.py + :diff: example.py.orig + + This shows the diff between ``example.py`` and ``example.py.orig`` with + unified diff format. + + .. versionchanged:: 0.4.3 + Added the ``encoding`` option. + + .. versionchanged:: 0.6 + Added the ``pyobject``, ``lines``, ``start-after`` and ``end-before`` + options, as well as support for absolute filenames. + + .. versionchanged:: 1.0 + Added the ``prepend``, ``append``, and ``tab-width`` options. + + .. versionchanged:: 1.3 + Added the ``diff``, ``lineno-match``, ``caption``, ``name``, and + ``dedent`` options. + + .. versionchanged:: 1.6 + With both ``start-after`` and ``lines`` in use, the first line as per + ``start-after`` is considered to be with line number ``1`` for ``lines``. + +.. _glossary-directive: + +Glossary +-------- + +.. rst:directive:: .. glossary:: + + This directive must contain a reST definition-list-like markup with terms and + definitions. The definitions will then be referencable with the + :rst:role:`term` role. Example:: + + .. glossary:: + + environment + A structure where information about all documents under the root is + saved, and used for cross-referencing. The environment is pickled + after the parsing stage, so that successive runs only need to read + and parse new and changed documents. + + source directory + The directory which, including its subdirectories, contains all + source files for one Sphinx project. + + In contrast to regular definition lists, *multiple* terms per entry are + allowed, and inline markup is allowed in terms. You can link to all of the + terms. For example:: + + .. glossary:: + + term 1 + term 2 + Definition of both terms. + + (When the glossary is sorted, the first term determines the sort order.) + + If you want to specify "grouping key" for general index entries, you can put a "key" + as "term : key". For example:: + + .. glossary:: + + term 1 : A + term 2 : B + Definition of both terms. + + Note that "key" is used for grouping key as is. + The "key" isn't normalized; key "A" and "a" become different groups. + The whole characters in "key" is used instead of a first character; it is used for + "Combining Character Sequence" and "Surrogate Pairs" grouping key. + + In i18n situation, you can specify "localized term : key" even if original text only + have "term" part. In this case, translated "localized term" will be categorized in + "key" group. + + .. versionadded:: 0.6 + You can now give the glossary directive a ``:sorted:`` flag that will + automatically sort the entries alphabetically. + + .. versionchanged:: 1.1 + Now supports multiple terms and inline markup in terms. + + .. versionchanged:: 1.4 + Index key for glossary term should be considered *experimental*. + + +Meta-information markup +----------------------- + +.. rst:directive:: .. sectionauthor:: name + + 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 + + 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. + + +.. rst:directive:: .. codeauthor:: name + + The :rst:dir:`codeauthor` directive, which can appear multiple times, names + the authors of the described code, just like :rst:dir:`sectionauthor` names + the author(s) of a piece of documentation. It too only produces output if + the :confval:`show_authors` configuration value is ``True``. + + +Index-generating markup +----------------------- + +Sphinx automatically creates index entries from all object descriptions (like +functions, classes or attributes) like discussed in +:doc:`/usage/restructuredtext/domains`. + +However, there is also explicit markup 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. + +.. rst:directive:: .. index:: + + This directive 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 + + The execution context + --------------------- + + ... + + 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). + + Since index directives generate cross-reference targets at their location in + the source, it makes sense to put them *before* the thing they refer to -- + e.g. a heading, as in the example above. + + 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``. + see + ``see: entry; other`` creates an index entry that refers from ``entry`` to + ``other``. + seealso + Like ``see``, but inserts "see also" instead of "see". + 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``. (These + are Python-specific and therefore deprecated.) + + You can mark up "main" index entries by prefixing them with an exclamation + mark. The references to "main" entries are emphasized in the generated + index. For example, if two pages contain :: + + .. index:: Python + + and one page contains :: + + .. index:: ! Python + + then the backlink to the latter page is emphasized among the three backlinks. + + For index directives containing only "single" entries, there is a shorthand + notation:: + + .. index:: BNF, grammar, syntax, notation + + This creates four index entries. + + .. versionchanged:: 1.1 + Added ``see`` and ``seealso`` types, as well as marking main entries. + +.. rst:role:: index + + While the :rst:dir:`index` directive is a block-level markup and links to the + beginning of the next paragraph, there is also a corresponding role that sets + the link target directly where it is used. + + The content of the role can be a simple phrase, which is then kept in the + text and used as an index entry. It can also be a combination of text and + index entry, styled like with explicit targets of cross-references. In that + case, the "target" part can be a full entry as described for the directive + above. For example:: + + This is a normal reST :index:`paragraph` that contains several + :index:`index entries `. + + .. versionadded:: 1.1 + + +.. _tags: + +Including content based on tags +------------------------------- + +.. rst:directive:: .. only:: + + Include the content of the directive only if the *expression* is true. The + expression should consist of tags, like this:: + + .. only:: html and draft + + Undefined tags are false, defined tags (via the ``-t`` command-line option or + within :file:`conf.py`, see :ref:`here `) are true. Boolean + expressions, also using parentheses (like ``html and (latex or draft)``) are + supported. + + The *format* and the *name* of the current builder (``html``, ``latex`` or + ``text``) are always set as a tag [#]_. To make the distinction between + format and name explicit, they are also added with the prefix ``format_`` and + ``builder_``, e.g. the epub builder defines the tags ``html``, ``epub``, + ``format_html`` and ``builder_epub``. + + These standard tags are set *after* the configuration file is read, so they + are not available there. + + All tags must follow the standard Python identifier syntax as set out in + the `Identifiers and keywords + `_ + documentation. That is, a tag expression may only consist of tags that + conform to the syntax of Python variables. In ASCII, this consists of the + uppercase and lowercase letters ``A`` through ``Z``, the underscore ``_`` + and, except for the first character, the digits ``0`` through ``9``. + + .. versionadded:: 0.6 + .. versionchanged:: 1.2 + Added the name of the builder and the prefixes. + + .. warning:: + + This directive is designed to control only content of document. It could + not control sections, labels and so on. + +.. _table-directives: + +Tables +------ + +Use :ref:`reStructuredText tables `, i.e. either + +- grid table syntax (:duref:`ref `), +- simple table syntax (:duref:`ref `), +- :dudir:`csv-table` syntax, +- or :dudir:`list-table` syntax. + +The :dudir:`table` directive serves as optional wrapper of the *grid* and +*simple* syntaxes. + +They work fine in HTML output, however there are some gotchas when using tables +in LaTeX: the column width is hard to determine correctly automatically. For +this reason, the following directive exists: + +.. rst:directive:: .. tabularcolumns:: column spec + + This directive gives a "column spec" for the next table occurring in the + source file. The spec is the second argument to the LaTeX ``tabulary`` + package's environment (which Sphinx uses to translate tables). It can have + values like :: + + |l|l|l| + + which means three left-adjusted, nonbreaking columns. For columns with + longer text that should automatically be broken, use either the standard + ``p{width}`` construct, or tabulary's automatic specifiers: + + +-----+------------------------------------------+ + |``L``| flush left column with automatic width | + +-----+------------------------------------------+ + |``R``| flush right column with automatic width | + +-----+------------------------------------------+ + |``C``| centered column with automatic width | + +-----+------------------------------------------+ + |``J``| justified column with automatic width | + +-----+------------------------------------------+ + + The automatic widths of the ``LRCJ`` columns are attributed by ``tabulary`` + in proportion to the observed shares in a first pass where the table cells + are rendered at their natural "horizontal" widths. + + By default, Sphinx uses a table layout with ``J`` for every column. + + .. versionadded:: 0.3 + + .. versionchanged:: 1.6 + Merged cells may now contain multiple paragraphs and are much better + handled, thanks to custom Sphinx LaTeX macros. This novel situation + motivated the switch to ``J`` specifier and not ``L`` by default. + + .. hint:: + + Sphinx actually uses ``T`` specifier having done ``\newcolumntype{T}{J}``. + To revert to previous default, insert ``\newcolumntype{T}{L}`` in the + LaTeX preamble (see :confval:`latex_elements`). + + A frequent issue with tabulary is that columns with little contents are + "squeezed". The minimal column width is a tabulary parameter called + ``\tymin``. You may set it globally in the LaTeX preamble via + ``\setlength{\tymin}{40pt}`` for example. + + Else, use the :rst:dir:`tabularcolumns` directive with an explicit + ``p{40pt}`` (for example) for that column. You may use also ``l`` + specifier but this makes the task of setting column widths more difficult + if some merged cell intersects that column. + + .. warning:: + + Tables with more than 30 rows are rendered using ``longtable``, not + ``tabulary``, in order to allow pagebreaks. The ``L``, ``R``, ... specifiers + do not work for these tables. + + Tables that contain list-like elements such as object descriptions, + blockquotes or any kind of lists cannot be set out of the box with + ``tabulary``. They are therefore set with the standard LaTeX ``tabular`` (or + ``longtable``) environment if you don't give a ``tabularcolumns`` directive. + If you do, the table will be set with ``tabulary`` but you must use the + ``p{width}`` construct (or Sphinx's ``\X`` and ``\Y`` specifiers described + below) for the columns containing these elements. + + Literal blocks do not work with ``tabulary`` at all, so tables containing + a literal block are always set with ``tabular``. The verbatim environment + used for literal blocks only works in ``p{width}`` (and ``\X`` or ``\Y``) + columns, hence Sphinx generates such column specs for tables containing + literal blocks. + + Since Sphinx 1.5, the ``\X{a}{b}`` specifier is used (there *is* a backslash + in the specifier letter). It is like ``p{width}`` with the width set to a + fraction ``a/b`` of the current line width. You can use it in the + :rst:dir:`tabularcolumns` (it is not a problem if some LaTeX macro is also + called ``\X``.) + + It is *not* needed for ``b`` to be the total number of columns, nor for the + sum of the fractions of the ``\X`` specifiers to add up to one. For example + ``|\X{2}{5}|\X{1}{5}|\X{1}{5}|`` is legitimate and the table will occupy + 80% of the line width, the first of its three columns having the same width + as the sum of the next two. + + This is used by the ``:widths:`` option of the :dudir:`table` directive. + + Since Sphinx 1.6, there is also the ``\Y{f}`` specifier which admits a + decimal argument, such has ``\Y{0.15}``: this would have the same effect as + ``\X{3}{20}``. + + .. versionchanged:: 1.6 + + Merged cells from complex grid tables (either multi-row, multi-column, or + both) now allow blockquotes, lists, literal blocks, ... as do regular cells. + + Sphinx's merged cells interact well with ``p{width}``, ``\X{a}{b}``, ``Y{f}`` + and tabulary's columns. + + .. note:: + + :rst:dir:`tabularcolumns` conflicts with ``:widths:`` option of table + directives. If both are specified, ``:widths:`` option will be ignored. + + +Math +---- + +.. todo:: Move this in here. + +See :ref:`math-support`. + + +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: + +.. rst:directive:: .. productionlist:: [name] + + 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. + + The argument to :rst:dir:`productionlist` serves to distinguish different + sets of production lists that belong to different grammars. + + 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. Outside of the + production list, you can reference to token productions using + :rst:role:`token`. + + Note that no further reST parsing is done in the production, so that you + don't have to escape ``*`` or ``|`` characters. + +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` + + +.. rubric:: Footnotes + +.. [#] The LaTeX writer only refers the ``maxdepth`` option of first toctree + directive in the document. + +.. [#] A note on available globbing syntax: you can use the standard shell + constructs ``*``, ``?``, ``[...]`` and ``[!...]`` with the feature that + these all don't match slashes. A double star ``**`` can be used to + match any sequence of characters *including* slashes. + +.. [#] There is a standard ``.. include`` directive, but it raises errors if the + file is not found. This one only emits a warning. + +.. [#] For most builders name and format are the same. At the moment only + builders derived from the html builder distinguish between the builder + format and the builder name. + + Note that the current builder tag is not available in ``conf.py``, it is + only available after the builder is initialized. diff --git a/doc/domains.rst b/doc/usage/restructuredtext/domains.rst similarity index 86% rename from doc/domains.rst rename to doc/usage/restructuredtext/domains.rst index 5bed02cf4..85ac80cb7 100644 --- a/doc/domains.rst +++ b/doc/usage/restructuredtext/domains.rst @@ -1,15 +1,11 @@ .. highlight:: rst -.. _domains: - -Sphinx Domains -============== +======= +Domains +======= .. versionadded:: 1.0 -What is a Domain? ------------------ - Originally, Sphinx was conceived for a single project, the documentation of the Python language. Shortly afterwards, it was made available for everyone as a documentation tool, but the documentation of Python modules remained deeply @@ -19,20 +15,20 @@ developed in using it for many different purposes: C/C++ projects, JavaScript, or even reStructuredText markup (like in this documentation). While this was always possible, it is now much easier to easily support -documentation of projects using different programming languages or even ones not -supported by the main Sphinx distribution, by providing a **domain** for every -such purpose. +documentation of projects using different programming languages or even ones +not supported by the main Sphinx distribution, by providing a **domain** for +every such purpose. A domain is a collection of markup (reStructuredText :term:`directive`\ s and :term:`role`\ s) to describe and link to :term:`object`\ s belonging together, e.g. elements of a programming language. Directive and role names in a domain -have names like ``domain:name``, e.g. ``py:function``. Domains can also provide -custom indices (like the Python Module Index). +have names like ``domain:name``, e.g. ``py:function``. Domains can also +provide custom indices (like the Python Module Index). Having domains means that there are no naming problems when one set of -documentation wants to refer to e.g. C++ and Python classes. It also means that -extensions that support the documentation of whole new languages are much easier -to write. +documentation wants to refer to e.g. C++ and Python classes. It also means +that extensions that support the documentation of whole new languages are much +easier to write. This section describes what the domains that are included with Sphinx provide. The domain API is documented as well, in the section :ref:`domain-api`. @@ -65,9 +61,9 @@ that are continued in the next line. Example:: (This example also shows how to use the ``:noindex:`` flag.) -The domains also provide roles that link back to these object descriptions. For -example, to link to one of the functions described in the example above, you -could say :: +The domains also provide roles that link back to these object descriptions. +For example, to link to one of the functions described in the example above, +you could say :: The function :py:func:`spam` does a similar thing. @@ -86,9 +82,9 @@ value :confval:`primary_domain` or via this directive: Select a new default domain. While the :confval:`primary_domain` selects a global default, this only has an effect within the same file. -If no other default is selected, the Python domain (named ``py``) is the default -one, mostly for compatibility with documentation written for older versions of -Sphinx. +If no other default is selected, the Python domain (named ``py``) is the +default one, mostly for compatibility with documentation written for older +versions of Sphinx. Directives and roles that belong to the default domain can be mentioned without giving the domain name, i.e. :: @@ -99,7 +95,6 @@ giving the domain name, i.e. :: Reference to :func:`pyfunc`. - Cross-referencing syntax ~~~~~~~~~~~~~~~~~~~~~~~~ @@ -145,7 +140,6 @@ declarations: 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. - .. rst:directive:: .. py:currentmodule:: name This directive tells Sphinx that the classes, functions etc. documented from @@ -156,7 +150,6 @@ declarations: location has the :rst:dir:`py:module` directive, the others only :rst:dir:`py:currentmodule`. - The following directives are provided for module and class contents: .. rst:directive:: .. py:function:: name(parameters) @@ -275,7 +268,6 @@ The following directives are provided for module and class contents: Refer to a decorator method using the :rst:role:`py:meth` role. - .. _signatures: Python Signatures @@ -290,15 +282,14 @@ can also be given as well as return type annotations:: .. py:function:: compile(source : string, filename, symbol='file') -> ast object -For functions with optional parameters that don't have default values (typically -functions implemented in C extension modules without keyword argument support), -you can use brackets to specify the optional parts: +For functions with optional parameters that don't have default values +(typically functions implemented in C extension modules without keyword +argument support), you can use brackets to specify the optional parts: .. py:function:: compile(source[, filename[, symbol]]) It is customary to put the opening bracket before the comma. - .. _info-field-lists: Info field lists @@ -321,8 +312,8 @@ are recognized and formatted nicely: .. note:: - In current release, all ``var``, ``ivar`` and ``cvar`` are represented as "Variable". - There is no difference at all. + In current release, all ``var``, ``ivar`` and ``cvar`` are represented as + "Variable". There is no difference at all. The field names must consist of one of these keywords and an argument (except for ``returns`` and ``rtype``, which do not need an argument). This is best @@ -364,7 +355,6 @@ single word, like this:: :param int priority: The priority of the message, can be a number 1-5 - .. versionadded:: 1.5 Container types such as lists and dictionaries can be linked automatically @@ -377,8 +367,8 @@ using the following syntax:: :type point: tuple(float, float) :type point: tuple[float, float] -Multiple types in a type field will be linked automatically if separated by -the word "or":: +Multiple types in a type field will be linked automatically if separated by the +word "or":: :type an_arg: int or None :vartype a_var: str or int @@ -419,9 +409,9 @@ a matching identifier is found: .. rst:role:: py:meth - Reference a method of an object. The role text can include the type name and - the method name; if it occurs within the description of a type, the type name - can be omitted. A dotted name may be used. + Reference a method of an object. The role text can include the type name + and the method name; if it occurs within the description of a type, the type + name can be omitted. A dotted name may be used. .. rst:role:: py:attr @@ -439,24 +429,24 @@ a matching identifier is found: .. versionadded:: 0.4 The name enclosed in this markup can include a module name and/or a class name. -For example, ``:py:func:`filter``` could refer to a function named ``filter`` in -the current module, or the built-in function of that name. In contrast, +For example, ``:py:func:`filter``` could refer to a function named ``filter`` +in the current module, or the built-in function of that name. In contrast, ``:py: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 Python's +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 Python's :mod:`codecs` module, ``:py:func:`open``` always refers to the built-in function, while ``:py: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. +A similar heuristic is used to determine whether the name is an attribute of +the currently documented class. Also, if the name is prefixed with a dot, and no exact match is found, the -target is taken as a suffix and all object names with that suffix are -searched. For example, ``:py:meth:`.TarFile.close``` references the +target is taken as a suffix and all object names with that suffix are searched. +For example, ``:py:meth:`.TarFile.close``` references the ``tarfile.TarFile.close()`` function, even if the current module is not ``tarfile``. Since this can get ambiguous, if there is more than one possible match, you will get a warning from Sphinx. @@ -515,14 +505,13 @@ The C domain (name **c**) is suited for documentation of C API. .. c:var:: PyObject* PyClass_Type - .. _c-roles: Cross-referencing C constructs ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -The following roles create cross-references to C-language constructs if they are -defined in the documentation: +The following roles create cross-references to C-language constructs if they +are defined in the documentation: .. rst:role:: c:func @@ -544,6 +533,7 @@ defined in the documentation: Reference a C-language variable. + .. _cpp-domain: The C++ Domain @@ -551,12 +541,11 @@ The C++ Domain The C++ domain (name **cpp**) supports documenting C++ projects. - Directives ~~~~~~~~~~ -The following directives are available. All declarations can start with -a visibility statement (``public``, ``private`` or ``protected``). +The following directives are available. All declarations can start with a +visibility statement (``public``, ``private`` or ``protected``). .. rst:directive:: .. cpp:class:: class specifier @@ -585,7 +574,6 @@ a visibility statement (``public``, ``private`` or ``protected``). .. cpp:class:: template \ std::array - .. rst:directive:: .. cpp:function:: (member) function prototype Describe a function or member function, e.g.,:: @@ -624,7 +612,6 @@ a visibility statement (``public``, ``private`` or ``protected``). .. cpp:function:: template<> \ void print(int i) - .. rst:directive:: .. cpp:member:: (member) variable declaration .. cpp:var:: (member) variable declaration @@ -641,13 +628,12 @@ a visibility statement (``public``, ``private`` or ``protected``). .. cpp:member:: template \ constexpr T pi = T(3.1415926535897932385) - .. rst:directive:: .. cpp:type:: typedef declaration .. cpp:type:: name .. cpp:type:: type alias declaration - Describe a type as in a typedef declaration, a type alias declaration, - or simply the name of a type with unspecified type, e.g.,:: + Describe a type as in a typedef declaration, a type alias declaration, or + simply the name of a type with unspecified type, e.g.,:: .. cpp:type:: std::vector MyList @@ -683,15 +669,13 @@ a visibility statement (``public``, ``private`` or ``protected``). .. cpp:type:: template \ MyContainer = std::vector - .. rst:directive:: .. cpp:enum:: unscoped enum declaration .. cpp:enum-struct:: scoped enum declaration .. cpp:enum-class:: scoped enum declaration - Describe a (scoped) enum, possibly with the underlying type specified. - Any enumerators declared inside an unscoped enum will be declared both in the enum scope - and in the parent scope. - Examples:: + Describe a (scoped) enum, possibly with the underlying type specified. Any + enumerators declared inside an unscoped enum will be declared both in the + enum scope and in the parent scope. Examples:: .. cpp:enum:: MyEnum @@ -718,15 +702,14 @@ a visibility statement (``public``, ``private`` or ``protected``). .. cpp:enumerator:: MyEnum::myOtherEnumerator = 42 - .. rst:directive:: .. cpp:concept:: template-parameter-list name .. warning:: The support for concepts is experimental. It is based on the current draft standard and the Concepts Technical Specification. The features may change as they evolve. - Describe a concept. It must have exactly 1 template parameter list. The name may be a - nested name. Example:: + Describe a concept. It must have exactly 1 template parameter list. The name + may be a nested name. Example:: .. cpp:concept:: template std::Iterator @@ -760,10 +743,11 @@ a visibility statement (``public``, ``private`` or ``protected``). **Valid Expressions** - :cpp:expr:`*r`, when :cpp:expr:`r` is dereferenceable. - - :cpp:expr:`++r`, with return type :cpp:expr:`It&`, when :cpp:expr:`r` is incrementable. + - :cpp:expr:`++r`, with return type :cpp:expr:`It&`, when :cpp:expr:`r` + is incrementable. Options -....... +^^^^^^^ Some directives support options: @@ -771,7 +755,6 @@ Some directives support options: - ``:tparam-line-spec:``, for templated declarations. If specified, each template parameter will be rendered on a separate line. - Constrained Templates ~~~~~~~~~~~~~~~~~~~~~ @@ -782,10 +765,11 @@ Constrained Templates .. note:: Sphinx does not currently support ``requires`` clauses. Placeholders -............ +^^^^^^^^^^^^ Declarations may use the name of a concept to introduce constrained template -parameters, or the keyword ``auto`` to introduce unconstrained template parameters:: +parameters, or the keyword ``auto`` to introduce unconstrained template +parameters:: .. cpp:function:: void f(auto &&arg) @@ -797,18 +781,20 @@ parameters, or the keyword ``auto`` to introduce unconstrained template paramete Iterator concept. Template Introductions -...................... +^^^^^^^^^^^^^^^^^^^^^^ -Simple constrained function or class templates can be declared with a -`template introduction` instead of a template parameter list:: +Simple constrained function or class templates can be declared with a `template +introduction` instead of a template parameter list:: .. cpp:function:: std::Iterator{It} void advance(It &it) - A function template with a template parameter constrained to be an Iterator. + A function template with a template parameter constrained to be an + Iterator. .. cpp:class:: std::LessThanComparable{T} MySortedContainer - A class template with a template parameter constrained to be LessThanComparable. + A class template with a template parameter constrained to be + LessThanComparable. They are rendered as follows. @@ -818,20 +804,19 @@ They are rendered as follows. .. cpp:class:: std::LessThanComparable{T} MySortedContainer - A class template with a template parameter constrained to be LessThanComparable. + A class template with a template parameter constrained to be + LessThanComparable. Note however that no checking is performed with respect to parameter compatibility. E.g., ``Iterator{A, B, C}`` will be accepted as an introduction even though it would not be valid C++. - Inline Expressions and Tpes ~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. rst:role:: cpp:expr - A role for inserting a C++ expression or type as inline text. - For example:: + A role for inserting a C++ expression or type as inline text. For example:: .. cpp:var:: int a = 42 @@ -846,34 +831,37 @@ Inline Expressions and Tpes .. cpp:function:: int f(int i) - An expression: :cpp:expr:`a * f(a)`. - A type: :cpp:expr:`const MySortedContainer&`. + An expression: :cpp:expr:`a * f(a)`. A type: :cpp:expr:`const + MySortedContainer&`. Namespacing -~~~~~~~~~~~~~~~~~ +~~~~~~~~~~~ + +Declarations in the C++ domain are as default placed in global scope. The +current scope can be changed using three namespace directives. They manage a +stack declarations where ``cpp:namespace`` resets the stack and changes a given +scope. -Declarations in the C++ domain are as default placed in global scope. -The current scope can be changed using three namespace directives. -They manage a stack declarations where ``cpp:namespace`` resets the stack and -changes a given scope. The ``cpp:namespace-push`` directive changes the scope to a given inner scope of the current one. -The ``cpp:namespace-pop`` directive undos the most recent ``cpp:namespace-push`` -directive. + +The ``cpp:namespace-pop`` directive undoes the most recent +``cpp:namespace-push`` directive. .. rst:directive:: .. cpp:namespace:: scope specification - Changes the current scope for the subsequent objects to the given scope, - and resets the namespace directive stack. - Note that the namespace does not need to correspond to C++ namespaces, - but can end in names of classes, e.g.,:: + Changes the current scope for the subsequent objects to the given scope, and + resets the namespace directive stack. Note that the namespace does not need + to correspond to C++ namespaces, but can end in names of classes, e.g.,:: .. cpp:namespace:: Namespace1::Namespace2::SomeClass::AnInnerClass - All subsequent objects will be defined as if their name were declared with the scope - prepended. The subsequent cross-references will be searched for starting in the current scope. + All subsequent objects will be defined as if their name were declared with + the scope prepended. The subsequent cross-references will be searched for + starting in the current scope. - Using ``NULL``, ``0``, or ``nullptr`` as the scope will change to global scope. + Using ``NULL``, ``0``, or ``nullptr`` as the scope will change to global + scope. A namespace declaration can also be templated, e.g.,:: @@ -884,8 +872,8 @@ directive. .. cpp:function:: std::size_t size() const - declares ``size`` as a member function of the class template ``std::vector``. - Equivalently this could have been declared using:: + declares ``size`` as a member function of the class template + ``std::vector``. Equivalently this could have been declared using:: .. cpp:class:: template \ std::vector @@ -897,7 +885,6 @@ directive. .. cpp:class:: template \ std::vector - .. rst:directive:: .. cpp:namespace-push:: scope specification Change the scope relatively to the current scope. For example, after:: @@ -921,26 +908,25 @@ directive. the current scope will be ``A::B`` (*not* ``A::B::C``). - If no previous ``cpp:namespace-push`` directive has been used, but only a ``cpp:namespace`` - directive, then the current scope will be reset to global scope. - That is, ``.. cpp:namespace:: A::B`` is equivalent to:: + If no previous ``cpp:namespace-push`` directive has been used, but only a + ``cpp:namespace`` directive, then the current scope will be reset to global + scope. That is, ``.. cpp:namespace:: A::B`` is equivalent to:: .. cpp:namespace:: nullptr .. cpp:namespace-push:: A::B - Info field lists ~~~~~~~~~~~~~~~~~ -The C++ directives support the following info fields (see also :ref:`info-field-lists`): +The C++ directives support the following info fields (see also +:ref:`info-field-lists`): * `param`, `parameter`, `arg`, `argument`: Description of a parameter. * `tparam`: Description of a template parameter. * `returns`, `return`: Description of a return value. * `throws`, `throw`, `exception`: Description of a possibly thrown exception. - .. _cpp-roles: Cross-referencing @@ -958,35 +944,34 @@ These roles link to the given declaration types: cpp:enum cpp:enumerator - Reference a C++ declaration by name (see below for details). - The name must be properly qualified relative to the position of the link. + Reference a C++ declaration by name (see below for details). The name must + be properly qualified relative to the position of the link. .. admonition:: Note on References with Templates Parameters/Arguments - Sphinx's syntax to give references a custom title can interfere with - linking to class templates, if nothing follows the closing angle - bracket, i.e. if the link looks like this: ``:cpp:class:`MyClass```. - This is interpreted as a link to ``int`` with a title of ``MyClass``. - In this case, please escape the opening angle bracket with a backslash, - like this: ``:cpp:class:`MyClass\```. + Sphinx's syntax to give references a custom title can interfere with linking + to class templates, if nothing follows the closing angle bracket, i.e. if + the link looks like this: ``:cpp:class:`MyClass```. This is + interpreted as a link to ``int`` with a title of ``MyClass``. In this case, + please escape the opening angle bracket with a backslash, like this: + ``:cpp:class:`MyClass\```. .. admonition:: Note on References to Overloaded Functions - It is currently impossible to link to a specific version of an - overloaded method. Currently the C++ domain is the first domain - that has basic support for overloaded methods and until there is more - data for comparison we don't want to select a bad syntax to reference a - specific overload. Currently Sphinx will link to the first overloaded - version of the method / function. + It is currently impossible to link to a specific version of an overloaded + method. Currently the C++ domain is the first domain that has basic support + for overloaded methods and until there is more data for comparison we don't + want to select a bad syntax to reference a specific overload. Currently + Sphinx will link to the first overloaded version of the method / function. Declarations without template parameters and template arguments -................................................................. +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -For linking to non-templated declarations the name must be a nested name, -e.g., ``f`` or ``MyClass::f``. +For linking to non-templated declarations the name must be a nested name, e.g., +``f`` or ``MyClass::f``. Templated declarations -...................... +^^^^^^^^^^^^^^^^^^^^^^ Assume the following declarations. @@ -998,23 +983,25 @@ Assume the following declarations. .. cpp:class:: template \ Inner -In general the reference must include the template paraemter declarations, e.g., -``template\ Wrapper::Outer`` (:cpp:class:`template\ Wrapper::Outer`). -Currently the lookup only succeed if the template parameter identifiers are equal strings. That is, +In general the reference must include the template paraemter declarations, +e.g., ``template\ Wrapper::Outer`` +(:cpp:class:`template\ Wrapper::Outer`). Currently the lookup +only succeed if the template parameter identifiers are equal strings. That is, ``template\ Wrapper::Outer`` will not work. -The inner class template can not be directly referenced, unless the current namespace -is changed or the following shorthand is used. -If a template parameter list is omitted, then the lookup will assume either a template or a non-template, -but not a partial template specialisation. -This means the following references work. +The inner class template can not be directly referenced, unless the current +namespace is changed or the following shorthand is used. If a template +parameter list is omitted, then the lookup will assume either a template or a +non-template, but not a partial template specialisation. This means the +following references work. - ``Wrapper::Outer`` (:cpp:class:`Wrapper::Outer`) - ``Wrapper::Outer::Inner`` (:cpp:class:`Wrapper::Outer::Inner`) -- ``template\ Wrapper::Outer::Inner`` (:cpp:class:`template\ Wrapper::Outer::Inner`) +- ``template\ Wrapper::Outer::Inner`` + (:cpp:class:`template\ Wrapper::Outer::Inner`) (Full) Template Specialisations -................................ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Assume the following declarations. @@ -1033,25 +1020,27 @@ Assume the following declarations. .. cpp:class:: template<> \ Inner -In general the reference must include a template parameter list for each template argument list. -The full specialisation above can therefore be referenced with ``template\<> Outer\`` (:cpp:class:`template\<> Outer\`) -and ``template\<> template\<> Outer\::Inner\`` (:cpp:class:`template\<> template\<> Outer\::Inner\`). -As a shorthand the empty template parameter list can be omitted, e.g., ``Outer\`` (:cpp:class:`Outer\`) -and ``Outer\::Inner\`` (:cpp:class:`Outer\::Inner\`). - +In general the reference must include a template parameter list for each +template argument list. The full specialisation above can therefore be +referenced with ``template\<> Outer\`` (:cpp:class:`template\<> +Outer\`) and ``template\<> template\<> Outer\::Inner\`` +(:cpp:class:`template\<> template\<> Outer\::Inner\`). As a +shorthand the empty template parameter list can be omitted, e.g., +``Outer\`` (:cpp:class:`Outer\`) and ``Outer\::Inner\`` +(:cpp:class:`Outer\::Inner\`). Partial Template Specialisations -................................. +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Assume the following declaration. .. cpp:class:: template \ Outer -References to partial specialisations must always include the template parameter lists, e.g., -``template\ Outer\`` (:cpp:class:`template\ Outer\`). -Currently the lookup only succeed if the template parameter identifiers are equal strings. - +References to partial specialisations must always include the template +parameter lists, e.g., ``template\ Outer\`` +(:cpp:class:`template\ Outer\`). Currently the lookup only +succeed if the template parameter identifiers are equal strings. Configuration Variables ~~~~~~~~~~~~~~~~~~~~~~~ @@ -1073,8 +1062,8 @@ There is a set of directives allowing documenting command-line programs: .. rst:directive:: .. option:: name args, name args, ... - Describes a command line argument or switch. Option argument names should be - enclosed in angle brackets. Examples:: + Describes a command line argument or switch. Option argument names should + be enclosed in angle brackets. Examples:: .. option:: dest_dir @@ -1092,8 +1081,8 @@ There is a set of directives allowing documenting command-line programs: .. rst:directive:: .. envvar:: name - Describes an environment variable that the documented code or program uses or - defines. Referencable by :rst:role:`envvar`. + Describes an environment variable that the documented code or program uses + or defines. Referencable by :rst:role:`envvar`. .. rst:directive:: .. program:: name @@ -1120,12 +1109,11 @@ There is a set of directives allowing documenting command-line programs: then ``:option:`rm -r``` would refer to the first option, while ``:option:`svn -r``` would refer to the second one. - The program name may contain spaces (in case you want to document subcommands - like ``svn add`` and ``svn commit`` separately). + The program name may contain spaces (in case you want to document + subcommands like ``svn add`` and ``svn commit`` separately). .. versionadded:: 0.5 - There is also a very generic object description directive, which is not tied to any domain: @@ -1154,9 +1142,9 @@ The JavaScript domain (name **js**) provides the following directives: :rst:dir:`py:class` would, for example. By default, this directive will create a linkable entity and will cause an - entry in the global module index, unless the ``noindex`` option is specified. - If this option is specified, the directive will only update the current - module name. + entry in the global module index, unless the ``noindex`` option is + specified. If this option is specified, the directive will only update the + current module name. To clear the current module, set the module name to ``null`` or ``None`` @@ -1165,8 +1153,8 @@ The JavaScript domain (name **js**) provides the following directives: .. rst:directive:: .. js:function:: name(signature) Describes a JavaScript function or method. If you want to describe - arguments as optional use square brackets as :ref:`documented - ` for Python signatures. + arguments as optional use square brackets as :ref:`documented ` + for Python signatures. You can use fields to give more details about arguments and their expected types, errors which may be thrown by the function, and the value being @@ -1196,15 +1184,15 @@ The JavaScript domain (name **js**) provides the following directives: .. rst:directive:: .. js:method:: name(signature) - This directive is an alias for :rst:dir:`js:function`, however it describes a - function that is implemented as a method on a class object. + This directive is an alias for :rst:dir:`js:function`, however it describes + a function that is implemented as a method on a class object. .. versionadded:: 1.6 .. rst:directive:: .. js:class:: name - Describes a constructor that creates an object. This is basically like - a function but will show up with a `class` prefix:: + Describes a constructor that creates an object. This is basically like a + function but will show up with a `class` prefix:: .. js:class:: MyAnimal(name[, age]) @@ -1297,7 +1285,6 @@ currently Ada_, CoffeeScript_, Erlang_, HTTP_, Lasso_, MATLAB_, PHP_, and Ruby_ domains. Also available are domains for `Chapel`_, `Common Lisp`_, dqn_, Go_, Jinja_, Operation_, and Scala_. - .. _sphinx-contrib: https://bitbucket.org/birkenfeld/sphinx-contrib/ .. _Ada: https://pypi.python.org/pypi/sphinxcontrib-adadomain diff --git a/doc/usage/restructuredtext/field-lists.rst b/doc/usage/restructuredtext/field-lists.rst new file mode 100644 index 000000000..10ded3ea4 --- /dev/null +++ b/doc/usage/restructuredtext/field-lists.rst @@ -0,0 +1,47 @@ +.. highlightlang:: rst + +=========== +Field Lists +=========== + +:ref:`As previously discussed `, field lists are sequences of +fields marked up like this:: + + :fieldname: Field content + +Sphinx provides custom behavior for bibliographic fields compared to docutils. + +.. _metadata: + +File-wide metadata +------------------ + +A field list near the top of a file is normally parsed by docutils as the +*docinfo* which is generally used to record the author, date of publication and +other metadata. However, in Sphinx, a field list preceding any other markup is +moved from the *docinfo* to the Sphinx environment as document metadata and is +not displayed in the output; a field list appearing after the document title +will be part of the *docinfo* as normal and will be displayed in the output. + +At the moment, these metadata fields are recognized: + +``tocdepth`` + The maximum depth for a table of contents of this file. :: + + :tocdepth: 2 + + .. versionadded:: 0.4 + +``nocomments`` + If set, the web application won't display a comment form for a page + generated from this source file. :: + + :nocomments: + +``orphan`` + If set, warnings about this file not being included in any toctree will be + suppressed. :: + + :orphan: + + .. versionadded:: 1.0 diff --git a/doc/usage/restructuredtext/index.rst b/doc/usage/restructuredtext/index.rst new file mode 100644 index 000000000..777103ebc --- /dev/null +++ b/doc/usage/restructuredtext/index.rst @@ -0,0 +1,22 @@ +================ +reStructuredText +================ + +reStructuredText (reST) is the default plaintext markup language used by both +Docutils and Sphinx. Docutils provides the basic reStructuredText syntax, while +Sphinx extends this to support additional functionality. + +The below guides go through the most important aspects of reST. For the +authoritative reStructuredText reference, refer to the `docutils +documentation`__. + +__ http://docutils.sourceforge.net/rst.html + +.. toctree:: + :maxdepth: 2 + + basics + roles + directives + field-lists + domains diff --git a/doc/markup/inline.rst b/doc/usage/restructuredtext/roles.rst similarity index 86% rename from doc/markup/inline.rst rename to doc/usage/restructuredtext/roles.rst index c8dfb6ff7..7e68b3e2a 100644 --- a/doc/markup/inline.rst +++ b/doc/usage/restructuredtext/roles.rst @@ -1,9 +1,8 @@ -.. highlight:: rest +.. highlight:: rst -.. _inline-markup: - -Inline markup -============= +===== +Roles +===== Sphinx uses interpreted text roles to insert semantic markup into documents. They are written as ``:rolename:`content```. @@ -16,21 +15,21 @@ They are written as ``:rolename:`content```. :rst:role:`any` role to find anything or the :rst:role:`py:obj` role to find Python objects are very useful for this. -See :ref:`domains` for roles added by domains. +See :doc:`/usage/restructuredtext/domains` for roles added by domains. .. _xref-syntax: Cross-referencing syntax -~~~~~~~~~~~~~~~~~~~~~~~~ +------------------------ Cross-references are generated by many semantic interpreted text roles. -Basically, you only need to write ``:role:`target```, and a link will be created -to the item named *target* of the type indicated by *role*. The link's text -will be the same as *target*. +Basically, you only need to write ``:role:`target```, and a link will be +created to the item named *target* of the type indicated by *role*. The link's +text will be the same as *target*. -There are some additional facilities, however, that make cross-referencing roles -more versatile: +There are some additional facilities, however, that make cross-referencing +roles more versatile: * You may supply an explicit title and reference target, like in reST direct hyperlinks: ``:role:`title ``` will refer to *target*, but the link @@ -50,7 +49,7 @@ more versatile: .. _any-role: Cross-referencing anything --------------------------- +^^^^^^^^^^^^^^^^^^^^^^^^^^ .. rst:role:: any @@ -90,9 +89,8 @@ Cross-referencing anything :mod:`~sphinx.ext.intersphinx` extension: when no local cross-reference is found, all object types of intersphinx inventories are also searched. - Cross-referencing objects -------------------------- +^^^^^^^^^^^^^^^^^^^^^^^^^ These roles are described with their respective domains: @@ -106,7 +104,7 @@ These roles are described with their respective domains: .. _ref-role: Cross-referencing arbitrary locations -------------------------------------- +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. rst:role:: ref @@ -116,7 +114,7 @@ Cross-referencing arbitrary locations refer to labels: * If you place a label directly before a section title, you can reference to - it with ``:ref:`label-name```. Example:: + it with ``:ref:`label-name```. For example:: .. _my-reference-label: @@ -127,11 +125,11 @@ Cross-referencing arbitrary locations It refers to the section itself, see :ref:`my-reference-label`. - The ``:ref:`` role would then generate a link to the section, with the link - title being "Section to cross-reference". This works just as well when - section and reference are in different source files. + The ``:ref:`` role would then generate a link to the section, with the + link title being "Section to cross-reference". This works just as well + when section and reference are in different source files. - Automatic labels also work with figures: given :: + Automatic labels also work with figures. For example:: .. _my-figure: @@ -139,8 +137,8 @@ Cross-referencing arbitrary locations Figure caption - a reference ``:ref:`my-figure``` would insert a reference to the figure - with link text "Figure caption". + In this case, a reference ``:ref:`my-figure``` would insert a reference + to the figure with link text "Figure caption". The same works for tables that are given an explicit caption using the :dudir:`table` directive. @@ -151,17 +149,17 @@ Cross-referencing arbitrary locations .. note:: - Reference labels must start with an underscore. When referencing a - label, the underscore must be omitted (see examples above). + Reference labels must start with an underscore. When referencing a label, + the underscore must be omitted (see examples above). Using :rst:role:`ref` is advised over standard reStructuredText links to sections (like ```Section title`_``) because it works across files, when - section headings are changed, and for all builders that support - cross-references. + section headings are changed, will raise warnings if incorrect, and works + for all builders that support cross-references. Cross-referencing documents ---------------------------- +^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. versionadded:: 0.6 @@ -180,7 +178,7 @@ There is also a way to directly link to documents: Referencing downloadable files ------------------------------- +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. versionadded:: 0.6 @@ -213,7 +211,7 @@ Referencing downloadable files See :download:`this example script <../example.py>`. Cross-referencing figures by figure number ------------------------------------------- +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. versionadded:: 1.3 @@ -238,7 +236,7 @@ Cross-referencing figures by figure number so this role inserts not a reference but the label or the link text. Cross-referencing other items of interest ------------------------------------------ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The following roles do possibly create a cross-reference, but do not refer to objects: @@ -280,10 +278,10 @@ The following role creates a cross-reference to a term in a Other semantic markup -~~~~~~~~~~~~~~~~~~~~~ +--------------------- -The following roles don't do anything special except formatting the text -in a different style: +The following roles don't do anything special except formatting the text in a +different style: .. rst:role:: abbr @@ -331,22 +329,22 @@ in a different style: .. rst: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 + 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```. .. rst: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```. + 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```. .. rst:role:: makevar @@ -354,9 +352,9 @@ in a different style: .. rst:role:: manpage - A reference to a Unix manual page including the section, - e.g. ``:manpage:`ls(1)```. Creates a hyperlink to an external site - rendering the manpage if :confval:`manpages_url` is defined. + A reference to a Unix manual page including the section, e.g. + ``:manpage:`ls(1)```. Creates a hyperlink to an external site rendering the + manpage if :confval:`manpages_url` is defined. .. rst:role:: menuselection @@ -370,8 +368,8 @@ in a different style: :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 + 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. ``menuselection`` also supports ampersand accelerators just like @@ -386,6 +384,8 @@ in a different style: The name of a Usenet newsgroup. +.. todo:: Is this not part of the standard domain? + .. rst:role:: program The name of an executable program. This may differ from the file name for @@ -432,7 +432,7 @@ the standard reST markup for that purpose. .. _default-substitutions: Substitutions -~~~~~~~~~~~~~ +------------- The documentation system provides three substitutions that are defined by default. They are set in the build configuration file. diff --git a/sphinx/application.py b/sphinx/application.py index d84301dd6..599552d63 100644 --- a/sphinx/application.py +++ b/sphinx/application.py @@ -515,14 +515,17 @@ class Sphinx(object): # registering addon parts - def add_builder(self, builder): - # type: (Type[Builder]) -> None + def add_builder(self, builder, override=False): + # type: (Type[Builder], bool) -> None """Register a new builder. *builder* must be a class that inherits from :class:`~sphinx.builders.Builder`. + + .. versionchanged:: 1.8 + Add *override* keyword. """ - self.registry.add_builder(builder) + self.registry.add_builder(builder, override=override) # TODO(stephenfin): Describe 'types' parameter def add_config_value(self, name, default, rebuild, types=()): @@ -567,8 +570,8 @@ class Sphinx(object): logger.debug('[app] adding event: %r', name) self.events.add(name) - def set_translator(self, name, translator_class): - # type: (unicode, Type[nodes.NodeVisitor]) -> None + def set_translator(self, name, translator_class, override=False): + # type: (unicode, Type[nodes.NodeVisitor], bool) -> None """Register or override a Docutils translator class. This is used to register a custom output translator or to replace a @@ -576,11 +579,13 @@ class Sphinx(object): and define custom nodes for the translator (see :meth:`add_node`). .. versionadded:: 1.3 + .. versionchanged:: 1.8 + Add *override* keyword. """ - self.registry.add_translator(name, translator_class) + self.registry.add_translator(name, translator_class, override=override) - def add_node(self, node, **kwds): - # type: (nodes.Node, Any) -> None + def add_node(self, node, override=False, **kwds): + # type: (nodes.Node, bool, Any) -> None """Register a Docutils node class. This is necessary for Docutils internals. It may also be used in the @@ -611,7 +616,7 @@ class Sphinx(object): Added the support for keyword arguments giving visit functions. """ logger.debug('[app] adding node: %r', (node, kwds)) - if not kwds.pop('override', False) and docutils.is_node_registered(node): + if not override and docutils.is_node_registered(node): logger.warning(__('while setting up extension %s: node class %r is ' 'already registered, its visitors will be overridden'), self._setting_up_extension, node.__name__, @@ -619,8 +624,8 @@ class Sphinx(object): docutils.register_node(node) self.registry.add_translation_handlers(node, **kwds) - def add_enumerable_node(self, node, figtype, title_getter=None, **kwds): - # type: (nodes.Node, unicode, TitleGetter, Any) -> None + def add_enumerable_node(self, node, figtype, title_getter=None, override=False, **kwds): + # type: (nodes.Node, unicode, TitleGetter, bool, Any) -> None """Register a Docutils node class as a numfig target. Sphinx numbers the node automatically. And then the users can refer it @@ -644,8 +649,8 @@ class Sphinx(object): .. versionadded:: 1.4 """ - self.registry.add_enumerable_node(node, figtype, title_getter) - self.add_node(node, **kwds) + self.registry.add_enumerable_node(node, figtype, title_getter, override=override) + self.add_node(node, override=override, **kwds) @property def enumerable_nodes(self): @@ -655,8 +660,8 @@ class Sphinx(object): RemovedInSphinx30Warning) return self.registry.enumerable_nodes - def add_directive(self, name, obj, content=None, arguments=None, **options): - # type: (unicode, Any, bool, Tuple[int, int, bool], Any) -> None + def add_directive(self, name, obj, content=None, arguments=None, override=False, **options): # NOQA + # type: (unicode, Any, bool, Tuple[int, int, bool], bool, Any) -> None """Register a Docutils directive. *name* must be the prospective directive name. There are two possible @@ -667,7 +672,7 @@ class Sphinx(object): function and determine whether the directive has content, arguments and options, respectively. **This style is deprecated.** - - In the docutils 0.5 style, *directiveclass* is the directive class. + - In the docutils 0.5 style, *obj* is the directive class. It must already have attributes named *has_content*, *required_arguments*, *optional_arguments*, *final_argument_whitespace* and *option_spec* that correspond to the @@ -683,21 +688,33 @@ class Sphinx(object): .. code-block:: python - from docutils.parsers.rst import directives - add_directive('literalinclude', literalinclude_directive, - content = 0, arguments = (1, 0, 0), - linenos = directives.flag, - language = directives.unchanged, - encoding = directives.encoding) + from docutils.parsers.rst import Directive, directives + + class LiteralIncludeDirective(Directive): + has_content = True + required_arguments = 1 + optional_arguments = 0 + final_argument_whitespace = True + option_spec = { + 'class': directives.class_option, + 'name': directives.unchanged, + } + + def run(self): + ... + + add_directive('literalinclude', LiteralIncludeDirective) .. versionchanged:: 0.6 Docutils 0.5-style directive classes are now supported. .. deprecated:: 1.8 Docutils 0.4-style (function based) directives support is deprecated. + .. versionchanged:: 1.8 + Add *override* keyword. """ logger.debug('[app] adding directive: %r', (name, obj, content, arguments, options)) - if name in directives._directives: + if name in directives._directives and not override: logger.warning(__('while setting up extension %s: directive %r is ' 'already registered, it will be overridden'), self._setting_up_extension[-1], name, @@ -709,36 +726,41 @@ class Sphinx(object): else: directives.register_directive(name, obj) - def add_role(self, name, role): - # type: (unicode, Any) -> None + def add_role(self, name, role, override=False): + # type: (unicode, Any, bool) -> None """Register a Docutils role. *name* must be the role name that occurs in the source, *role* the role function. Refer to the `Docutils documentation `_ for more information. + + .. versionchanged:: 1.8 + Add *override* keyword. """ logger.debug('[app] adding role: %r', (name, role)) - if name in roles._roles: + if name in roles._roles and not override: logger.warning(__('while setting up extension %s: role %r is ' 'already registered, it will be overridden'), self._setting_up_extension[-1], name, type='app', subtype='add_role') roles.register_local_role(name, role) - def add_generic_role(self, name, nodeclass): - # type: (unicode, Any) -> None + def add_generic_role(self, name, nodeclass, override=False): + # type: (unicode, Any, bool) -> None """Register a generic Docutils role. Register a Docutils role that does nothing but wrap its contents in the node given by *nodeclass*. .. versionadded:: 0.6 + .. versionchanged:: 1.8 + Add *override* keyword. """ # Don't use ``roles.register_generic_role`` because it uses # ``register_canonical_role``. logger.debug('[app] adding generic role: %r', (name, nodeclass)) - if name in roles._roles: + if name in roles._roles and not override: logger.warning(__('while setting up extension %s: role %r is ' 'already registered, it will be overridden'), self._setting_up_extension[-1], name, @@ -746,16 +768,18 @@ class Sphinx(object): role = roles.GenericRole(name, nodeclass) roles.register_local_role(name, role) - def add_domain(self, domain): - # type: (Type[Domain]) -> None + def add_domain(self, domain, override=False): + # type: (Type[Domain], bool) -> None """Register a domain. Make the given *domain* (which must be a class; more precisely, a subclass of :class:`~sphinx.domains.Domain`) known to Sphinx. .. versionadded:: 1.0 + .. versionchanged:: 1.8 + Add *override* keyword. """ - self.registry.add_domain(domain) + self.registry.add_domain(domain, override=override) def override_domain(self, domain): # type: (Type[Domain]) -> None @@ -766,48 +790,60 @@ class Sphinx(object): of the existing one. .. versionadded:: 1.0 + .. deprecated:: 1.8 + Integrated to :meth:`add_domain`. """ - self.registry.override_domain(domain) + warnings.warn('app.override_domain() is deprecated. ' + 'Use app.add_domain() with override option instead.', + RemovedInSphinx30Warning) + self.registry.add_domain(domain, override=True) - def add_directive_to_domain(self, domain, name, obj, - has_content=None, argument_spec=None, **option_spec): - # type: (unicode, unicode, Any, bool, Any, Any) -> None + def add_directive_to_domain(self, domain, name, obj, has_content=None, argument_spec=None, + override=False, **option_spec): + # type: (unicode, unicode, Any, bool, Any, bool, Any) -> None """Register a Docutils directive in a domain. Like :meth:`add_directive`, but the directive is added to the domain named *domain*. .. versionadded:: 1.0 + .. versionchanged:: 1.8 + Add *override* keyword. """ self.registry.add_directive_to_domain(domain, name, obj, - has_content, argument_spec, **option_spec) + has_content, argument_spec, override=override, + **option_spec) - def add_role_to_domain(self, domain, name, role): - # type: (unicode, unicode, Union[RoleFunction, XRefRole]) -> None + def add_role_to_domain(self, domain, name, role, override=False): + # type: (unicode, unicode, Union[RoleFunction, XRefRole], bool) -> None """Register a Docutils role in a domain. Like :meth:`add_role`, but the role is added to the domain named *domain*. .. versionadded:: 1.0 + .. versionchanged:: 1.8 + Add *override* keyword. """ - self.registry.add_role_to_domain(domain, name, role) + self.registry.add_role_to_domain(domain, name, role, override=override) - def add_index_to_domain(self, domain, index): - # type: (unicode, Type[Index]) -> None + def add_index_to_domain(self, domain, index, override=False): + # type: (unicode, Type[Index], bool) -> None """Register a custom index for a domain. Add a custom *index* class to the domain named *domain*. *index* must be a subclass of :class:`~sphinx.domains.Index`. .. versionadded:: 1.0 + .. versionchanged:: 1.8 + Add *override* keyword. """ self.registry.add_index_to_domain(domain, index) def add_object_type(self, directivename, rolename, indextemplate='', parse_node=None, ref_nodeclass=None, objname='', - doc_field_types=[]): - # type: (unicode, unicode, unicode, Callable, nodes.Node, unicode, List) -> None + doc_field_types=[], override=False): + # type: (unicode, unicode, unicode, Callable, nodes.Node, unicode, List, bool) -> None """Register a new object type. This method is a very convenient way to add a new :term:`object` type @@ -862,9 +898,13 @@ class Sphinx(object): This method is also available under the deprecated alias :meth:`add_description_unit`. + + .. versionchanged:: 1.8 + Add *override* keyword. """ self.registry.add_object_type(directivename, rolename, indextemplate, parse_node, - ref_nodeclass, objname, doc_field_types) + ref_nodeclass, objname, doc_field_types, + override=override) def add_description_unit(self, directivename, rolename, indextemplate='', parse_node=None, ref_nodeclass=None, objname='', @@ -882,8 +922,8 @@ class Sphinx(object): ref_nodeclass, objname, doc_field_types) def add_crossref_type(self, directivename, rolename, indextemplate='', - ref_nodeclass=None, objname=''): - # type: (unicode, unicode, unicode, nodes.Node, unicode) -> None + ref_nodeclass=None, objname='', override=False): + # type: (unicode, unicode, unicode, nodes.Node, unicode, bool) -> None """Register a new crossref object type. This method is very similar to :meth:`add_object_type` except that the @@ -909,9 +949,13 @@ class Sphinx(object): (Of course, the element following the ``topic`` directive needn't be a section.) + + .. versionchanged:: 1.8 + Add *override* keyword. """ self.registry.add_crossref_type(directivename, rolename, - indextemplate, ref_nodeclass, objname) + indextemplate, ref_nodeclass, objname, + override=override) def add_transform(self, transform): # type: (Type[Transform]) -> None @@ -1066,25 +1110,29 @@ class Sphinx(object): assert issubclass(cls, SearchLanguage) languages[cls.lang] = cls - def add_source_suffix(self, suffix, filetype): - # type: (unicode, unicode) -> None + def add_source_suffix(self, suffix, filetype, override=False): + # type: (unicode, unicode, bool) -> None """Register a suffix of source files. Same as :confval:`source_suffix`. The users can override this using the setting. - """ - self.registry.add_source_suffix(suffix, filetype) - def add_source_parser(self, *args): - # type: (Any) -> None + .. versionadded:: 1.8 + """ + self.registry.add_source_suffix(suffix, filetype, override=override) + + def add_source_parser(self, *args, **kwargs): + # type: (Any, Any) -> None """Register a parser class. .. versionadded:: 1.4 .. versionchanged:: 1.8 *suffix* argument is deprecated. It only accepts *parser* argument. Use :meth:`add_source_suffix` API to register suffix instead. + .. versionchanged:: 1.8 + Add *override* keyword. """ - self.registry.add_source_parser(*args) + self.registry.add_source_parser(*args, **kwargs) def add_env_collector(self, collector): # type: (Type[EnvironmentCollector]) -> None diff --git a/sphinx/registry.py b/sphinx/registry.py index 0d23e8368..ab4cfce70 100644 --- a/sphinx/registry.py +++ b/sphinx/registry.py @@ -113,12 +113,12 @@ class SphinxComponentRegistry(object): #: additional transforms; list of transforms self.transforms = [] # type: List[Type[Transform]] - def add_builder(self, builder): - # type: (Type[Builder]) -> None + def add_builder(self, builder, override=False): + # type: (Type[Builder], bool) -> None logger.debug('[app] adding builder: %r', builder) if not hasattr(builder, 'name'): raise ExtensionError(__('Builder class %s has no "name" attribute') % builder) - if builder.name in self.builders: + if builder.name in self.builders and not override: raise ExtensionError(__('Builder %r already exists (in module %s)') % (builder.name, self.builders[builder.name].__module__)) self.builders[builder.name] = builder @@ -145,10 +145,10 @@ class SphinxComponentRegistry(object): return self.builders[name](app) - def add_domain(self, domain): - # type: (Type[Domain]) -> None + def add_domain(self, domain, override=False): + # type: (Type[Domain], bool) -> None logger.debug('[app] adding domain: %r', domain) - if domain.name in self.domains: + if domain.name in self.domains and not override: raise ExtensionError(__('domain %s already registered') % domain.name) self.domains[domain.name] = domain @@ -172,48 +172,54 @@ class SphinxComponentRegistry(object): def override_domain(self, domain): # type: (Type[Domain]) -> None - logger.debug('[app] overriding domain: %r', domain) - if domain.name not in self.domains: - raise ExtensionError(__('domain %s not yet registered') % domain.name) - if not issubclass(domain, self.domains[domain.name]): - raise ExtensionError(__('new domain not a subclass of registered %s ' - 'domain') % domain.name) - self.domains[domain.name] = domain + warnings.warn('registry.override_domain() is deprecated. ' + 'Use app.add_domain(domain, override=True) instead.', + RemovedInSphinx30Warning) + self.add_domain(domain, override=True) - def add_directive_to_domain(self, domain, name, obj, - has_content=None, argument_spec=None, **option_spec): - # type: (unicode, unicode, Any, bool, Any, Any) -> None + def add_directive_to_domain(self, domain, name, obj, has_content=None, argument_spec=None, + override=False, **option_spec): + # type: (unicode, unicode, Any, bool, Any, bool, Any) -> None logger.debug('[app] adding directive to domain: %r', (domain, name, obj, has_content, argument_spec, option_spec)) if domain not in self.domains: raise ExtensionError(__('domain %s not yet registered') % domain) directives = self.domain_directives.setdefault(domain, {}) + if name in directives and not override: + raise ExtensionError(__('The %r directive is already registered to %d domain') % + (name, domain)) if not isclass(obj) or not issubclass(obj, Directive): directives[name] = directive_helper(obj, has_content, argument_spec, **option_spec) else: directives[name] = obj - def add_role_to_domain(self, domain, name, role): - # type: (unicode, unicode, Union[RoleFunction, XRefRole]) -> None + def add_role_to_domain(self, domain, name, role, override=False): + # type: (unicode, unicode, Union[RoleFunction, XRefRole], bool) -> None logger.debug('[app] adding role to domain: %r', (domain, name, role)) if domain not in self.domains: raise ExtensionError(__('domain %s not yet registered') % domain) roles = self.domain_roles.setdefault(domain, {}) + if name in roles and not override: + raise ExtensionError(__('The %r role is already registered to %d domain') % + (name, domain)) roles[name] = role - def add_index_to_domain(self, domain, index): - # type: (unicode, Type[Index]) -> None + def add_index_to_domain(self, domain, index, override=False): + # type: (unicode, Type[Index], bool) -> None logger.debug('[app] adding index to domain: %r', (domain, index)) if domain not in self.domains: raise ExtensionError(__('domain %s not yet registered') % domain) indices = self.domain_indices.setdefault(domain, []) + if index in indices and not override: + raise ExtensionError(__('The %r index is already registered to %d domain') % + (index.name, domain)) indices.append(index) def add_object_type(self, directivename, rolename, indextemplate='', parse_node=None, ref_nodeclass=None, objname='', - doc_field_types=[]): - # type: (unicode, unicode, unicode, Callable, nodes.Node, unicode, List) -> None + doc_field_types=[], override=False): + # type: (unicode, unicode, unicode, Callable, nodes.Node, unicode, List, bool) -> None logger.debug('[app] adding object type: %r', (directivename, rolename, indextemplate, parse_node, ref_nodeclass, objname, doc_field_types)) @@ -229,11 +235,14 @@ class SphinxComponentRegistry(object): self.add_role_to_domain('std', rolename, XRefRole(innernodeclass=ref_nodeclass)) object_types = self.domain_object_types.setdefault('std', {}) + if directivename in object_types and not override: + raise ExtensionError(__('The %r object_type is already registered') % + directivename) object_types[directivename] = ObjType(objname or directivename, rolename) def add_crossref_type(self, directivename, rolename, indextemplate='', - ref_nodeclass=None, objname=''): - # type: (unicode, unicode, unicode, nodes.Node, unicode) -> None + ref_nodeclass=None, objname='', override=False): + # type: (unicode, unicode, unicode, nodes.Node, unicode, bool) -> None logger.debug('[app] adding crossref type: %r', (directivename, rolename, indextemplate, ref_nodeclass, objname)) @@ -246,18 +255,21 @@ class SphinxComponentRegistry(object): self.add_role_to_domain('std', rolename, XRefRole(innernodeclass=ref_nodeclass)) object_types = self.domain_object_types.setdefault('std', {}) + if directivename in object_types and not override: + raise ExtensionError(__('The %r crossref_type is already registered') % + directivename) object_types[directivename] = ObjType(objname or directivename, rolename) - def add_source_suffix(self, suffix, filetype): - # type: (unicode, unicode) -> None + def add_source_suffix(self, suffix, filetype, override=False): + # type: (unicode, unicode, bool) -> None logger.debug('[app] adding source_suffix: %r, %r', suffix, filetype) - if suffix in self.source_suffix: + if suffix in self.source_suffix and not override: raise ExtensionError(__('source_parser for %r is already registered') % suffix) else: self.source_suffix[suffix] = filetype - def add_source_parser(self, *args): - # type: (Any) -> None + def add_source_parser(self, *args, **kwargs): + # type: (Any, bool) -> None logger.debug('[app] adding search source_parser: %r', args) if len(args) == 1: # new sytle arguments: (source_parser) @@ -281,7 +293,7 @@ class SphinxComponentRegistry(object): # create a map from filetype to parser for filetype in parser.supported: - if filetype in self.source_parsers: + if filetype in self.source_parsers and not kwargs.get('override'): raise ExtensionError(__('source_parser for %r is already registered') % filetype) else: @@ -312,10 +324,10 @@ class SphinxComponentRegistry(object): parser.set_application(app) return parser - def add_source_input(self, input_class): - # type: (Type[Input]) -> None + def add_source_input(self, input_class, override=False): + # type: (Type[Input], bool) -> None for filetype in input_class.supported: - if filetype in self.source_inputs: + if filetype in self.source_inputs and not override: raise ExtensionError(__('source_input for %r is already registered') % filetype) self.source_inputs[filetype] = input_class @@ -331,9 +343,11 @@ class SphinxComponentRegistry(object): except KeyError: raise SphinxError(__('source_input for %s not registered') % filetype) - def add_translator(self, name, translator): - # type: (unicode, Type[nodes.NodeVisitor]) -> None + def add_translator(self, name, translator, override=False): + # type: (unicode, Type[nodes.NodeVisitor], bool) -> None logger.debug('[app] Change of translator for the %s builder.' % name) + if name in self.translators and not override: + raise ExtensionError(__('Translatoro for %r already exists') % name) self.translators[name] = translator def add_translation_handlers(self, node, **kwargs): @@ -403,9 +417,11 @@ class SphinxComponentRegistry(object): logger.debug('[app] adding latex package: %r', name) self.latex_packages.append((name, options)) - def add_enumerable_node(self, node, figtype, title_getter=None): - # type: (nodes.Node, unicode, TitleGetter) -> None + def add_enumerable_node(self, node, figtype, title_getter=None, override=False): + # type: (nodes.Node, unicode, TitleGetter, bool) -> None logger.debug('[app] adding enumerable node: (%r, %r, %r)', node, figtype, title_getter) + if node in self.enumerable_nodes and not override: + raise ExtensionError(__('enumerable_node %r already registered') % node) self.enumerable_nodes[node] = (figtype, title_getter) def load_extension(self, app, extname): diff --git a/sphinx/templates/latex/latex.tex_t b/sphinx/templates/latex/latex.tex_t index 34086b1cb..0ea75557f 100644 --- a/sphinx/templates/latex/latex.tex_t +++ b/sphinx/templates/latex/latex.tex_t @@ -25,6 +25,7 @@ <%= fncychap %> \usepackage<%= sphinxpkgoptions %>{sphinx} <%= sphinxsetup %> +<%= fvset %> <%= geometry %> <%= usepackages %> <%= hyperref %> diff --git a/sphinx/texinputs/sphinx.sty b/sphinx/texinputs/sphinx.sty index e323b2a5d..17aa6644d 100644 --- a/sphinx/texinputs/sphinx.sty +++ b/sphinx/texinputs/sphinx.sty @@ -6,7 +6,7 @@ % \NeedsTeXFormat{LaTeX2e}[1995/12/01] -\ProvidesPackage{sphinx}[2018/03/11 v1.7.2 LaTeX package (Sphinx markup)] +\ProvidesPackage{sphinx}[2018/03/28 v1.8 LaTeX package (Sphinx markup)] % provides \ltx@ifundefined % (many packages load ltxcmds: graphicx does for pdftex and lualatex but @@ -164,7 +164,6 @@ } % For highlighted code. \RequirePackage{fancyvrb} -\fvset{fontsize=\small} \define@key{FV}{hllines}{\def\sphinx@verbatim@checkifhl##1{\in@{, ##1,}{#1}}} % For hyperlinked footnotes in tables; also for gathering footnotes from % topic and warning blocks. Also to allow code-blocks in footnotes. diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py index caaba92e2..c98411f42 100644 --- a/sphinx/writers/latex.py +++ b/sphinx/writers/latex.py @@ -61,6 +61,7 @@ DEFAULT_SETTINGS = { 'maxlistdepth': '', 'sphinxpkgoptions': '', 'sphinxsetup': '', + 'fvset': '\\fvset{fontsize=\\small}', 'passoptionstopackages': '', 'geometry': '\\usepackage{geometry}', 'inputenc': '', @@ -132,6 +133,7 @@ ADDITIONAL_SETTINGS = { 'fontpkg': '', 'utf8extra': ('\\catcode`^^^^00a0\\active\\protected\\def^^^^00a0' '{\\leavevmode\\nobreak\\ }'), + 'fvset': '\\fvset{fontsize=auto}', }, 'lualatex': { 'latex_engine': 'lualatex', @@ -141,6 +143,7 @@ ADDITIONAL_SETTINGS = { 'fontpkg': '', 'utf8extra': ('\\catcode`^^^^00a0\\active\\protected\\def^^^^00a0' '{\\leavevmode\\nobreak\\ }'), + 'fvset': '\\fvset{fontsize=auto}', }, 'platex': { 'latex_engine': 'platex', diff --git a/tests/test_application.py b/tests/test_application.py index aa598b00a..efd55c487 100644 --- a/tests/test_application.py +++ b/tests/test_application.py @@ -58,28 +58,6 @@ def test_extension_in_blacklist(app, status, warning): assert msg.startswith("WARNING: the extension 'sphinxjp.themecore' was") -def test_domain_override(app, status, warning): - class A(Domain): - name = 'foo' - - class B(A): - name = 'foo' - - class C(Domain): - name = 'foo' - - # No domain know named foo. - with pytest.raises(ExtensionError) as excinfo: - app.override_domain(A) - assert 'domain foo not yet registered' in str(excinfo.value) - - assert app.add_domain(A) is None - assert app.override_domain(B) is None - with pytest.raises(ExtensionError) as excinfo: - app.override_domain(C) - assert 'new domain not a subclass of registered foo domain' in str(excinfo.value) - - @pytest.mark.sphinx(testroot='add_source_parser') def test_add_source_parser(app, status, warning): assert set(app.config.source_suffix) == set(['.rst', '.md', '.test'])