Issue #6431: Fix Fraction comparisons with unknown types, and with
[python.git] / Doc / documenting / markup.rst
blob1d1023a5d13d9d3e7c15c0b618734724083cd303
1 .. highlightlang:: rest
3 Additional Markup Constructs
4 ============================
6 Sphinx adds a lot of new directives and interpreted text roles to standard reST
7 markup.  This section contains the reference material for these facilities.
8 Documentation for "standard" reST constructs is not included here, though
9 they are used in the Python documentation.
11 .. note::
13    This is just an overview of Sphinx' extended markup capabilities; full
14    coverage can be found in `its own documentation
15    <http://sphinx.pocoo.org/contents.html>`_.
18 Meta-information markup
19 -----------------------
21 .. describe:: sectionauthor
23    Identifies the author of the current section.  The argument should include
24    the author's name such that it can be used for presentation (though it isn't)
25    and email address.  The domain name portion of the address should be lower
26    case.  Example::
28       .. sectionauthor:: Guido van Rossum <guido@python.org>
30    Currently, this markup isn't reflected in the output in any way, but it helps
31    keep track of contributions.
34 Module-specific markup
35 ----------------------
37 The markup described in this section is used to provide information about a
38 module being documented.  Each module should be documented in its own file.
39 Normally this markup appears after the title heading of that file; a typical
40 file might start like this::
42    :mod:`parrot` -- Dead parrot access
43    ===================================
45    .. module:: parrot
46       :platform: Unix, Windows
47       :synopsis: Analyze and reanimate dead parrots.
48    .. moduleauthor:: Eric Cleese <eric@python.invalid>
49    .. moduleauthor:: John Idle <john@python.invalid>
51 As you can see, the module-specific markup consists of two directives, the
52 ``module`` directive and the ``moduleauthor`` directive.
54 .. describe:: module
56    This directive marks the beginning of the description of a module (or package
57    submodule, in which case the name should be fully qualified, including the
58    package name).
60    The ``platform`` option, if present, is a comma-separated list of the
61    platforms on which the module is available (if it is available on all
62    platforms, the option should be omitted).  The keys are short identifiers;
63    examples that are in use include "IRIX", "Mac", "Windows", and "Unix".  It is
64    important to use a key which has already been used when applicable.
66    The ``synopsis`` option should consist of one sentence describing the
67    module's purpose -- it is currently only used in the Global Module Index.
69    The ``deprecated`` option can be given (with no value) to mark a module as
70    deprecated; it will be designated as such in various locations then.
72 .. describe:: moduleauthor
74    The ``moduleauthor`` directive, which can appear multiple times, names the
75    authors of the module code, just like ``sectionauthor`` names the author(s)
76    of a piece of documentation.  It too does not result in any output currently.
78 .. note::
80    It is important to make the section title of a module-describing file
81    meaningful since that value will be inserted in the table-of-contents trees
82    in overview files.
85 Information units
86 -----------------
88 There are a number of directives used to describe specific features provided by
89 modules.  Each directive requires one or more signatures to provide basic
90 information about what is being described, and the content should be the
91 description.  The basic version makes entries in the general index; if no index
92 entry is desired, you can give the directive option flag ``:noindex:``.  The
93 following example shows all of the features of this directive type::
95     .. function:: spam(eggs)
96                   ham(eggs)
97        :noindex:
99        Spam or ham the foo.
101 The signatures of object methods or data attributes should always include the
102 type name (``.. method:: FileInput.input(...)``), even if it is obvious from the
103 context which type they belong to; this is to enable consistent
104 cross-references.  If you describe methods belonging to an abstract protocol,
105 such as "context managers", include a (pseudo-)type name too to make the
106 index entries more informative.
108 The directives are:
110 .. describe:: cfunction
112    Describes a C function. The signature should be given as in C, e.g.::
114       .. cfunction:: PyObject* PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
116    This is also used to describe function-like preprocessor macros.  The names
117    of the arguments should be given so they may be used in the description.
119    Note that you don't have to backslash-escape asterisks in the signature,
120    as it is not parsed by the reST inliner.
122 .. describe:: cmember
124    Describes a C struct member. Example signature::
126       .. cmember:: PyObject* PyTypeObject.tp_bases
128    The text of the description should include the range of values allowed, how
129    the value should be interpreted, and whether the value can be changed.
130    References to structure members in text should use the ``member`` role.
132 .. describe:: cmacro
134    Describes a "simple" C macro.  Simple macros are macros which are used
135    for code expansion, but which do not take arguments so cannot be described as
136    functions.  This is not to be used for simple constant definitions.  Examples
137    of its use in the Python documentation include :cmacro:`PyObject_HEAD` and
138    :cmacro:`Py_BEGIN_ALLOW_THREADS`.
140 .. describe:: ctype
142    Describes a C type. The signature should just be the type name.
144 .. describe:: cvar
146    Describes a global C variable.  The signature should include the type, such
147    as::
149       .. cvar:: PyObject* PyClass_Type
151 .. describe:: data
153    Describes global data in a module, including both variables and values used
154    as "defined constants."  Class and object attributes are not documented
155    using this environment.
157 .. describe:: exception
159    Describes an exception class.  The signature can, but need not include
160    parentheses with constructor arguments.
162 .. describe:: function
164    Describes a module-level function.  The signature should include the
165    parameters, enclosing optional parameters in brackets.  Default values can be
166    given if it enhances clarity.  For example::
168       .. function:: Timer.repeat([repeat=3[, number=1000000]])
170    Object methods are not documented using this directive. Bound object methods
171    placed in the module namespace as part of the public interface of the module
172    are documented using this, as they are equivalent to normal functions for
173    most purposes.
175    The description should include information about the parameters required and
176    how they are used (especially whether mutable objects passed as parameters
177    are modified), side effects, and possible exceptions.  A small example may be
178    provided.
180 .. describe:: class
182    Describes a class.  The signature can include parentheses with parameters
183    which will be shown as the constructor arguments.
185 .. describe:: attribute
187    Describes an object data attribute.  The description should include
188    information about the type of the data to be expected and whether it may be
189    changed directly.
191 .. describe:: method
193    Describes an object method.  The parameters should not include the ``self``
194    parameter.  The description should include similar information to that
195    described for ``function``.
197 .. describe:: opcode
199    Describes a Python :term:`bytecode` instruction.
201 .. describe:: cmdoption
203    Describes a command line option or switch.  Option argument names should be
204    enclosed in angle brackets.  Example::
206       .. cmdoption:: -m <module>
208          Run a module as a script.
210 .. describe:: envvar
212    Describes an environment variable that Python uses or defines.
215 There is also a generic version of these directives:
217 .. describe:: describe
219    This directive produces the same formatting as the specific ones explained
220    above but does not create index entries or cross-referencing targets.  It is
221    used, for example, to describe the directives in this document. Example::
223       .. describe:: opcode
225          Describes a Python bytecode instruction.
228 Showing code examples
229 ---------------------
231 Examples of Python source code or interactive sessions are represented using
232 standard reST literal blocks.  They are started by a ``::`` at the end of the
233 preceding paragraph and delimited by indentation.
235 Representing an interactive session requires including the prompts and output
236 along with the Python code.  No special markup is required for interactive
237 sessions.  After the last line of input or output presented, there should not be
238 an "unused" primary prompt; this is an example of what *not* to do::
240    >>> 1 + 1
241    2
242    >>>
244 Syntax highlighting is handled in a smart way:
246 * There is a "highlighting language" for each source file.  Per default,
247   this is ``'python'`` as the majority of files will have to highlight Python
248   snippets.
250 * Within Python highlighting mode, interactive sessions are recognized
251   automatically and highlighted appropriately.
253 * The highlighting language can be changed using the ``highlightlang``
254   directive, used as follows::
256      .. highlightlang:: c
258   This language is used until the next ``highlightlang`` directive is
259   encountered.
261 * The values normally used for the highlighting language are:
263   * ``python`` (the default)
264   * ``c``
265   * ``rest``
266   * ``none`` (no highlighting)
268 * If highlighting with the current language fails, the block is not highlighted
269   in any way.
271 Longer displays of verbatim text may be included by storing the example text in
272 an external file containing only plain text.  The file may be included using the
273 ``literalinclude`` directive. [1]_ For example, to include the Python source file
274 :file:`example.py`, use::
276    .. literalinclude:: example.py
278 The file name is relative to the current file's path.  Documentation-specific
279 include files should be placed in the ``Doc/includes`` subdirectory.
282 Inline markup
283 -------------
285 As said before, Sphinx uses interpreted text roles to insert semantic markup in
286 documents.
288 Names of local variables, such as function/method arguments, are an exception,
289 they should be marked simply with ``*var*``.
291 For all other roles, you have to write ``:rolename:`content```.
293 There are some additional facilities that make cross-referencing roles more
294 versatile:
296 * You may supply an explicit title and reference target, like in reST direct
297   hyperlinks: ``:role:`title <target>``` will refer to *target*, but the link
298   text will be *title*.
300 * If you prefix the content with ``!``, no reference/hyperlink will be created.
302 * For the Python object roles, if you prefix the content with ``~``, the link
303   text will only be the last component of the target.  For example,
304   ``:meth:`~Queue.Queue.get``` will refer to ``Queue.Queue.get`` but only
305   display ``get`` as the link text.
307   In HTML output, the link's ``title`` attribute (that is e.g. shown as a
308   tool-tip on mouse-hover) will always be the full target name.
310 The following roles refer to objects in modules and are possibly hyperlinked if
311 a matching identifier is found:
313 .. describe:: mod
315    The name of a module; a dotted name may be used.  This should also be used for
316    package names.
318 .. describe:: func
320    The name of a Python function; dotted names may be used.  The role text
321    should not include trailing parentheses to enhance readability.  The
322    parentheses are stripped when searching for identifiers.
324 .. describe:: data
326    The name of a module-level variable or constant.
328 .. describe:: const
330    The name of a "defined" constant.  This may be a C-language ``#define``
331    or a Python variable that is not intended to be changed.
333 .. describe:: class
335    A class name; a dotted name may be used.
337 .. describe:: meth
339    The name of a method of an object.  The role text should include the type
340    name and the method name.  A dotted name may be used.
342 .. describe:: attr
344    The name of a data attribute of an object.
346 .. describe:: exc
348    The name of an exception. A dotted name may be used.
350 The name enclosed in this markup can include a module name and/or a class name.
351 For example, ``:func:`filter``` could refer to a function named ``filter`` in
352 the current module, or the built-in function of that name.  In contrast,
353 ``:func:`foo.filter``` clearly refers to the ``filter`` function in the ``foo``
354 module.
356 Normally, names in these roles are searched first without any further
357 qualification, then with the current module name prepended, then with the
358 current module and class name (if any) prepended.  If you prefix the name with a
359 dot, this order is reversed.  For example, in the documentation of the
360 :mod:`codecs` module, ``:func:`open``` always refers to the built-in function,
361 while ``:func:`.open``` refers to :func:`codecs.open`.
363 A similar heuristic is used to determine whether the name is an attribute of
364 the currently documented class.
366 The following roles create cross-references to C-language constructs if they
367 are defined in the API documentation:
369 .. describe:: cdata
371    The name of a C-language variable.
373 .. describe:: cfunc
375    The name of a C-language function. Should include trailing parentheses.
377 .. describe:: cmacro
379    The name of a "simple" C macro, as defined above.
381 .. describe:: ctype
383    The name of a C-language type.
386 The following role does possibly create a cross-reference, but does not refer
387 to objects:
389 .. describe:: token
391    The name of a grammar token (used in the reference manual to create links
392    between production displays).
395 The following role creates a cross-reference to the term in the glossary:
397 .. describe:: term
399    Reference to a term in the glossary.  The glossary is created using the
400    ``glossary`` directive containing a definition list with terms and
401    definitions.  It does not have to be in the same file as the ``term``
402    markup, in fact, by default the Python docs have one global glossary
403    in the ``glossary.rst`` file.
405    If you use a term that's not explained in a glossary, you'll get a warning
406    during build.
408 ---------
410 The following roles don't do anything special except formatting the text
411 in a different style:
413 .. describe:: command
415    The name of an OS-level command, such as ``rm``.
417 .. describe:: dfn
419    Mark the defining instance of a term in the text.  (No index entries are
420    generated.)
422 .. describe:: envvar
424    An environment variable.  Index entries are generated.
426 .. describe:: file
428    The name of a file or directory.  Within the contents, you can use curly
429    braces to indicate a "variable" part, for example::
431       ... is installed in :file:`/usr/lib/python2.{x}/site-packages` ...
433    In the built documentation, the ``x`` will be displayed differently to
434    indicate that it is to be replaced by the Python minor version.
436 .. describe:: guilabel
438    Labels presented as part of an interactive user interface should be marked
439    using ``guilabel``.  This includes labels from text-based interfaces such as
440    those created using :mod:`curses` or other text-based libraries.  Any label
441    used in the interface should be marked with this role, including button
442    labels, window titles, field names, menu and menu selection names, and even
443    values in selection lists.
445 .. describe:: kbd
447    Mark a sequence of keystrokes.  What form the key sequence takes may depend
448    on platform- or application-specific conventions.  When there are no relevant
449    conventions, the names of modifier keys should be spelled out, to improve
450    accessibility for new users and non-native speakers.  For example, an
451    *xemacs* key sequence may be marked like ``:kbd:`C-x C-f```, but without
452    reference to a specific application or platform, the same sequence should be
453    marked as ``:kbd:`Control-x Control-f```.
455 .. describe:: keyword
457    The name of a keyword in Python.
459 .. describe:: mailheader
461    The name of an RFC 822-style mail header.  This markup does not imply that
462    the header is being used in an email message, but can be used to refer to any
463    header of the same "style."  This is also used for headers defined by the
464    various MIME specifications.  The header name should be entered in the same
465    way it would normally be found in practice, with the camel-casing conventions
466    being preferred where there is more than one common usage. For example:
467    ``:mailheader:`Content-Type```.
469 .. describe:: makevar
471    The name of a :command:`make` variable.
473 .. describe:: manpage
475    A reference to a Unix manual page including the section,
476    e.g. ``:manpage:`ls(1)```.
478 .. describe:: menuselection
480    Menu selections should be marked using the ``menuselection`` role.  This is
481    used to mark a complete sequence of menu selections, including selecting
482    submenus and choosing a specific operation, or any subsequence of such a
483    sequence.  The names of individual selections should be separated by
484    ``-->``.
486    For example, to mark the selection "Start > Programs", use this markup::
488       :menuselection:`Start --> Programs`
490    When including a selection that includes some trailing indicator, such as the
491    ellipsis some operating systems use to indicate that the command opens a
492    dialog, the indicator should be omitted from the selection name.
494 .. describe:: mimetype
496    The name of a MIME type, or a component of a MIME type (the major or minor
497    portion, taken alone).
499 .. describe:: newsgroup
501    The name of a Usenet newsgroup.
503 .. describe:: option
505    A command-line option to an executable program.  The leading hyphen(s) must
506    be included.
508 .. describe:: program
510    The name of an executable program.  This may differ from the file name for
511    the executable for some platforms.  In particular, the ``.exe`` (or other)
512    extension should be omitted for Windows programs.
514 .. describe:: regexp
516    A regular expression. Quotes should not be included.
518 .. describe:: samp
520    A piece of literal text, such as code.  Within the contents, you can use
521    curly braces to indicate a "variable" part, as in ``:file:``.
523    If you don't need the "variable part" indication, use the standard
524    ````code```` instead.
526 .. describe:: var
528    A Python or C variable or parameter name.
531 The following roles generate external links:
533 .. describe:: pep
535    A reference to a Python Enhancement Proposal.  This generates appropriate
536    index entries. The text "PEP *number*\ " is generated; in the HTML output,
537    this text is a hyperlink to an online copy of the specified PEP.
539 .. describe:: rfc
541    A reference to an Internet Request for Comments.  This generates appropriate
542    index entries. The text "RFC *number*\ " is generated; in the HTML output,
543    this text is a hyperlink to an online copy of the specified RFC.
546 Note that there are no special roles for including hyperlinks as you can use
547 the standard reST markup for that purpose.
550 .. _doc-ref-role:
552 Cross-linking markup
553 --------------------
555 To support cross-referencing to arbitrary sections in the documentation, the
556 standard reST labels are "abused" a bit: Every label must precede a section
557 title; and every label name must be unique throughout the entire documentation
558 source.
560 You can then reference to these sections using the ``:ref:`label-name``` role.
562 Example::
564    .. _my-reference-label:
566    Section to cross-reference
567    --------------------------
569    This is the text of the section.
571    It refers to the section itself, see :ref:`my-reference-label`.
573 The ``:ref:`` invocation is replaced with the section title.
576 Paragraph-level markup
577 ----------------------
579 These directives create short paragraphs and can be used inside information
580 units as well as normal text:
582 .. describe:: note
584    An especially important bit of information about an API that a user should be
585    aware of when using whatever bit of API the note pertains to.  The content of
586    the directive should be written in complete sentences and include all
587    appropriate punctuation.
589    Example::
591       .. note::
593          This function is not suitable for sending spam e-mails.
595 .. describe:: warning
597    An important bit of information about an API that a user should be aware of
598    when using whatever bit of API the warning pertains to.  The content of the
599    directive should be written in complete sentences and include all appropriate
600    punctuation.  This should only be chosen over ``note`` for information
601    regarding the possibility of crashes, data loss, or security implications.
603 .. describe:: versionadded
605    This directive documents the version of Python which added the described
606    feature to the library or C API. When this applies to an entire module, it
607    should be placed at the top of the module section before any prose.
609    The first argument must be given and is the version in question; you can add
610    a second argument consisting of a *brief* explanation of the change.
612    Example::
614       .. versionadded:: 2.5
615          The *spam* parameter.
617    Note that there must be no blank line between the directive head and the
618    explanation; this is to make these blocks visually continuous in the markup.
620 .. describe:: versionchanged
622    Similar to ``versionadded``, but describes when and what changed in the named
623    feature in some way (new parameters, changed side effects, etc.).
625 --------------
627 .. describe:: seealso
629    Many sections include a list of references to module documentation or
630    external documents.  These lists are created using the ``seealso`` directive.
632    The ``seealso`` directive is typically placed in a section just before any
633    sub-sections.  For the HTML output, it is shown boxed off from the main flow
634    of the text.
636    The content of the ``seealso`` directive should be a reST definition list.
637    Example::
639       .. seealso::
641          Module :mod:`zipfile`
642             Documentation of the :mod:`zipfile` standard module.
644          `GNU tar manual, Basic Tar Format <http://link>`_
645             Documentation for tar archive files, including GNU tar extensions.
647 .. describe:: rubric
649    This directive creates a paragraph heading that is not used to create a
650    table of contents node.  It is currently used for the "Footnotes" caption.
652 .. describe:: centered
654    This directive creates a centered boldfaced paragraph.  Use it as follows::
656       .. centered::
658          Paragraph contents.
661 Table-of-contents markup
662 ------------------------
664 Since reST does not have facilities to interconnect several documents, or split
665 documents into multiple output files, Sphinx uses a custom directive to add
666 relations between the single files the documentation is made of, as well as
667 tables of contents.  The ``toctree`` directive is the central element.
669 .. describe:: toctree
671    This directive inserts a "TOC tree" at the current location, using the
672    individual TOCs (including "sub-TOC trees") of the files given in the
673    directive body.  A numeric ``maxdepth`` option may be given to indicate the
674    depth of the tree; by default, all levels are included.
676    Consider this example (taken from the library reference index)::
678       .. toctree::
679          :maxdepth: 2
681          intro.rst
682          strings.rst
683          datatypes.rst
684          numeric.rst
685          (many more files listed here)
687    This accomplishes two things:
689    * Tables of contents from all those files are inserted, with a maximum depth
690      of two, that means one nested heading.  ``toctree`` directives in those
691      files are also taken into account.
692    * Sphinx knows that the relative order of the files ``intro.rst``,
693      ``strings.rst`` and so forth, and it knows that they are children of the
694      shown file, the library index.  From this information it generates "next
695      chapter", "previous chapter" and "parent chapter" links.
697    In the end, all files included in the build process must occur in one
698    ``toctree`` directive; Sphinx will emit a warning if it finds a file that is
699    not included, because that means that this file will not be reachable through
700    standard navigation.
702    The special file ``contents.rst`` at the root of the source directory is the
703    "root" of the TOC tree hierarchy; from it the "Contents" page is generated.
706 Index-generating markup
707 -----------------------
709 Sphinx automatically creates index entries from all information units (like
710 functions, classes or attributes) like discussed before.
712 However, there is also an explicit directive available, to make the index more
713 comprehensive and enable index entries in documents where information is not
714 mainly contained in information units, such as the language reference.
716 The directive is ``index`` and contains one or more index entries.  Each entry
717 consists of a type and a value, separated by a colon.
719 For example::
721    .. index::
722       single: execution; context
723       module: __main__
724       module: sys
725       triple: module; search; path
727 This directive contains five entries, which will be converted to entries in the
728 generated index which link to the exact location of the index statement (or, in
729 case of offline media, the corresponding page number).
731 The possible entry types are:
733 single
734    Creates a single index entry.  Can be made a subentry by separating the
735    subentry text with a semicolon (this notation is also used below to describe
736    what entries are created).
737 pair
738    ``pair: loop; statement`` is a shortcut that creates two index entries,
739    namely ``loop; statement`` and ``statement; loop``.
740 triple
741    Likewise, ``triple: module; search; path`` is a shortcut that creates three
742    index entries, which are ``module; search path``, ``search; path, module`` and
743    ``path; module search``.
744 module, keyword, operator, object, exception, statement, builtin
745    These all create two index entries.  For example, ``module: hashlib`` creates
746    the entries ``module; hashlib`` and ``hashlib; module``.
748 For index directives containing only "single" entries, there is a shorthand
749 notation::
751    .. index:: BNF, grammar, syntax, notation
753 This creates four index entries.
756 Grammar production displays
757 ---------------------------
759 Special markup is available for displaying the productions of a formal grammar.
760 The markup is simple and does not attempt to model all aspects of BNF (or any
761 derived forms), but provides enough to allow context-free grammars to be
762 displayed in a way that causes uses of a symbol to be rendered as hyperlinks to
763 the definition of the symbol.  There is this directive:
765 .. describe:: productionlist
767    This directive is used to enclose a group of productions.  Each production is
768    given on a single line and consists of a name, separated by a colon from the
769    following definition.  If the definition spans multiple lines, each
770    continuation line must begin with a colon placed at the same column as in the
771    first line.
773    Blank lines are not allowed within ``productionlist`` directive arguments.
775    The definition can contain token names which are marked as interpreted text
776    (e.g. ``unaryneg ::= "-" `integer```) -- this generates cross-references
777    to the productions of these tokens.
779    Note that no further reST parsing is done in the production, so that you
780    don't have to escape ``*`` or ``|`` characters.
783 .. XXX describe optional first parameter
785 The following is an example taken from the Python Reference Manual::
787    .. productionlist::
788       try_stmt: try1_stmt | try2_stmt
789       try1_stmt: "try" ":" `suite`
790                : ("except" [`expression` ["," `target`]] ":" `suite`)+
791                : ["else" ":" `suite`]
792                : ["finally" ":" `suite`]
793       try2_stmt: "try" ":" `suite`
794                : "finally" ":" `suite`
797 Substitutions
798 -------------
800 The documentation system provides three substitutions that are defined by default.
801 They are set in the build configuration file :file:`conf.py`.
803 .. describe:: |release|
805    Replaced by the Python release the documentation refers to.  This is the full
806    version string including alpha/beta/release candidate tags, e.g. ``2.5.2b3``.
808 .. describe:: |version|
810    Replaced by the Python version the documentation refers to. This consists
811    only of the major and minor version parts, e.g. ``2.5``, even for version
812    2.5.1.
814 .. describe:: |today|
816    Replaced by either today's date, or the date set in the build configuration
817    file.  Normally has the format ``April 14, 2007``.
820 .. rubric:: Footnotes
822 .. [1] There is a standard ``.. include`` directive, but it raises errors if the
823        file is not found.  This one only emits a warning.