Debian Codegraph @

docs/howto/rst-directives.rst

raw
1 .. include:: ../header.rst
2
3 =======================================
4 Creating reStructuredText_ Directives
5 =======================================
6
7 :Authors: Dethe Elza, David Goodger, Lea Wiemann
8 :Contact: [email protected]
9 :Date: $Date: 2024-08-15 10:43:38 +0200 (Do, 15. Aug 2024) $
10 :Revision: $Revision: 9906 $
11 :Copyright: This document has been placed in the public domain.
12
13 .. _reStructuredText: https://docutils.sourceforge.io/rst.html
14
15
16 Directives are the primary extension mechanism of reStructuredText.
17 This document aims to make the creation of new directives as easy and
18 understandable as possible. There are only a couple of
19 reStructuredText-specific features the developer needs to know to
20 create a basic directive.
21
22 The syntax of directives is detailed in the `reStructuredText Markup
23 Specification`_, and standard directives are described in
24 `reStructuredText Directives`_.
25
26 Directives are a reStructuredText markup/parser concept. There is no
27 "directive" document tree element, no single element that corresponds
28 exactly to the concept of directives. Instead, choose the most
29 appropriate elements from the existing Docutils elements. Directives
30 build structures using the existing building blocks. See `The
31 Docutils Document Tree`_ and the ``docutils.nodes`` module for more
32 about the building blocks of Docutils documents.
33
34 .. _reStructuredText Markup Specification:
35 ../ref/rst/restructuredtext.html#directives
36 .. _reStructuredText Directives: ../ref/rst/directives.html
37 .. _The Docutils Document Tree: ../ref/doctree.html
38
39
40 .. contents:: Table of Contents
41
42
43 The Directive Class
44 ===================
45
46 Directives are created by defining a directive class that inherits
47 from ``docutils.parsers.rst.Directive``::
48
49 from docutils.parsers import rst
50
51 class MyDirective(rst.Directive):
52
53 ...
54
55 To understand how to implement the directive, let's have a look at the
56 docstring of the ``Directive`` base class::
57
58 >>> from docutils.parsers import rst
59 >>> print rst.Directive.__doc__
60
61 Base class for reStructuredText directives.
62
63 The following attributes may be set by subclasses. They are
64 interpreted by the directive parser (which runs the directive
65 class):
66
67 - `required_arguments`: The number of required arguments (default:
68 0).
69
70 - `optional_arguments`: The number of optional arguments (default:
71 0).
72
73 - `final_argument_whitespace`: A boolean, indicating if the final
74 argument may contain whitespace (default: False).
75
76 - `option_spec`: A dictionary, mapping known option names to
77 conversion functions such as `int` or `float` (default: {}, no
78 options). Several conversion functions are defined in the
79 directives/__init__.py module.
80
81 Option conversion functions take a single parameter, the option
82 argument (a string or ``None``), validate it and/or convert it
83 to the appropriate form. Conversion functions may raise
84 `ValueError` and `TypeError` exceptions.
85
86 - `has_content`: A boolean; True if content is allowed. Client
87 code must handle the case where content is required but not
88 supplied (an empty content list will be supplied).
89
90 Arguments are normally single whitespace-separated words. The
91 final argument may contain whitespace and/or newlines if
92 `final_argument_whitespace` is True.
93
94 If the form of the arguments is more complex, specify only one
95 argument (either required or optional) and set
96 `final_argument_whitespace` to True; the client code must do any
97 context-sensitive parsing.
98
99 When a directive implementation is being run, the directive class
100 is instantiated, and the `run()` method is executed. During
101 instantiation, the following instance variables are set:
102
103 - ``name`` is the directive type or name (string).
104
105 - ``arguments`` is the list of positional arguments (strings).
106
107 - ``options`` is a dictionary mapping option names (strings) to
108 values (type depends on option conversion functions; see
109 `option_spec` above).
110
111 - ``content`` is a list of strings, the directive content line by line.
112
113 - ``lineno`` is the line number of the first line of the directive.
114
115 - ``content_offset`` is the line offset of the first line of the content from
116 the beginning of the current input. Used when initiating a nested parse.
117
118 - ``block_text`` is a string containing the entire directive.
119
120 - ``state`` is the state which called the directive function.
121
122 - ``state_machine`` is the state machine which controls the state which called
123 the directive function.
124
125 Directive functions return a list of nodes which will be inserted
126 into the document tree at the point where the directive was
127 encountered. This can be an empty list if there is nothing to
128 insert.
129
130 For ordinary directives, the list must contain body elements or
131 structural elements. Some directives are intended specifically
132 for substitution definitions, and must return a list of `Text`
133 nodes and/or inline elements (suitable for inline insertion, in
134 place of the substitution reference). Such directives must verify
135 substitution definition context, typically using code like this::
136
137 if not isinstance(state, states.SubstitutionDef):
138 error = state_machine.reporter.error(
139 'Invalid context: the "%s" directive can only be used '
140 'within a substitution definition.' % (name),
141 nodes.literal_block(block_text, block_text), line=lineno)
142 return [error]
143
144 >>>
145
146
147 Option Conversion Functions
148 ===========================
149
150 An option specification (``Directive.option_spec``) must be defined
151 detailing the options available to the directive. An option spec is a
152 mapping of option name to conversion function; conversion functions
153 are applied to each option value to check validity and convert them to
154 the expected type. Python's built-in conversion functions are often
155 usable for this, such as ``int``, ``float``. Other useful conversion
156 functions are included in the ``docutils.parsers.rst.directives``
157 package (in the ``__init__.py`` module):
158
159 - ``flag``: For options with no option arguments. Checks for an
160 argument (raises ``ValueError`` if found), returns ``None`` for
161 valid flag options.
162
163 - ``unchanged_required``: Returns the text argument, unchanged.
164 Raises ``ValueError`` if no argument is found.
165
166 - ``unchanged``: Returns the text argument, unchanged. Returns an
167 empty string ("") if no argument is found.
168
169 - ``path``: Returns the path argument unwrapped (with newlines
170 removed). Raises ``ValueError`` if no argument is found.
171
172 - ``uri``: Returns the value (URI-reference) with whitespace removed.
173 Raises ``ValueError`` if no argument is found.
174
175 - ``nonnegative_int``: Checks for a nonnegative integer argument,
176 and raises ``ValueError`` if not.
177
178 - ``class_option``: Converts the argument into an ID-compatible
179 string and returns it. Raises ``ValueError`` if no argument is
180 found.
181
182 - ``unicode_code``: Convert a Unicode character code to a Unicode
183 character.
184
185 - ``single_char_or_unicode``: A single character is returned as-is.
186 Unicode characters codes are converted as in ``unicode_code``.
187
188 - ``single_char_or_whitespace_or_unicode``: As with
189 ``single_char_or_unicode``, but "tab" and "space" are also
190 supported.
191
192 - ``positive_int``: Converts the argument into an integer. Raises
193 ValueError for negative, zero, or non-integer values.
194
195 - ``positive_int_list``: Converts a space- or comma-separated list
196 of integers into a Python list of integers. Raises ValueError for
197 non-positive-integer values.
198
199 - ``encoding``: Verifies the encoding argument by lookup. Raises
200 ValueError for unknown encodings.
201
202 A further utility function, ``choice``, is supplied to enable
203 options whose argument must be a member of a finite set of possible
204 values. A custom conversion function must be written to use it.
205 For example::
206
207 from docutils.parsers.rst import directives
208
209 def yesno(argument):
210 return directives.choice(argument, ('yes', 'no'))
211
212 For example, here is an option spec for a directive which allows two
213 options, "name" and "value", each with an option argument::
214
215 option_spec = {'name': unchanged, 'value': int}
216
217
218 Error Handling
219 ==============
220
221 If your directive implementation encounters an error during
222 processing, you should call ``self.error()`` inside the ``run()``
223 method::
224
225 if error_condition:
226 raise self.error('Error message.')
227
228 The ``self.error()`` method will immediately raise an exception that
229 will be caught by the reStructuredText directive handler. The
230 directive handler will then insert an error-level system message in
231 the document at the place where the directive occurred.
232
233 Instead of ``self.error``, you can also use ``self.severe`` and
234 ``self.warning`` for more or less severe problems.
235
236 If you want to return a system message *and* document contents, you need to
237 create the system message yourself instead of using the ``self.error``
238 convenience method::
239
240 def run(self):
241 # Create node(s).
242 node = nodes.paragraph(...)
243 # Node list to return.
244 node_list = [node]
245 if error_condition:
246 # Create system message.
247 error = self.reporter.error(
248 'Error in "%s" directive: Your error message.' % self.name,
249 nodes.literal_block(block_text, block_text), line=lineno)
250 node_list.append(error)
251 return node_list
252
253
254 Register the Directive
255 ======================
256
257 * If the directive is a general-use **addition to the Docutils core**,
258 it must be registered with the parser and language mappings added:
259
260 1. Register the new directive using its canonical name in
261 ``docutils/parsers/rst/directives/__init__.py``, in the
262 ``_directive_registry`` dictionary. This allows the
263 reStructuredText parser to find and use the directive.
264
265 2. Add an entry to the ``directives`` dictionary in
266 ``docutils/parsers/rst/languages/en.py`` for the directive, mapping
267 the English name to the canonical name (both lowercase). Usually
268 the English name and the canonical name are the same.
269
270 3. Update all the other language modules as well. For languages in
271 which you are proficient, please add translations. For other
272 languages, add the English directive name plus "(translation
273 required)".
274
275 * If the directive is **application-specific**, use the
276 ``register_directive`` function::
277
278 from docutils.parsers.rst import directives
279 directives.register_directive(directive_name, directive_class)
280
281
282 Examples
283 ========
284
285 For the most direct and accurate information, "Use the Source, Luke!".
286 All standard directives are documented in `reStructuredText
287 Directives`_, and the source code implementing them is located in the
288 ``docutils/parsers/rst/directives`` package. The ``__init__.py``
289 module contains a mapping of directive name to module and function
290 name. Several representative directives are described below.
291
292
293 Admonitions
294 -----------
295
296 `Admonition directives`__, such as "note" and "caution", are quite
297 simple. They have no directive arguments or options. Admonition
298 directive content is interpreted as ordinary reStructuredText.
299
300 __ ../ref/rst/directives.html#specific-admonitions
301
302 The resulting document tree for a simple reStructuredText line
303 "``.. note:: This is a note.``" looks as follows:
304
305 <note>
306 <paragraph>
307 This is a note.
308
309 The directive class for the "note" directive simply derives from a
310 generic admonition directive class::
311
312 class Note(BaseAdmonition):
313
314 node_class = nodes.note
315
316 Note that the only thing distinguishing the various admonition
317 directives is the element (node class) generated. In the code above,
318 the node class is set as a class attribute and is read by the
319 ``run()`` method of ``BaseAdmonition``, where the actual processing
320 takes place::
321
322 # Import Docutils document tree nodes module.
323 from docutils import nodes
324 # Import Directive base class.
325 from docutils.parsers.rst import Directive
326
327 class BaseAdmonition(Directive):
328
329 required_arguments = 0
330 optional_arguments = 0
331 final_argument_whitespace = True
332 option_spec = {}
333 has_content = True
334
335 node_class = None
336 """Subclasses must set this to the appropriate admonition node class."""
337
338 def run(self):
339 # Raise an error if the directive does not have contents.
340 self.assert_has_content()
341 text = '\n'.join(self.content)
342 # Create the admonition node, to be populated by `nested_parse`.
343 admonition_node = self.node_class(rawsource=text)
344 # Parse the directive contents.
345 self.state.nested_parse(self.content, self.content_offset,
346 admonition_node)
347 return [admonition_node]
348
349 Three things are noteworthy in the ``run()`` method above:
350
351 * The ``admonition_node = self.node_class(text)`` line creates the
352 wrapper element, using the class set by the specific admonition
353 subclasses (as in note, ``node_class = nodes.note``).
354
355 * The call to ``state.nested_parse()`` is what does the actual
356 processing. It parses the directive content and adds any generated
357 elements as child elements of ``admonition_node``.
358
359 * If there was no directive content, the ``assert_has_content()``
360 convenience method raises an error exception by calling
361 ``self.error()`` (see `Error Handling`_ above).
362
363
364 "image"
365 -------
366
367 .. _image: ../ref/rst/directives.html#image
368
369 The "image_" directive is used to insert a picture into a document.
370 This directive has one argument, the path to the image file, and
371 supports several options. There is no directive content. Here's an
372 early version of the image directive class::
373
374 # Import Docutils document tree nodes module.
375 from docutils import nodes
376 # Import ``directives`` module (contains conversion functions).
377 from docutils.parsers.rst import directives
378 # Import Directive base class.
379 from docutils.parsers.rst import Directive
380
381 def align(argument):
382 """Conversion function for the "align" option."""
383 return directives.choice(argument, ('left', 'center', 'right'))
384
385 class Image(Directive):
386
387 required_arguments = 1
388 optional_arguments = 0
389 final_argument_whitespace = True
390 option_spec = {'alt': directives.unchanged,
391 'height': directives.nonnegative_int,
392 'width': directives.nonnegative_int,
393 'scale': directives.nonnegative_int,
394 'align': align,
395 }
396 has_content = False
397
398 def run(self):
399 reference = directives.uri(self.arguments[0])
400 self.options['uri'] = reference
401 image_node = nodes.image(rawsource=self.block_text,
402 **self.options)
403 return [image_node]
404
405 Several things are noteworthy in the code above:
406
407 * The "image" directive requires a single argument, which is allowed
408 to contain whitespace (``final_argument_whitespace = True``). This
409 is to allow for long URLs which may span multiple lines. The first
410 line of the ``run()`` method joins the URL, discarding any embedded
411 whitespace.
412
413 * The reference is added to the ``options`` dictionary under the
414 "uri" key; this becomes an attribute of the ``nodes.image`` element
415 object. Any other attributes have already been set explicitly in
416 the reStructuredText source text.
417
418
419 The Pending Element
420 -------------------
421
422 Directives that cause actions to be performed *after* the complete
423 document tree has been generated can be implemented using a
424 ``pending`` node. The ``pending`` node causes a transform_ to be run
425 after the document has been parsed.
426
427 For an example usage of the ``pending`` node, see the implementation
428 of the ``contents`` directive in
429 docutils.parsers.rst.directives.parts__.
430
431 .. _transform: ../api/transforms.html
432 __ https://docutils.sourceforge.io/docutils/parsers/rst/directives/parts.py