Server IP : 127.0.0.2 / Your IP : 18.222.48.95 Web Server : Apache/2.4.18 (Ubuntu) System : User : www-data ( ) PHP Version : 7.0.33-0ubuntu0.16.04.16 Disable Function : disk_free_space,disk_total_space,diskfreespace,dl,exec,fpaththru,getmyuid,getmypid,highlight_file,ignore_user_abord,leak,listen,link,opcache_get_configuration,opcache_get_status,passthru,pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,php_uname,phpinfo,posix_ctermid,posix_getcwd,posix_getegid,posix_geteuid,posix_getgid,posix_getgrgid,posix_getgrnam,posix_getgroups,posix_getlogin,posix_getpgid,posix_getpgrp,posix_getpid,posix,_getppid,posix_getpwnam,posix_getpwuid,posix_getrlimit,posix_getsid,posix_getuid,posix_isatty,posix_kill,posix_mkfifo,posix_setegid,posix_seteuid,posix_setgid,posix_setpgid,posix_setsid,posix_setuid,posix_times,posix_ttyname,posix_uname,pclose,popen,proc_open,proc_close,proc_get_status,proc_nice,proc_terminate,shell_exec,source,show_source,system,virtual MySQL : OFF | cURL : ON | WGET : ON | Perl : ON | Python : ON | Sudo : ON | Pkexec : ON Directory : /usr/share/doc/docutils-doc/docs/howto/ |
Upload File : |
<?xml version="1.0" encoding="utf-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="generator" content="Docutils 0.12: http://docutils.sourceforge.net/" /> <title>Creating reStructuredText Directives</title> <meta name="authors" content="Dethe Elza David Goodger Lea Wiemann" /> <meta name="date" content="2012-01-03" /> <meta name="copyright" content="This document has been placed in the public domain." /> <link rel="stylesheet" href="../../css/html4css1.css" type="text/css" /> </head> <body> <div class="document" id="creating-restructuredtext-directives"> <h1 class="title">Creating <a class="reference external" href="http://docutils.sourceforge.net/rst.html">reStructuredText</a> Directives</h1> <table class="docinfo" frame="void" rules="none"> <col class="docinfo-name" /> <col class="docinfo-content" /> <tbody valign="top"> <tr><th class="docinfo-name">Authors:</th> <td>Dethe Elza <br />David Goodger <br />Lea Wiemann</td></tr> <tr><th class="docinfo-name">Contact:</th> <td><a class="first last reference external" href="mailto:docutils-develop@lists.sourceforge.net">docutils-develop@lists.sourceforge.net</a></td></tr> <tr><th class="docinfo-name">Date:</th> <td>2012-01-03</td></tr> <tr><th class="docinfo-name">Revision:</th> <td>7302</td></tr> <tr><th class="docinfo-name">Copyright:</th> <td>This document has been placed in the public domain.</td></tr> </tbody> </table> <p>Directives are the primary extension mechanism of reStructuredText. This document aims to make the creation of new directives as easy and understandable as possible. There are only a couple of reStructuredText-specific features the developer needs to know to create a basic directive.</p> <p>The syntax of directives is detailed in the <a class="reference external" href="../ref/rst/restructuredtext.html#directives">reStructuredText Markup Specification</a>, and standard directives are described in <a class="reference external" href="../ref/rst/directives.html">reStructuredText Directives</a>.</p> <p>Directives are a reStructuredText markup/parser concept. There is no "directive" document tree element, no single element that corresponds exactly to the concept of directives. Instead, choose the most appropriate elements from the existing Docutils elements. Directives build structures using the existing building blocks. See <a class="reference external" href="../ref/doctree.html">The Docutils Document Tree</a> and the <tt class="docutils literal">docutils.nodes</tt> module for more about the building blocks of Docutils documents.</p> <div class="contents topic" id="table-of-contents"> <p class="topic-title first">Table of Contents</p> <ul class="simple"> <li><a class="reference internal" href="#the-directive-class" id="id4">The Directive Class</a></li> <li><a class="reference internal" href="#option-conversion-functions" id="id5">Option Conversion Functions</a></li> <li><a class="reference internal" href="#error-handling" id="id6">Error Handling</a></li> <li><a class="reference internal" href="#register-the-directive" id="id7">Register the Directive</a></li> <li><a class="reference internal" href="#examples" id="id8">Examples</a><ul> <li><a class="reference internal" href="#admonitions" id="id9">Admonitions</a></li> <li><a class="reference internal" href="#image" id="id10">"image"</a></li> <li><a class="reference internal" href="#the-pending-element" id="id11">The Pending Element</a></li> </ul> </li> </ul> </div> <div class="section" id="the-directive-class"> <h1><a class="toc-backref" href="#id4">The Directive Class</a></h1> <p>Directives are created by defining a directive class that inherits from <tt class="docutils literal">docutils.parsers.rst.Directive</tt>:</p> <pre class="literal-block"> from docutils.parsers import rst class MyDirective(rst.Directive): ... </pre> <p>To understand how to implement the directive, let's have a look at the docstring of the <tt class="docutils literal">Directive</tt> base class:</p> <pre class="literal-block"> >>> from docutils.parsers import rst >>> print rst.Directive.__doc__ Base class for reStructuredText directives. The following attributes may be set by subclasses. They are interpreted by the directive parser (which runs the directive class): - `required_arguments`: The number of required arguments (default: 0). - `optional_arguments`: The number of optional arguments (default: 0). - `final_argument_whitespace`: A boolean, indicating if the final argument may contain whitespace (default: False). - `option_spec`: A dictionary, mapping known option names to conversion functions such as `int` or `float` (default: {}, no options). Several conversion functions are defined in the directives/__init__.py module. Option conversion functions take a single parameter, the option argument (a string or ``None``), validate it and/or convert it to the appropriate form. Conversion functions may raise `ValueError` and `TypeError` exceptions. - `has_content`: A boolean; True if content is allowed. Client code must handle the case where content is required but not supplied (an empty content list will be supplied). Arguments are normally single whitespace-separated words. The final argument may contain whitespace and/or newlines if `final_argument_whitespace` is True. If the form of the arguments is more complex, specify only one argument (either required or optional) and set `final_argument_whitespace` to True; the client code must do any context-sensitive parsing. When a directive implementation is being run, the directive class is instantiated, and the `run()` method is executed. During instantiation, the following instance variables are set: - ``name`` is the directive type or name (string). - ``arguments`` is the list of positional arguments (strings). - ``options`` is a dictionary mapping option names (strings) to values (type depends on option conversion functions; see `option_spec` above). - ``content`` is a list of strings, the directive content line by line. - ``lineno`` is the line number of the first line of the directive. - ``content_offset`` is the line offset of the first line of the content from the beginning of the current input. Used when initiating a nested parse. - ``block_text`` is a string containing the entire directive. - ``state`` is the state which called the directive function. - ``state_machine`` is the state machine which controls the state which called the directive function. Directive functions return a list of nodes which will be inserted into the document tree at the point where the directive was encountered. This can be an empty list if there is nothing to insert. For ordinary directives, the list must contain body elements or structural elements. Some directives are intended specifically for substitution definitions, and must return a list of `Text` nodes and/or inline elements (suitable for inline insertion, in place of the substitution reference). Such directives must verify substitution definition context, typically using code like this:: if not isinstance(state, states.SubstitutionDef): error = state_machine.reporter.error( 'Invalid context: the "%s" directive can only be used ' 'within a substitution definition.' % (name), nodes.literal_block(block_text, block_text), line=lineno) return [error] >>> </pre> </div> <div class="section" id="option-conversion-functions"> <h1><a class="toc-backref" href="#id5">Option Conversion Functions</a></h1> <p>An option specification (<tt class="docutils literal">Directive.option_spec</tt>) must be defined detailing the options available to the directive. An option spec is a mapping of option name to conversion function; conversion functions are applied to each option value to check validity and convert them to the expected type. Python's built-in conversion functions are often usable for this, such as <tt class="docutils literal">int</tt>, <tt class="docutils literal">float</tt>. Other useful conversion functions are included in the <tt class="docutils literal">docutils.parsers.rst.directives</tt> package (in the <tt class="docutils literal">__init__.py</tt> module):</p> <ul class="simple"> <li><tt class="docutils literal">flag</tt>: For options with no option arguments. Checks for an argument (raises <tt class="docutils literal">ValueError</tt> if found), returns <tt class="docutils literal">None</tt> for valid flag options.</li> <li><tt class="docutils literal">unchanged_required</tt>: Returns the text argument, unchanged. Raises <tt class="docutils literal">ValueError</tt> if no argument is found.</li> <li><tt class="docutils literal">unchanged</tt>: Returns the text argument, unchanged. Returns an empty string ("") if no argument is found.</li> <li><tt class="docutils literal">path</tt>: Returns the path argument unwrapped (with newlines removed). Raises <tt class="docutils literal">ValueError</tt> if no argument is found.</li> <li><tt class="docutils literal">uri</tt>: Returns the URI argument with whitespace removed. Raises <tt class="docutils literal">ValueError</tt> if no argument is found.</li> <li><tt class="docutils literal">nonnegative_int</tt>: Checks for a nonnegative integer argument, and raises <tt class="docutils literal">ValueError</tt> if not.</li> <li><tt class="docutils literal">class_option</tt>: Converts the argument into an ID-compatible string and returns it. Raises <tt class="docutils literal">ValueError</tt> if no argument is found.</li> <li><tt class="docutils literal">unicode_code</tt>: Convert a Unicode character code to a Unicode character.</li> <li><tt class="docutils literal">single_char_or_unicode</tt>: A single character is returned as-is. Unicode characters codes are converted as in <tt class="docutils literal">unicode_code</tt>.</li> <li><tt class="docutils literal">single_char_or_whitespace_or_unicode</tt>: As with <tt class="docutils literal">single_char_or_unicode</tt>, but "tab" and "space" are also supported.</li> <li><tt class="docutils literal">positive_int</tt>: Converts the argument into an integer. Raises ValueError for negative, zero, or non-integer values.</li> <li><tt class="docutils literal">positive_int_list</tt>: Converts a space- or comma-separated list of integers into a Python list of integers. Raises ValueError for non-positive-integer values.</li> <li><tt class="docutils literal">encoding</tt>: Verfies the encoding argument by lookup. Raises ValueError for unknown encodings.</li> </ul> <p>A further utility function, <tt class="docutils literal">choice</tt>, is supplied to enable options whose argument must be a member of a finite set of possible values. A custom conversion function must be written to use it. For example:</p> <pre class="literal-block"> from docutils.parsers.rst import directives def yesno(argument): return directives.choice(argument, ('yes', 'no')) </pre> <p>For example, here is an option spec for a directive which allows two options, "name" and "value", each with an option argument:</p> <pre class="literal-block"> option_spec = {'name': unchanged, 'value': int} </pre> </div> <div class="section" id="error-handling"> <h1><a class="toc-backref" href="#id6">Error Handling</a></h1> <p>If your directive implementation encounters an error during processing, you should call <tt class="docutils literal">self.error()</tt> inside the <tt class="docutils literal">run()</tt> method:</p> <pre class="literal-block"> if error_condition: raise self.error('Error message.') </pre> <p>The <tt class="docutils literal">self.error()</tt> method will immediately raise an exception that will be caught by the reStructuredText directive handler. The directive handler will then insert an error-level system message in the document at the place where the directive occurred.</p> <p>Instead of <tt class="docutils literal">self.error</tt>, you can also use <tt class="docutils literal">self.severe</tt> and <tt class="docutils literal">self.warning</tt> for more or less severe problems.</p> <p>If you want to return a system message <em>and</em> document contents, you need to create the system message yourself instead of using the <tt class="docutils literal">self.error</tt> convenience method:</p> <pre class="literal-block"> def run(self): # Create node(s). node = nodes.paragraph(...) # Node list to return. node_list = [node] if error_condition: # Create system message. error = self.reporter.error( 'Error in "%s" directive: Your error message.' % self.name, nodes.literal_block(block_text, block_text), line=lineno) node_list.append(error) return node_list </pre> </div> <div class="section" id="register-the-directive"> <h1><a class="toc-backref" href="#id7">Register the Directive</a></h1> <ul> <li><p class="first">If the directive is a general-use <strong>addition to the Docutils core</strong>, it must be registered with the parser and language mappings added:</p> <ol class="arabic simple"> <li>Register the new directive using its canonical name in <tt class="docutils literal">docutils/parsers/rst/directives/__init__.py</tt>, in the <tt class="docutils literal">_directive_registry</tt> dictionary. This allows the reStructuredText parser to find and use the directive.</li> <li>Add an entry to the <tt class="docutils literal">directives</tt> dictionary in <tt class="docutils literal">docutils/parsers/rst/languages/en.py</tt> for the directive, mapping the English name to the canonical name (both lowercase). Usually the English name and the canonical name are the same.</li> <li>Update all the other language modules as well. For languages in which you are proficient, please add translations. For other languages, add the English directive name plus "(translation required)".</li> </ol> </li> <li><p class="first">If the directive is <strong>application-specific</strong>, use the <tt class="docutils literal">register_directive</tt> function:</p> <pre class="literal-block"> from docutils.parsers.rst import directives directives.register_directive(directive_name, directive_class) </pre> </li> </ul> </div> <div class="section" id="examples"> <h1><a class="toc-backref" href="#id8">Examples</a></h1> <p>For the most direct and accurate information, "Use the Source, Luke!". All standard directives are documented in <a class="reference external" href="../ref/rst/directives.html">reStructuredText Directives</a>, and the source code implementing them is located in the <tt class="docutils literal">docutils/parsers/rst/directives</tt> package. The <tt class="docutils literal">__init__.py</tt> module contains a mapping of directive name to module and function name. Several representative directives are described below.</p> <div class="section" id="admonitions"> <h2><a class="toc-backref" href="#id9">Admonitions</a></h2> <p><a class="reference external" href="../ref/rst/directives.html#specific-admonitions">Admonition directives</a>, such as "note" and "caution", are quite simple. They have no directive arguments or options. Admonition directive content is interpreted as ordinary reStructuredText.</p> <p>The resulting document tree for a simple reStructuredText line "<tt class="docutils literal">.. note:: This is a note.</tt>" looks as follows:</p> <blockquote> <dl class="docutils"> <dt><note></dt> <dd><dl class="first last docutils"> <dt><paragraph></dt> <dd>This is a note.</dd> </dl> </dd> </dl> </blockquote> <p>The directive class for the "note" directive simply derives from a generic admonition directive class:</p> <pre class="literal-block"> class Note(BaseAdmonition): node_class = nodes.note </pre> <p>Note that the only thing distinguishing the various admonition directives is the element (node class) generated. In the code above, the node class is set as a class attribute and is read by the <tt class="docutils literal">run()</tt> method of <tt class="docutils literal">BaseAdmonition</tt>, where the actual processing takes place:</p> <pre class="literal-block"> # Import Docutils document tree nodes module. from docutils import nodes # Import Directive base class. from docutils.parsers.rst import Directive class BaseAdmonition(Directive): required_arguments = 0 optional_arguments = 0 final_argument_whitespace = True option_spec = {} has_content = True node_class = None """Subclasses must set this to the appropriate admonition node class.""" def run(self): # Raise an error if the directive does not have contents. self.assert_has_content() text = '\n'.join(self.content) # Create the admonition node, to be populated by `nested_parse`. admonition_node = self.node_class(rawsource=text) # Parse the directive contents. self.state.nested_parse(self.content, self.content_offset, admonition_node) return [admonition_node] </pre> <p>Three things are noteworthy in the <tt class="docutils literal">run()</tt> method above:</p> <ul class="simple"> <li>The <tt class="docutils literal">admonition_node = self.node_class(text)</tt> line creates the wrapper element, using the class set by the specific admonition subclasses (as in note, <tt class="docutils literal">node_class = nodes.note</tt>).</li> <li>The call to <tt class="docutils literal">state.nested_parse()</tt> is what does the actual processing. It parses the directive content and adds any generated elements as child elements of <tt class="docutils literal">admonition_node</tt>.</li> <li>If there was no directive content, the <tt class="docutils literal">assert_has_content()</tt> convenience method raises an error exception by calling <tt class="docutils literal">self.error()</tt> (see <a class="reference internal" href="#error-handling">Error Handling</a> above).</li> </ul> </div> <div class="section" id="image"> <h2><a class="toc-backref" href="#id10">"image"</a></h2> <p>The "<a class="reference external" href="../ref/rst/directives.html#image">image</a>" directive is used to insert a picture into a document. This directive has one argument, the path to the image file, and supports several options. There is no directive content. Here's an early version of the image directive class:</p> <pre class="literal-block"> # Import Docutils document tree nodes module. from docutils import nodes # Import ``directives`` module (contains conversion functions). from docutils.parsers.rst import directives # Import Directive base class. from docutils.parsers.rst import Directive def align(argument): """Conversion function for the "align" option.""" return directives.choice(argument, ('left', 'center', 'right')) class Image(Directive): required_arguments = 1 optional_arguments = 0 final_argument_whitespace = True option_spec = {'alt': directives.unchanged, 'height': directives.nonnegative_int, 'width': directives.nonnegative_int, 'scale': directives.nonnegative_int, 'align': align, } has_content = False def run(self): reference = directives.uri(self.arguments[0]) self.options['uri'] = reference image_node = nodes.image(rawsource=self.block_text, **self.options) return [image_node] </pre> <p>Several things are noteworthy in the code above:</p> <ul class="simple"> <li>The "image" directive requires a single argument, which is allowed to contain whitespace (<tt class="docutils literal">final_argument_whitespace = True</tt>). This is to allow for long URLs which may span multiple lines. The first line of the <tt class="docutils literal">run()</tt> method joins the URL, discarding any embedded whitespace.</li> <li>The reference is added to the <tt class="docutils literal">options</tt> dictionary under the "uri" key; this becomes an attribute of the <tt class="docutils literal">nodes.image</tt> element object. Any other attributes have already been set explicitly in the reStructuredText source text.</li> </ul> </div> <div class="section" id="the-pending-element"> <h2><a class="toc-backref" href="#id11">The Pending Element</a></h2> <p>Directives that cause actions to be performed <em>after</em> the complete document tree has been generated can be implemented using a <tt class="docutils literal">pending</tt> node. The <tt class="docutils literal">pending</tt> node causes a <a class="reference external" href="../ref/transforms.html">transform</a> to be run after the document has been parsed.</p> <p>For an example usage of the <tt class="docutils literal">pending</tt> node, see the implementation of the <tt class="docutils literal">contents</tt> directive in <a class="reference external" href="http://docutils.sf.net/docutils/parsers/rst/directives/parts.py">docutils.parsers.rst.directives.parts</a>.</p> </div> </div> </div> </body> </html>