Docutils markup API¶
This section describes the API for adding ReST markup elements (roles and directives).
The markup syntax of the new directive is determined by the follow five class attributes:
Number of required directive arguments.
Number of optional arguments after the required arguments.
May the final argument contain whitespace?
Mapping of option names to validator functions.
Option validator functions take a single parameter, the option argument (or
Noneif not given), and should validate it or convert it to the proper form. They raise
TypeErrorto indicate failure.
There are several predefined and possibly useful validators in the
May the directive have content?
New directives must implement the
This method must process the directive arguments, options and content, and return a list of Docutils/Sphinx nodes that will be inserted into the document tree at the point where the directive was encountered.
Instance attributes that are always set on the directive are:
The directive name (useful when registering the same directive class under multiple names).
The arguments given to the directive, as a list.
The options given to the directive, as a dictionary mapping option names to validated/converted values.
The directive content, if given, as a
The absolute line number on which the directive appeared. This is not always a useful value; use
The source file of the directive.
The line number in the source file on which the directive appeared.
Internal offset of the directive content. Used when calling
The string containing the entire directive.
Docutils represents document source lines in a class
docutils.statemachine.ViewList. This is a list with extended functionality
– for one, slicing creates views of the original list, and also the list
contains information about the source line numbers.
Directive.content attribute is a ViewList. If you generate content
to be parsed as ReST, you have to create a ViewList yourself. Important for
content generation are the following points:
- The constructor takes a list of strings (lines) and a source (document) name.
.append()method takes a line and a source name as well.
Parsing directive content as ReST¶
Many directives will contain more markup that must be parsed. To do this, use
one of the following APIs from the
sphinx.util.nodes.nested_parse_with_titles()– this allows titles in the parsed content.
Both APIs parse the content into a given node. They are used like this:
node = docutils.nodes.paragraph() # either from sphinx.ext.autodoc import AutodocReporter self.state.memo.reporter = AutodocReporter(self.result, self.state.memo.reporter) # override reporter to avoid errors from "include" directive nested_parse_with_titles(self.state, self.result, node) # or self.state.nested_parse(self.result, 0, node)
If you don’t need the wrapping node, you can use any concrete node type and
node.children from the Directive.
- Creating directives
- HOWTO of the Docutils documentation