Debian Codegraph @

doc/development/tutorials/extending_syntax.rst

raw
1 .. _tutorial-extending-syntax:
2
3 Extending syntax with roles and directives
4 ==========================================
5
6 Overview
7 --------
8
9 The syntax of both reStructuredText and MyST can be extended
10 by creating new **directives** - for block-level elements -
11 and **roles** - for inline elements.
12
13 In this tutorial we shall extend Sphinx to add:
14
15 * A ``hello`` role, that will simply output the text ``Hello {text}!``.
16 * A ``hello`` directive, that will simply output the text ``Hello {text}!``,
17 as a paragraph.
18
19 For this extension, you will need some basic understanding of Python,
20 and we shall also introduce aspects of the docutils_ API.
21
22 Setting up the project
23 ----------------------
24
25 You can either use an existing Sphinx project
26 or create a new one using :program:`sphinx-quickstart`.
27
28 With this we will add the extension to the project,
29 within the :file:`source` folder:
30
31 #. Create an :file:`_ext` folder in :file:`source`
32 #. Create a new Python file in the :file:`_ext` folder called
33 :file:`helloworld.py`
34
35 Here is an example of the folder structure you might obtain:
36
37 .. code-block:: text
38
39 └── source
40    ├── _ext
41 │   └── helloworld.py
42    ├── conf.py
43    ├── index.rst
44
45
46 Writing the extension
47 ---------------------
48
49 Open :file:`helloworld.py` and paste the following code in it:
50
51 .. literalinclude:: examples/helloworld.py
52 :language: python
53 :linenos:
54
55 Some essential things are happening in this example:
56
57 The role class
58 ...............
59
60 Our new role is declared in the ``HelloRole`` class.
61
62 .. literalinclude:: examples/helloworld.py
63 :language: python
64 :linenos:
65 :pyobject: HelloRole
66
67 This class extends the :class:`.SphinxRole` class.
68 The class contains a ``run`` method,
69 which is a requirement for every role.
70 It contains the main logic of the role and it
71 returns a tuple containing:
72
73 - a list of inline-level docutils nodes to be processed by Sphinx.
74 - an (optional) list of system message nodes
75
76 The directive class
77 ...................
78
79 Our new directive is declared in the ``HelloDirective`` class.
80
81 .. literalinclude:: examples/helloworld.py
82 :language: python
83 :linenos:
84 :pyobject: HelloDirective
85
86 This class extends the :class:`.SphinxDirective` class.
87 The class contains a ``run`` method,
88 which is a requirement for every directive.
89 It contains the main logic of the directive and it
90 returns a list of block-level docutils nodes to be processed by Sphinx.
91 It also contains a ``required_arguments`` attribute,
92 which tells Sphinx how many arguments are required for the directive.
93
94 What are docutils nodes?
95 ........................
96
97 When Sphinx parses a document,
98 it creates an "Abstract Syntax Tree" (AST) of nodes
99 that represent the content of the document in a structured way,
100 that is generally independent of any one
101 input (rST, MyST, etc) or output (HTML, LaTeX, etc) format.
102 It is a tree because each node can have children nodes, and so on:
103
104 .. code-block:: xml
105
106 <document>
107 <paragraph>
108 <text>
109 Hello world!
110
111 The docutils_ package provides many `built-in nodes <docutils nodes_>`_,
112 to represent different types of content such as
113 text, paragraphs, references, tables, etc.
114
115 Each node type generally only accepts a specific set of direct child nodes,
116 for example the ``document`` node should only contain "block-level" nodes,
117 such as ``paragraph``, ``section``, ``table``, etc,
118 whilst the ``paragraph`` node should only contain "inline-level" nodes,
119 such as ``text``, ``emphasis``, ``strong``, etc.
120
121 .. seealso::
122
123 The docutils documentation on
124 `creating directives <docutils directives_>`_, and
125 `creating roles <docutils roles_>`_.
126
127 The ``setup`` function
128 ......................
129
130 This function is a requirement.
131 We use it to plug our new directive into Sphinx.
132
133 .. literalinclude:: examples/helloworld.py
134 :language: python
135 :pyobject: setup
136
137 The simplest thing you can do is to call the
138 :meth:`.Sphinx.add_role` and :meth:`.Sphinx.add_directive` methods,
139 which is what we've done here.
140 For this particular call, the first argument is the name of the role/directive itself
141 as used in a reStructuredText file.
142 In this case, we would use ``hello``. For example:
143
144 .. code-block:: rst
145
146 Some intro text here...
147
148 .. hello:: world
149
150 Some text with a :hello:`world` role.
151
152 We also return the :ref:`extension metadata <ext-metadata>` that indicates the
153 version of our extension, along with the fact that it is safe to use the
154 extension for both parallel reading and writing.
155
156 Using the extension
157 -------------------
158
159 The extension has to be declared in your :file:`conf.py` file to make Sphinx
160 aware of it. There are two steps necessary here:
161
162 #. Add the :file:`_ext` directory to the `Python path`_ using
163 ``sys.path.append``. This should be placed at the top of the file.
164
165 #. Update or create the :confval:`extensions` list and add the extension file
166 name to the list
167
168 For example:
169
170 .. code-block:: python
171
172 import sys
173 from pathlib import Path
174
175 sys.path.append(str(Path('_ext').resolve()))
176
177 extensions = ['helloworld']
178
179 .. tip::
180
181 Because we haven't installed our extension as a `Python package`_, we need to
182 modify the `Python path`_ so Sphinx can find our extension. This is why we
183 need the call to ``sys.path.append``.
184
185 You can now use the extension in a file. For example:
186
187 .. code-block:: rst
188
189 Some intro text here...
190
191 .. hello:: world
192
193 Some text with a :hello:`world` role.
194
195 The sample above would generate:
196
197 .. code-block:: text
198
199 Some intro text here...
200
201 Hello world!
202
203 Some text with a hello world! role.
204
205
206 Further reading
207 ---------------
208
209 This is the very basic principle of an extension
210 that creates a new role and directive.
211
212 For a more advanced example, refer to :ref:`tutorial-extend-build`.
213
214 If you wish to share your extension across multiple projects or with others,
215 check out the :ref:`third-party-extensions` section.
216
217 .. _docutils: https://docutils.sourceforge.io/
218 .. _docutils roles: https://docutils.sourceforge.io/docs/howto/rst-roles.html
219 .. _docutils directives: https://docutils.sourceforge.io/docs/howto/rst-directives.html
220 .. _docutils nodes: https://docutils.sourceforge.io/docs/ref/doctree.html
221 .. _PyPI: https://pypi.org/
222 .. _Python package: https://packaging.python.org/
223 .. _Python path: https://docs.python.org/3/using/cmdline.html#envvar-PYTHONPATH