Docutils | Overview | About | Users | Reference | Developers

reStructuredText Directives

Author:

David Goodger

Contact:
docutils-develop@lists.sourceforge.net
Revision:
9947
Date:
2024-10-13

This document describes the directives implemented in the reference reStructuredText parser.

Directives have the following syntax:

+-------+-------------------------------+
| ".. " | directive type "::" directive |
+-------+ block                         |
        |                               |
        +-------------------------------+

Directives begin with an explicit markup start (two periods and a space), followed by the directive type and two colons (collectively, the "directive marker"). The directive block begins immediately after the directive marker, and includes all subsequent indented lines. The directive block is divided into arguments, options (a field list), and content (in that order), any of which may appear. See the Directives section in the reStructuredText Markup Specification for syntax details.

Descriptions below list "doctree elements" (document tree element names; XML DTD generic identifiers) corresponding to individual directives. For details on the hierarchy of elements, please see The Docutils Document Tree and the Docutils Generic DTD XML document type definition. For directive implementation details, see Creating reStructuredText Directives.

Admonitions

Admonitions ("safety messages" or "hazard statements") can appear anywhere an ordinary body element can. They contain arbitrary body elements. Typically, an admonition is rendered as an offset block in a document, sometimes outlined or shaded.

Docutils defines a generic admonition as well as a set of specific admonitions.

Specific Admonitions

Directive Types:

"attention", "caution", "danger", "error", "hint", "important", "note", "tip", "warning"

Doctree Elements:

<attention>, <caution>, <danger>, <error>, <hint>, <important>, <note>, <tip>, <warning>

Directive Arguments:

none

Directive Options:

class, name

Directive Content:

Interpreted as body elements.

Specific admonitions are rendered with a title matching the admonition type. For example:

.. DANGER::
   Beware killer rabbits!

This directive might be rendered something like this:

+------------------------+
|        !DANGER!        |
|                        |
| Beware killer rabbits! |
+------------------------+

Any text immediately following the directive indicator (on the same line and/or indented on following lines) is interpreted as a directive block and is parsed for normal body elements. For example, the following "note" admonition directive contains one paragraph and a bullet list consisting of two list items:

.. note:: This is a note admonition.
   This is the second line of the first paragraph.

   - The note contains all indented body elements
     following.
   - It includes this bullet list.

Generic Admonition

Directive Type:

"admonition"

Doctree Elements:

<admonition>, <title>

Directive Arguments:

one, required (admonition title)

Directive Options:

class, name

Directive Content:

Interpreted as body elements.

This is a generic, titled admonition. The title may be anything the author desires.

The author-supplied title is also used as a classes attribute value after identifier normalization and adding the prefix "admonition-". For example, this admonition:

.. admonition:: And, by the way...

   You can make up your own admonition too.

becomes the following document tree (pseudo-XML):

<document source="test data">
    <admonition classes="admonition-and-by-the-way">
        <title>
            And, by the way...
        <paragraph>
            You can make up your own admonition too.

The class option overrides the generated classes attribute value.

Images

There are two directives to include images: image and figure.

SVG

PDF

PNG

JPG

GIF

APNG

AVIF

WebM

MP4

OGG

vector

raster

video [1]

HTML4 [2]

(✓)

(✓)

(✓)

(✓)

(✓)

HTML5

LaTeX [3]

ODT

Image

Directive Type:

"image"

Doctree Elements:

<image>, <reference> (only with option "target")

Directive Arguments:

one, required (image URI)

Directive Options:

see below

Directive Content:

none

Configuration Setting:

image_loading (only HTML5 writer)

An "image" is a simple picture:

.. image:: picture.png

A URI reference to the image source file is specified in the directive argument. As with hyperlink targets, the image URI may begin on the same line as the explicit markup start and target name, or it may begin in an indented text block immediately following, with no intervening blank lines. If there are multiple lines in the link block, they are stripped of leading and trailing whitespace and joined together.

Optionally, the image link block may contain a flat field list, the image options. For example:

.. image:: picture.jpeg
   :height: 100px
   :width: 200 px
   :scale: 50 %
   :loading: embed
   :alt: alternate text
   :align: right

Inline images can be defined with an "image" directive in a substitution definition, e.g.

|Red light| means stop, |green light| means go.

.. |red light|    image:: red_light.png
   :align: top
.. |green light|  image:: green_light.png
   :align: bottom

The "image" directive recognizes the common options class and name as well as

align"top", "middle", "bottom", "left", "center", or "right"

The alignment of the image, equivalent to the HTML <img> tag's deprecated "align" attribute or the corresponding "vertical-align" and "text-align" CSS properties. The values "top", "middle", and "bottom" control an image's vertical alignment (relative to the text baseline); they are only useful for inline images (substitutions). The values "left", "center", and "right" control an image's horizontal alignment, allowing the image to float and have the text flow around it. The specific behaviour depends upon the browser or rendering software used.

alttext

Alternate text: a short description of the image, displayed by applications that cannot display images, or spoken by applications for visually impaired users.

heightlength

