Debian Codegraph @

test/expensive_benchmarks/docutils_data/docs/howto/rst-roles.txt

raw
1 ==================================================
2 Creating reStructuredText Interpreted Text Roles
3 ==================================================
4
5 :Authors: David Goodger
6 :Contact: [email protected]
7 :Date: $Date$
8 :Revision: $Revision$
9 :Copyright: This document has been placed in the public domain.
10
11 Interpreted text roles are an extension mechanism for inline markup in
12 reStructuredText. This document aims to make the creation of new
13 roles as easy and understandable as possible.
14
15 Standard roles are described in `reStructuredText Interpreted Text
16 Roles`_. See the `Interpreted Text`_ section in the `reStructuredText
17 Markup Specification`_ for syntax details.
18
19 .. _reStructuredText Interpreted Text Roles: ../ref/rst/roles.html
20 .. _Interpreted Text:
21 ../ref/rst/restructuredtext.html#interpreted-text
22 .. _reStructuredText Markup Specification:
23 ../ref/rst/restructuredtext.html
24
25
26 .. contents::
27
28
29 Define the Role Function
30 ========================
31
32 The role function creates and returns inline elements (nodes) and does
33 any additional processing required. Its signature is as follows::
34
35 def role_fn(name, rawtext, text, lineno, inliner,
36 options=None, content=None):
37 code...
38
39 # Optional function attributes for customization:
40 role_fn.options = ...
41 role_fn.content = ...
42
43 Function attributes are described below (see `Specify Role Function
44 Options and Content`_). The role function parameters are as follows:
45
46 * ``name``: The local name of the interpreted role, the role name
47 actually used in the document.
48
49 * ``rawtext``: A string containing the entire interpreted text input,
50 including the role and markup. Return it as a ``problematic`` node
51 linked to a system message if a problem is encountered.
52
53 * ``text``: The interpreted text content.
54
55 * ``lineno``: The line number where the text block containing the
56 interpreted text begins.
57
58 * ``inliner``: The ``docutils.parsers.rst.states.Inliner`` object that
59 called role_fn. It contains the several attributes useful for error
60 reporting and document tree access.
61
62 * ``options``: A dictionary of directive options for customization
63 (from the `"role" directive`_), to be interpreted by the role
64 function. Used for additional attributes for the generated elements
65 and other functionality.
66
67 * ``content``: A list of strings, the directive content for
68 customization (from the `"role" directive`_). To be interpreted by
69 the role function.
70
71 Role functions return a tuple of two values:
72
73 * A list of nodes which will be inserted into the document tree at the
74 point where the interpreted role was encountered (can be an empty
75 list).
76
77 * A list of system messages, which will be inserted into the document tree
78 immediately after the end of the current block (can also be empty).
79
80
81 Specify Role Function Options and Content
82 =========================================
83
84 Function attributes are for customization, and are interpreted by the
85 `"role" directive`_. If unspecified, role function attributes are
86 assumed to have the value ``None``. Two function attributes are
87 recognized:
88
89 - ``options``: The option specification. All role functions
90 implicitly support the "class" option, unless disabled with an
91 explicit ``{'class': None}``.
92
93 An option specification must be defined detailing the options
94 available to the "role" directive. An option spec is a mapping of
95 option name to conversion function; conversion functions are applied
96 to each option value to check validity and convert them to the
97 expected type. Python's built-in conversion functions are often
98 usable for this, such as ``int``, ``float``, and ``bool`` (included
99 in Python from version 2.2.1). Other useful conversion functions
100 are included in the ``docutils.parsers.rst.directives`` package.
101 For further details, see `Creating reStructuredText Directives`_.
102
103 - ``content``: A boolean; true if "role" directive content is allowed.
104 Role functions must handle the case where content is required but
105 not supplied (an empty content list will be supplied).
106
107 As of this writing, no roles accept directive content.
108
109 Note that unlike directives, the "arguments" function attribute is not
110 supported for role customization. Directive arguments are handled by
111 the "role" directive itself.
112
113 .. _"role" directive: ../ref/rst/directives.html#role
114 .. _Creating reStructuredText Directives:
115 rst-directives.html#specify-directive-arguments-options-and-content
116
117
118 Register the Role
119 =================
120
121 If the role is a general-use addition to the Docutils core, it must be
122 registered with the parser and language mappings added:
123
124 1. Register the new role using the canonical name::
125
126 from docutils.parsers.rst import roles
127 roles.register_canonical_role(name, role_function)
128
129 This code is normally placed immediately after the definition of
130 the role function.
131
132 2. Add an entry to the ``roles`` dictionary in
133 ``docutils/parsers/rst/languages/en.py`` for the role, mapping the
134 English name to the canonical name (both lowercase). Usually the
135 English name and the canonical name are the same. Abbreviations
136 and other aliases may also be added here.
137
138 3. Update all the other language modules as well. For languages in
139 which you are proficient, please add translations. For other
140 languages, add the English role name plus "(translation required)".
141
142 If the role is application-specific, use the ``register_local_role``
143 function::
144
145 from docutils.parsers.rst import roles
146 roles.register_local_role(name, role_function)
147
148
149 Examples
150 ========
151
152 For the most direct and accurate information, "Use the Source, Luke!".
153 All standard roles are documented in `reStructuredText Interpreted
154 Text Roles`_, and the source code implementing them is located in the
155 ``docutils/parsers/rst/roles.py`` module. Several representative
156 roles are described below.
157
158
159 Generic Roles
160 -------------
161
162 Many roles simply wrap a given element around the text. There's a
163 special helper function, ``register_generic_role``, which generates a
164 role function from the canonical role name and node class::
165
166 register_generic_role('emphasis', nodes.emphasis)
167
168 For the implementation of ``register_generic_role``, see the
169 ``docutils.parsers.rst.roles`` module.
170
171
172 RFC Reference Role
173 ------------------
174
175 This role allows easy references to RFCs_ (Request For Comments
176 documents) by automatically providing the base URL,
177 http://www.faqs.org/rfcs/, and appending the RFC document itself
178 (rfcXXXX.html, where XXXX is the RFC number). For example::
179
180 See :RFC:`2822` for information about email headers.
181
182 This is equivalent to::
183
184 See `RFC 2822`__ for information about email headers.
185
186 __ http://www.faqs.org/rfcs/rfc2822.html
187
188 Here is the implementation of the role::
189
190 def rfc_reference_role(role, rawtext, text, lineno, inliner,
191 options=None, content=None):
192 if "#" in text:
193 rfcnum, section = utils.unescape(text).split("#", 1)
194 else:
195 rfcnum, section = utils.unescape(text), None
196 try:
197 rfcnum = int(rfcnum)
198 if rfcnum < 1:
199 raise ValueError
200 except ValueError:
201 msg = inliner.reporter.error(
202 'RFC number must be a number greater than or equal to 1; '
203 '"%s" is invalid.' % text, line=lineno)
204 prb = inliner.problematic(rawtext, rawtext, msg)
205 return [prb], [msg]
206 # Base URL mainly used by inliner.rfc_reference, so this is correct:
207 ref = inliner.document.settings.rfc_base_url + inliner.rfc_url % rfcnum
208 if section is not None:
209 ref += "#"+section
210 options = normalize_role_options(options)
211 node = nodes.reference(rawtext, 'RFC ' + str(rfcnum), refuri=ref,
212 **options)
213 return [node], []
214
215 register_canonical_role('rfc-reference', rfc_reference_role)
216
217 Noteworthy in the code above are:
218
219 1. The interpreted text itself should contain the RFC number. The
220 ``try`` clause verifies by converting it to an integer. If the
221 conversion fails, the ``except`` clause is executed: a system
222 message is generated, the entire interpreted text construct (in
223 ``rawtext``) is wrapped in a ``problematic`` node (linked to the
224 system message), and the two are returned.
225
226 2. The RFC reference itself is constructed from a stock URI, set as
227 the "refuri" attribute of a "reference" element.
228
229 3. The ``options`` function parameter, a dictionary, may contain a
230 "class" customization attribute; it is interpreted and replaced
231 with a "classes" attribute by the ``set_classes()`` function. The
232 resulting "classes" attribute is passed through to the "reference"
233 element node constructor.
234
235 .. _RFCs: http://foldoc.doc.ic.ac.uk/foldoc/foldoc.cgi?query=rfc&action=Search&sourceid=Mozilla-search