The desired height of the image. Used to reserve space or scale the image vertically. When the scale option is also specified, they are combined. For example, a height of 200px and a scale of 50 is equivalent to a height of 100px with no scale.

loading"embed", "link", or "lazy"

Set the loading attribute to indicate the preferred handling by the Docutils Writer. [4]

embed:

Embed the image into the output document. [5]

link:

Refer to the image via its URI.

lazy:

Refer to the image. The HTML5 writer additionally specifies the "lazy loading attribute".

(New in Docutils 0.21.)

scaleinteger percentage (the "%" symbol is optional)

The uniform scaling factor of the image. The default is "100 %", i.e. no scaling. If the output format does not support a scaling attribute (e.g. HTML), the Docutils writer tries to determine missing size specifications from the image file (requires the Python Imaging Library).

targetURI or reference name

Nest the image in a hyperlink reference element (make it "clickable"). The option argument may be a URI reference or a reference name with underscore suffix (e.g. `a name`_).

widthlength or percentage of the current line width

The width of the image. Used to reserve space or scale the image horizontally. As with height above, when the scale option is also specified, they are combined.

Figure

Directive Type:

"figure"

Doctree Elements:

<figure>, <image>, <caption>, <legend>

Directive Arguments:

one, required (image URI)

Directive Options:

see below

Directive Content:

Interpreted as the figure caption and an optional legend.

A "figure" consists of image data (including image options), an optional caption (a single paragraph), and an optional legend (arbitrary body elements). For page-based output media, figures might float to a different position if this helps the page layout.

.. figure:: picture.png
   :scale: 50 %
   :alt: map to buried treasure

   This is the caption of the figure (a simple paragraph).

   The legend consists of all elements after the caption.  In this
   case, the legend consists of this paragraph and the following
   table:

   +-----------------------+-----------------------+
   | Symbol                | Meaning               |
   +=======================+=======================+
   | .. image:: tent.png   | Campground            |
   +-----------------------+-----------------------+
   | .. image:: waves.png  | Lake                  |
   +-----------------------+-----------------------+
   | .. image:: peak.png   | Mountain              |
   +-----------------------+-----------------------+

There must be blank lines before the caption paragraph and before the legend. To specify a legend without a caption, use an empty comment ("..") in place of the caption.

The "figure" directive supports all options of the "image" directive. These options (except align) are passed on to the contained image.

align"left", "center", or "right"

The horizontal alignment of the figure, allowing the image to float and have the text flow around it. The specific behaviour depends upon the browser or rendering software used.

In addition, the following options are recognized:

figwidth"image", length, or percentage of current line width

The width of the figure. Limits the horizontal space used by the figure. A special value of "image" is allowed, in which case the included image's actual width is used (requires the Python Imaging Library). If the image file is not found or the required software is unavailable, this option is ignored.

Sets the width attribute of the <figure> doctree element.

This option does not scale the included image; use the width image option for that.

+---------------------------+
|        figure             |
|                           |
|<------ figwidth --------->|
|                           |
|  +---------------------+  |
|  |     image           |  |
|  |                     |  |
|  |<--- width --------->|  |
|  +---------------------+  |
|                           |
|The figure's caption should|
|wrap at this width.        |
+---------------------------+
figclassspace separated list of class names

Set a classes attribute value on the figure element. See the class directive below.

Body Elements

Topic

Directive Type:

"topic"

Doctree Element:

<topic>

Directive Arguments:

one, required (topic title)

Directive Options:

class, name

Directive Content:

Interpreted as the topic body.

A topic is like a block quote with a title, or a self-contained section with no subsections. Use the "topic" directive to indicate a self-contained idea that is separate from the flow of the document. Topics may occur anywhere a section or transition may occur. Body elements and topics may not contain nested topics.

The directive's sole argument is interpreted as the topic title; the next line must be blank. All subsequent lines make up the topic body, interpreted as body elements. For example:

.. topic:: Topic Title

    Subsequent indented lines comprise
    the body of the topic, and are
    interpreted as body elements.

Line Block

Directive Type:

"line-block"

Doctree Element:

<line_block>

Directive Arguments:

none

Directive Options:

class, name

Directive Content:

Becomes the body of the line block.

The "line-block" directive constructs an element where line breaks and initial indentation is significant and inline markup is supported. It is equivalent to a parsed literal block with different rendering: typically in an ordinary serif typeface instead of a typewriter/monospaced face, and not automatically indented. (Have the line-block directive begin a block quote to get an indented line block.) Line blocks are useful for address blocks and verse (poetry, song lyrics), where the structure of lines is significant. For example, here's a classic:

"To Ma Own Beloved Lassie: A Poem on her 17th Birthday", by
Ewan McTeagle (for Lassie O'Shea):

    .. line-block::

        Lend us a couple of bob till Thursday.
        I'm absolutely skint.
        But I'm expecting a postal order and I can pay you back
            as soon as it comes.
        Love, Ewan.

Parsed Literal Block

Directive Type:

"parsed-literal"

Doctree Element:

<literal_block>

Directive Arguments:

none

Directive Options:

class, name

Directive Content:

Becomes the body of the literal block.

Unlike an ordinary literal block, the "parsed-literal" directive constructs a literal block where the text is parsed for inline markup. It is equivalent to a line block with different rendering: typically in a typewriter/monospaced typeface, like an ordinary literal block. Parsed literal blocks are useful for adding hyperlinks to code examples.

However, care must be taken with the text, because inline markup is recognized and there is no protection from parsing. Backslash-escapes may be necessary to prevent unintended parsing. And because the markup characters are removed by the parser, care must also be taken with vertical alignment. Parsed "ASCII art" is tricky, and extra whitespace may be necessary.

For example, all the element names in this content model are links:

.. parsed-literal::

   ( (title_, subtitle_?)?,
     decoration_?,
     (docinfo_, transition_?)?,
     `%structure.model;`_ )

Code

Directive Type:

"code"

Doctree Elements:

<literal_block>, inline elements

Directive Arguments:

one, optional (formal language)

Directive Options:

see below

Directive Content:

Becomes the body of the literal block.

Configuration Setting:

syntax_highlight

The "code" directive constructs a literal block. If the code language is specified, the content is parsed by the Pygments syntax highlighter and tokens are stored in nested inline elements with class arguments according to their syntactic category. The actual highlighting requires a custom style-sheet, see the sandbox/stylesheets for examples.

For example, the content of the following directive

.. code:: python
   :number-lines:

   def my_function():
       "just a test"
       print(8/2)

is parsed and marked up as Python source code.

The parsing can be turned off with the syntax_highlight configuration setting and command line option or by specifying the language as class option instead of directive argument. This also avoids warnings when Pygments is not installed or the language is not in the supported languages and markup formats.

For code in external files, use the "include" directive with the code option. For inline code, use the "code" role.

Recognizes the common options class and name as well as

number-linesinteger (start line number, optional)

Precede every line with a line number. The optional argument is the number of the first line (default 1).

Math

Directive Type:

"math"

Doctree Element:

<math_block>

Directive Arguments:

none

Directive Options:

class, name

Directive Content:

Becomes the body of the math block. (Content blocks separated by a blank line are put in adjacent math blocks.)

Configuration Setting:

math_output

The "math" directive inserts blocks with mathematical content (display formulas, equations) into the document. The input format is LaTeX math syntax with support for Unicode symbols, for example:

.. math::

  α_t(i) = P(O_1, O_2, … O_t, q_t = S_i λ)

Support is limited to a subset of LaTeX math by the conversion required for many output formats. For HTML, the math_output configuration setting (or the corresponding --math-output command line option) select between alternative output formats with different subsets of supported elements. If a writer does not support math typesetting, the content is inserted verbatim.

For inline formulas, use the "math" role.

Rubric

Directive Type:

"rubric"

Doctree Element:

<rubric>

Directive Arguments:

one, required (rubric text)

Directive Options:

class, name

Directive Content:

none

rubric n. 1. a title, heading, or the like, in a manuscript, book, statute, etc., written or printed in red or otherwise distinguished from the rest of the text. ...

—Random House Webster's College Dictionary, 1991

The "rubric" directive inserts a "rubric" element into the document tree. A rubric is like an informal heading that doesn't correspond to the document's structure.

Epigraph

Directive Type:

"epigraph"

Doctree Element:

<block_quote>

Directive Arguments:

none

Directive Options:

none

Directive Content:

Interpreted as the body of the block quote.

An epigraph is an apposite (suitable, apt, or pertinent) short inscription, often a quotation or poem, at the beginning of a document or section.

The "epigraph" directive produces an "epigraph"-class block quote. For example, this input:

.. epigraph::

   No matter where you go, there you are.

   -- Buckaroo Banzai

becomes this document tree fragment:

<block_quote classes="epigraph">
    <paragraph>
        No matter where you go, there you are.
    <attribution>
        Buckaroo Banzai

Highlights

Directive Type:

"highlights"

Doctree Element:

<block_quote>

Directive Arguments:

none

Directive Options:

none

Directive Content:

Interpreted as the body of the block quote.

Highlights summarize the main points of a document or section, often consisting of a list.

The "highlights" directive produces a "highlights"-class block quote. See Epigraph above for an analogous example.

Pull-Quote

Directive Type:

"pull-quote"

Doctree Element:

<block_quote>

Directive Arguments:

none

Directive Options:

none

Directive Content:

Interpreted as the body of the block quote.

A pull-quote is a small selection of text "pulled out and quoted", typically in a larger typeface. Pull-quotes are used to attract attention, especially in long articles.

The "pull-quote" directive produces a "pull-quote"-class block quote. See Epigraph above for an analogous example.

Compound Paragraph

Directive Type:

"compound"

Doctree Element:

<compound>

Directive Arguments:

none

Directive Options:

class, name

Directive Content:

Interpreted as body elements.

The "compound" directive is used to create a compound paragraph, which is a single logical paragraph containing multiple physical body elements such as simple paragraphs, literal blocks, tables, lists, etc., instead of directly containing text and inline elements. For example:

.. compound::

   The 'rm' command is very dangerous.  If you are logged
   in as root and enter ::

       cd /
       rm -rf *

   you will erase the entire contents of your file system.

In the example above, a literal block is "embedded" within a sentence that begins in one physical paragraph and ends in another.

Compound paragraphs are typically rendered as multiple distinct text blocks, with the possibility of variations to emphasize their logical unity:

  • If paragraphs are rendered with a first-line indent, only the first physical paragraph of a compound paragraph should have that indent -- second and further physical paragraphs should omit the indents;

  • vertical spacing between physical elements may be reduced;

  • and so on.

Container

Directive Type:

"container"

Doctree Element:

<container>

Directive Arguments:

one or more, optional (class names)

Directive Options:

name

Directive Content:

Interpreted as body elements.

The "container" directive surrounds its contents (arbitrary body elements) with a generic block-level "container" element. Combined with the optional argument, this is an extension mechanism for users & applications. For example:

.. container:: custom

   This paragraph might be rendered in a custom way.

Parsing the above results in the following pseudo-XML:

<container classes="custom">
    <paragraph>
        This paragraph might be rendered in a custom way.

The "container" directive is the equivalent of HTML's <div> element. It may be used to group a sequence of elements for user- or application-specific purposes.

Tables

Formal tables need more structure than the reStructuredText table syntax supplies. Tables may be given titles with the "table" directive. Sometimes reStructuredText tables are inconvenient to write, or table data in a standard format is readily available. The "csv-table" directive supports CSV [7] data.

Table

Directive Type:

"table"

Doctree Element:

<table>

Directive Arguments:

one, optional (table caption)

Directive Options:

see below

Directive Content:

A normal reStructuredText table.

Configuration Setting:

table_style

The "table" directive is used to provide a table caption or specify options, e.g.:

.. table:: Truth table for "not"
   :widths: auto

   =====  =====
     A    not A
   =====  =====
   False  True
   True   False
   =====  =====

Recognizes the common options class and name as well as

align"left", "center", or "right"

The horizontal alignment of the table (new in Docutils 0.13).

widthlength or percentage of the current line width

Sets the width of the table to the specified length or percentage of the line width. If omitted, the renderer determines the width of the table based on its contents or the column widths.

widths"auto", "grid", or a list of integers

Explicitly set column widths. Specifies relative widths if used with the width option. Possible values:

auto:

Delegate the determination of column widths to the backend (LaTeX, the HTML browser, ...).

grid:

Determine column widths from the widths of the input columns (in characters).

list of integers:

Must match the number of table columns. Used instead of the input column widths. Implies "grid".

The default depends on the writer. Most writers default to grid. [6]

CSV Table

Directive Type:

"csv-table"

Doctree Element:

<table>

Directive Arguments:

one, optional (table caption)

Directive Options:

see below

Directive Content:

A CSV (comma-separated values) table or (with the file or url options) none.

Configuration Settings:

table_style, file_insertion_enabled

The "csv-table" directive is used to create a table from CSV (comma-separated values) [7] data. The data may be internal (an integral part of the document) or external (a separate file).

  • Block markup and inline markup within cells is supported. Line ends are recognized within quoted cells.

  • There is no support for checking that the number of columns in each row is the same. The directive automatically adds empty entries at the end of short rows.

Example:

.. csv-table:: Frozen Delights!
   :header: "Treat", "Quantity", "Description"
   :widths: 15, 10, 30

   "Albatross", 2.99, "On a stick!"
   "Crunchy Frog", 1.49, "If we took the bones out,
   it wouldn't be crunchy, now would it?"
   "Gannet Ripple", 1.99, "On a stick!"

Recognizes the common options class and name as well as

align"left", "center", or "right"

The horizontal alignment of the table. (New in Docutils 0.13)

delimcharacter, "tab", or "space"

The character used to separate data fields. The special values "tab" and "space" are converted to the respective whitespace characters. [8] Defaults to "," (comma).

encodingencoding

The text encoding of the external CSV data (file or URL). Defaults to the document's input_encoding.

escapecharacter

A character used to escape the delimiter or quote characters from the CSV parser. The default is no escape character -- fields may contain delimiter or newline characters if they are quoted, two quote characters stand for a literal one, e.g., """Hi!"", he said.".

filepath

The local filesystem path to a CSV data file.

headertext (CSV data)

Supplemental data for the table header, added independently of and before any header-rows from the main CSV data. Must use the same CSV format as the main CSV data. [9]

header-rowsinteger

The number of rows of CSV data to use in the table header. Defaults to 0.

keepspaceflag

Treat whitespace immediately following the delimiter as significant. The default is to ignore such whitespace.

quotecharacter

The character used to quote fields containing special characters, such as the delimiter, quote, or new-line characters. Defaults to " (quote).

stub-columnsinteger

The number of table columns to use as stubs (row titles, on the left). Defaults to 0.

urlURI

A URI reference to a CSV data file.

widthlength or percentage of the current line width

Sets the width of the table to the specified length or percentage of the line width. If omitted, the renderer determines the width of the table based on its contents or the column widths.

widthslist of integers or "auto"

A list of relative column widths. The default is equal-width columns (100%/#columns).

"auto" delegates the determination of column widths to the backend (LaTeX, the HTML browser, ...).

List Table

Directive Type:

"list-table"

Doctree Element:

<table>

Directive Arguments:

one, optional (table caption)

Directive Options:

see below

Directive Content:

A uniform two-level bullet list.

Configuration Setting:

table_style

(This is an initial implementation; further ideas may be implemented in the future.)

The "list-table" directive is used to create a table from data in a uniform two-level bullet list. "Uniform" means that each sublist (second-level list) must contain the same number of list items.

Example:

.. list-table:: Frozen Delights!
   :widths: 15 10 30
   :header-rows: 1

   * - Treat
     - Quantity
     - Description
   * - Albatross
     - 2.99
     - On a stick!
   * - Crunchy Frog
     - 1.49
     - If we took the bones out, it wouldn't be
       crunchy, now would it?
   * - Gannet Ripple
     - 1.99
     - On a stick!

Recognizes the common options class and name as well as

align"left", "center", or "right"

The horizontal alignment of the table. (New in Docutils 0.13)

header-rowsinteger

The number of rows of list data to use in the table header. Defaults to 0.

stub-columnsinteger

The number of table columns to use as stubs (row titles, on the left). Defaults to 0.

widthlength or percentage of the current line width

Sets the width of the table to the specified length or percentage of the line width. If omitted, the renderer determines the width of the table based on its contents or the column widths.

widthslist of integers or "auto"

A list of relative column widths. The default is equal-width columns (100%/#columns).

"auto" delegates the determination of column widths to the backend (LaTeX, the HTML browser, ...).

Document Parts

Table of Contents

Directive Type:

"contents"

Doctree Elements:

<pending>, <topic>

Directive Arguments:

one, optional: title

Directive Options:

see below

Directive Content:

none

Configuration Settings:

toc_backlinks, use_latex_toc, generate_oowriter_toc

The "contents" directive generates a table of contents (TOC) in a <topic> element. Topics, and therefore tables of contents, may occur anywhere a section or transition may occur. Body elements and topics may not contain tables of contents.

Here's the directive in its simplest form:

.. contents::

Language-dependent boilerplate text will be used for the title. The English default title text is "Contents".

An explicit title may be specified:

.. contents:: Table of Contents

The title may span lines, although it is not recommended:

.. contents:: Here's a very long Table of
   Contents title

Directive options may be specified using a field list:

.. contents:: Table of Contents
   :depth: 2

If the default title is to be used, the options field list may begin on the same line as the directive marker:

.. contents:: :depth: 2

The "contents" directive recognizes the common option class as well as

backlinks"entry" or "top" or "none"

Generate links from section headers back to the table of contents entries, the table of contents itself, or generate no back-links.

depthinteger

The number of section levels that are collected in the table of contents. The default is unlimited depth.

localflag

Generate a local table of contents. Entries will only include subsections of the section in which the directive is given. If no explicit title is given, the table of contents will not be titled.

Automatic Section Numbering

Directive Type:

"sectnum" or "section-numbering" (synonyms)

Doctree Elements:

<pending>, <generated>

Directive Arguments:

none

Directive Options:

see below

Directive Content:

none

Configuration Setting:

sectnum_xform

The "sectnum" (or "section-numbering") directive automatically numbers sections and subsections in a document (if not disabled by the --no-section-numbering command line option or the sectnum_xform configuration setting).

Section numbers are of the "multiple enumeration" form, where each level has a number, separated by periods. For example, the title of section 1, subsection 2, subsubsection 3 would have "1.2.3" prefixed.

The directive does its work in two passes: the initial parse and a transform. During the initial parse, a <pending> element is generated which acts as a placeholder, storing any options internally. At a later stage in the processing, the <pending> element triggers a transform, which adds section numbers to titles. Section numbers are enclosed in a <generated> element, and titles have their auto attribute set to "1".

The "sectnum" directive recognizes the following options:

depthinteger

The number of section levels that are numbered by this directive. The default is unlimited depth.

prefixtext

An arbitrary string that is prefixed to the automatically generated section numbers. It may be something like "3.2.", which will produce "3.2.1", "3.2.2", "3.2.2.1", and so on. Note that any separating punctuation (in the example, a period, ".") must be explicitly provided. The default is no prefix.

suffixtext

An arbitrary string that is appended to the automatically generated section numbers. The default is no suffix.

startinteger

The value that will be used for the first section number. Combined with prefix, this may be used to force the right numbering for a document split over several source files. The default is 1.

References

Target Footnotes

Directive Type:

"target-notes"

Doctree Elements:

<pending>, <footnote>, <footnote_reference>

Directive Arguments:

none

Directive Options:

class, name

Directive Content:

none

The "target-notes" directive creates a footnote for each external target in the text, and corresponding footnote references after each reference. For every explicit target (of the form, .. _target name: URL) in the text, a footnote will be generated containing the visible URL as content.

Footnotes

NOT IMPLEMENTED YET

Directive Type:

"footnotes"

Doctree Elements:

<pending>, <topic>

Directive Arguments:

none?

Directive Options:

Possible?

Directive Content:

none

@@@

Citations

NOT IMPLEMENTED YET

Directive Type:

"citations"

Doctree Elements:

<pending>, <topic>

Directive Arguments:

none?

Directive Options:

Possible?

Directive Content:

none

@@@

Directives for Substitution Definitions

The directives introduced in this section may only be used in substitution definitions. They may not be used directly, in standalone context.

Inline Images

The image directive can be used both, stand-alone (to define block-level images) and in substitution definitions to define inline images.

Replacement Text

Directive Type:

"replace"

Doctree Element:

Text & inline elements

Directive Arguments:

none

Directive Options:

none

Directive Content:

A single paragraph; may contain inline markup.

The "replace" directive is used to indicate replacement text for a substitution reference. It may be used within substitution definitions only. For example, this directive can be used to expand abbreviations:

.. |reST| replace:: reStructuredText

Yes, |reST| is a long word, so I can't blame anyone for wanting to
abbreviate it.
I recommend you try |Python|_.

.. |Python| replace:: Python, *the* best language around
.. _Python: https://www.python.org/

Unicode Character Codes

Directive Type:

"unicode"

Doctree Element:

Text

Directive Arguments:

one or more, required (Unicode character codes, optional text, and comments)

Directive Options:

see below

Directive Content:

none

The "unicode" directive converts Unicode character codes (numerical values) to characters, and may be used in substitution definitions only.

The arguments, separated by spaces, can be:

  • character codes as

    • decimal numbers or

    • hexadecimal numbers, prefixed by 0x, x, \x, U+, u, or \u or as XML-style hexadecimal character entities, e.g. &#x1a2b;

  • text, which is used as-is.

Text following " .. " is a comment and is ignored. The spaces between the arguments are ignored and thus do not appear in the output. Hexadecimal codes are case-insensitive.

For example, the following text:

Copyright |copy| 2003, |BogusMegaCorp (TM)| |---|
all rights reserved.

.. |copy| unicode:: 0xA9 .. copyright sign
.. |BogusMegaCorp (TM)| unicode:: BogusMegaCorp U+2122
   .. with trademark sign
.. |---| unicode:: U+02014 .. em dash
   :trim:

results in:

Copyright © 2003, BogusMegaCorp™—all rights reserved.

Docutils comes with a set of character substitution definitions in the reStructuredText Standard Definition Files.

The "unicode" directive recognizes the following options:

ltrimflag

Whitespace to the left of the substitution reference is removed.

rtrimflag

Whitespace to the right of the substitution reference is removed.

trimflag

Equivalent to ltrim plus rtrim; whitespace on both sides of the substitution reference is removed.

Date

Directive Type:

"date"

Doctree Element:

Text

Directive Arguments:

one, optional (date format)

Directive Options:

none

Directive Content:

none

The "date" directive generates the current local date and inserts it into the document as text. This directive may be used in substitution definitions only.

The optional directive content is interpreted as the desired date format, using the same codes as Python's time.strftime() function. The default format is "%Y-%m-%d" (ISO 8601 date), but time fields can also be used. Examples:

.. |date| date::
.. |time| date:: %H:%M

Today's date is |date|.

This document was generated on |date| at |time|.

Miscellaneous

Including an External Document Fragment

Directive Type:

"include"

Doctree Elements:

Depend on data being included; <literal_block> with code or literal option.

Directive Arguments:

one, required (path to the file to include)

Directive Options:

see below

Directive Content:

none

Configuration Setting:

file_insertion_enabled

The "include" directive reads a text file. The directive argument is the path to the file to be included, relative to the document containing the directive. Unless the options literal, code, or parser are given, the file is parsed in the current document's context at the point of the directive. For example:

This first example will be parsed at the document level, and can
thus contain any construct, including section headers.

.. include:: inclusion.rst

Back in the main document.

    This second example will be parsed in a block quote context.
    Therefore it may only contain body elements.  It may not
    contain section headers.

    .. include:: inclusion.rst

If an included document fragment contains section structure, the title adornments must match those of the master document.

Standard data files intended for inclusion in reStructuredText documents are distributed with the Docutils source code, located in the "docutils" package in the docutils/parsers/rst/include directory. To access these files, use the special syntax for standard "include" data files, angle brackets around the file name:

.. include:: <isonum.txt>

The current set of standard "include" data files consists of sets of substitution definitions. See reStructuredText Standard Definition Files for details.

The "include" directive recognizes the following options:

codetext (formal language, optional)

The argument and the included content are passed to the code directive (useful for program listings).

encodingencoding

The text encoding of the external file. Defaults to the document's input_encoding.

end-beforetext

Only the content before the first occurrence of the specified text in the external data file (but after any start-after text) will be included.

end-lineinteger

Only the content up to (but excluding) this line will be included.

literalflag

The entire included text is inserted into the document as a single literal block.

number-linesinteger (start line number, optional)

Precede every included line with a line number. The optional argument is the number of the first line (default 1). Works only with code or literal.

parsertext (parser name)

Parse the included content with the specified parser. See the "parser" configuration setting for available parsers.

(New in Docutils 0.17)

start-aftertext

Only the content after the first occurrence of the specified text in the external data file will be included.

start-lineinteger

Only the content starting from this line will be included. (As usual in Python, the first line has index 0 and negative values count from the end.)

tab-widthinteger

Number of spaces for hard tab expansion. Must be a positive integer, except for literal inclusions and code, where a negative value prevents expansion of hard tabs. Defaults to the tab_width configuration setting.

With code or literal the common options class and name are recognized as well.

Combining start-line/end-line and start-after/end-before is possible. The text markers will be searched in the specified lines (further limiting the included content).

Raw Data Pass-Through

Directive Type:

"raw"

Doctree Element:

<raw>

Directive Arguments:

one or more, required (output format types)

Directive Options:

see below

Directive Content:

Stored verbatim, uninterpreted. None (empty) if a file or url option given.

Configuration Settings:

raw_enabled, file_insertion_enabled

The "raw" directive indicates non-reStructuredText data that is to be passed untouched to the Writer. The names of the output formats are given in the directive arguments. The interpretation of the raw data is up to the Writer. A Writer may ignore any raw output not matching its format.

For example, the following input would be passed untouched by an HTML writer:

.. raw:: html

   <hr width=50 size=10>

A LaTeX Writer could insert the following raw content into its output stream:

.. raw:: latex

   \setlength{\parindent}{0pt}

Raw data can also be read from an external file, specified in the file or url directive option. In this case, the content block must be empty. For example:

.. raw:: html
   :file: inclusion.html

Inline equivalents of the "raw" directive can be defined via custom interpreted text roles derived from the "raw" role.

The "raw" directive recognizes the common option class as well as

encodingencoding

The text encoding of the external raw data (with file or url). Defaults to the main document's input_encoding.

filepath

The local filesystem path of a raw data file to be included.

urlURI

A URI reference to a raw data file to be included.

Class

Directive Type:

"class"

Doctree Element:

<pending>

Directive Arguments:

one or more, required (class names / attribute values)

Directive Options:

none

Directive Content:

Optional. If present, it is interpreted as body elements.

The "class" directive sets the classes attribute value on its content or on the first immediately following [10] non-comment element [11]. The directive argument consists of one or more space-separated class names. The names are transformed to conform to the regular expression [a-z](-?[a-z0-9]+)* (see Identifier Normalization below).

Examples:

.. class:: special

This is a "special" paragraph.

.. class:: exceptional remarkable

An Exceptional Section
======================

This is an ordinary paragraph.

.. class:: multiple

   First paragraph.

   Second paragraph.

The text above is parsed and transformed into this doctree fragment:

<paragraph classes="special">
    This is a "special" paragraph.
<section classes="exceptional remarkable">
    <title>
        An Exceptional Section
    <paragraph>
        This is an ordinary paragraph.
    <paragraph classes="multiple">
        First paragraph.
    <paragraph classes="multiple">
        Second paragraph.

Identifier Normalization

Docutils normalizes class names and identifiers to conform to the regular expression "[a-z](-?[a-z0-9]+)*" by converting

  • alphabetic characters to lowercase,

  • accented characters to the base character,

  • non-alphanumeric characters to hyphens,

  • consecutive hyphens into one hyphen

and stripping

  • leading hyphens and number characters, and

  • trailing hyphens.

For example "Rot.Gelb&Grün:+2008" becomes "rot-gelb-grun-2008" and "1000_Steps!" becomes "steps".

Custom Interpreted Text Roles

Directive Type:

"role"

Doctree Element:

none; affects subsequent parsing

Directive Arguments:

two; one required (new role name), one optional (base role name, in parentheses)

Directive Options:

see below

Directive Content:

depends on base role.

The "role" directive dynamically creates a custom interpreted text role and registers it with the parser. This means that after declaring a role like this:

.. role:: custom

the document may use the new "custom" role:

An example of using :custom:`interpreted text`

This will be parsed into the following document tree fragment:

<paragraph>
    An example of using
    <inline classes="custom">
        interpreted text

Role names are case insensitive and must conform to the rules of simple reference names (but do not share a namespace with hyperlinks, footnotes, and citations).

The new role may be based on an existing role, specified as a second argument in parentheses (whitespace optional):

.. role:: custom(emphasis)

:custom:`text`

The parsed result is as follows:

<paragraph>
    <emphasis classes="custom">
        text

A special case is the "raw" role: derived roles enable inline raw data pass-through, e.g.:

.. role:: raw-role(raw)
   :format: html latex

:raw-role:`raw text`

If no base role is explicitly specified, a generic custom role is automatically used. Subsequent interpreted text will produce an <inline> element with a classes attribute, as in the first example above.

Depending on the base role, the following options may be recognized by the "role" directive:

classspace separated list of class names

Set the classes attribute value on the element produced when the custom interpreted text role is used. Default value is the directive argument (role name).

For example

.. role:: custom
   :class: special

:custom:`interpreted text`

is parsed as

<paragraph>
    <inline classes="special">
        interpreted text

The "class" option is recognized with all interpreted text roles.

formatspace-separated list of output format names (writer names)

Specify the generated <raw> element's format attribute.

Only recognized with the "raw" base role.

languagetext

Name of a formal language, passed to Pygments for syntax highlighting. See supported languages and markup formats for recognized values.

Only recognized with the "code" base role.

Setting the Default Interpreted Text Role

Directive Type:

"default-role"

Doctree Element:

none; affects subsequent parsing

Directive Arguments:

one, optional (new default role name)

Directive Options:

none

Directive Content:

none

The "default-role" directive sets the default interpreted text role, the role that is used for interpreted text without an explicit role. For example, after setting the default role like this:

.. default-role:: subscript

any subsequent use of implicit-role interpreted text in the document will use the "subscript" role:

An example of a `default` role.

This will be parsed into the following document tree fragment:

<paragraph>
    An example of a
    <subscript>
        default
     role.

Custom roles may be used (see the "role" directive above), but it must have been declared in a document before it can be set as the default role. See the reStructuredText Interpreted Text Roles document for details of built-in roles.

The directive may be used without an argument to restore the initial default interpreted text role, which is application-dependent. The initial default interpreted text role of the standard reStructuredText parser is "title-reference".

Metadata

Directive Type:

"meta"

Doctree Element:

<meta>

Directive Arguments:

none

Directive Options:

none

Directive Content:

Must contain a flat field list.

The "meta" directive is used to specify metadata[13] to be stored in, e.g., HTML meta elements or as ODT file properties. The LaTeX writer passes it to the pdfinfo option of the hyperref package. If an output format does not support "invisible" metadata, content is silently dropped by the writer.

Within the directive block, a flat field list provides the syntax for metadata. The field name becomes the contents of the "name" attribute of the META tag, and the field body (interpreted as a single string without inline markup) becomes the contents of the "content" attribute. For example:

.. meta::
   :description: The reStructuredText plaintext markup language
   :keywords: plaintext, markup language

This would be converted to the following HTML:

<meta name="description"
    content="The reStructuredText plaintext markup language">
<meta name="keywords" content="plaintext, markup language">

Support for other META attributes ("http-equiv", "scheme", "lang", "dir") are provided through field arguments, which must be of the form "attr=value":

.. meta::
   :description lang=en: An amusing story
   :description lang=fr: Une histoire amusante

And their HTML equivalents:

<meta name="description" lang="en" content="An amusing story">
<meta name="description" lang="fr" content="Une histoire amusante">

Some META tags use an "http-equiv" attribute instead of the "name" attribute. To specify "http-equiv" META tags, simply omit the name:

.. meta::
   :http-equiv=Content-Type: text/html; charset=ISO-8859-1

HTML equivalent:

<meta http-equiv="Content-Type"
     content="text/html; charset=ISO-8859-1">

Metadata Document Title

Directive Type:

"title"

Doctree Element:

sets the <document> element's title attribute)

Directive Arguments:

one, required (the title text)

Directive Options:

none

Directive Content:

none

Configuration Setting:

title

The "title" directive specifies the document title as metadata, which does not become part of the document body. It overrides the document-supplied document title and the "title" configuration setting.

Restructuredtext-Test-Directive

Directive Type:

"restructuredtext-test-directive"

Doctree Element:

<system_message>

Directive Arguments:

none

Directive Options:

none

Directive Content:

Interpreted as a literal block.

This directive is provided for test purposes only. (Nobody is expected to type in a name that long!) It is converted into a level-1 (info) system message showing the directive data, possibly followed by a literal block containing the rest of the directive block.

Common Options

Most of the directives that generate doctree elements support the following options:

classtext (space separated list of class names)

Set a classes attribute value on the doctree element generated by the directive. For example,

.. image:: bild.png
   :alt:   example picture
   :class: large-pics

is the recommended syntax alternative to a preceding class directive

.. class:: large-pics
.. image:: bild.png
   :alt:   example picture
nametext

Add text to the names attribute of the doctree element generated by the directive. This allows hyperlink references to the element using text as reference name. For example,

.. image:: bild.png
   :alt:   example picture
   :name:  my picture

is the recommended syntax alternative to a preceding hyperlink target

.. _my picture:
.. image:: bild.png
   :alt:   example picture

Common Option Value Types

"keyword":

recognized keywords

Used without quotes in the reStructuredText source.

character:

single character

May be specified as literal character or as Unicode character code (cf. the unicode directive).

encoding:

text encoding name

Docutils looks it up in the list of registered codecs (see also Standard Encodings).

flag:

no value

integer:

integer number

A list of integers may be comma- or whitespace-separated.

length:

number, optionally followed by one of the supported length units

Handling of values without unit depends on the writer/output format. See the writer specific documentation in the user doc for details.

path:

local filesystem path

Newlines are removed. The root_prefix configuration setting can be used to tell Docutils to interpret paths starting with "/" relative to a "project directory".

percentage:

number followed by the percent sign '%'

Percentage values are relative to other values, depending on the context in which they occur.

text:

free text

Possible restrictions are given in parentheses.

URI:

URI reference

Full URI or relative reference (absolute or relative path reference, cf. RFC 3986). Whitespace is removed (cf. external hyperlink targets in the reStructuredText specification).