1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
|
"""
sphinx.addnodes
~~~~~~~~~~~~~~~
Additional docutils nodes.
:copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from typing import TYPE_CHECKING, Any, Dict, List, Sequence
from docutils import nodes
from docutils.nodes import Element
if TYPE_CHECKING:
from sphinx.application import Sphinx
class document(nodes.document):
"""The document root element patched by Sphinx.
This fixes that document.set_id() does not support a node having multiple node Ids.
see https://sourceforge.net/p/docutils/patches/167/
.. important:: This is only for Sphinx internal use. Please don't use this
in your extensions. It will be removed without deprecation period.
"""
def set_id(self, node: Element, msgnode: Element = None,
suggested_prefix: str = '') -> str:
from sphinx.util import docutils
if docutils.__version_info__ >= (0, 16):
ret = super().set_id(node, msgnode, suggested_prefix) # type: ignore
else:
ret = super().set_id(node, msgnode)
if docutils.__version_info__ < (0, 17):
# register other node IDs forcedly
for node_id in node['ids']:
if node_id not in self.ids:
self.ids[node_id] = node
return ret
class translatable(nodes.Node):
"""Node which supports translation.
The translation goes forward with following steps:
1. Preserve original translatable messages
2. Apply translated messages from message catalog
3. Extract preserved messages (for gettext builder)
The translatable nodes MUST preserve original messages.
And these messages should not be overridden at applying step.
Because they are used at final step; extraction.
"""
def preserve_original_messages(self) -> None:
"""Preserve original translatable messages."""
raise NotImplementedError
def apply_translated_message(self, original_message: str, translated_message: str) -> None:
"""Apply translated message."""
raise NotImplementedError
def extract_original_messages(self) -> Sequence[str]:
"""Extract translation messages.
:returns: list of extracted messages or messages generator
"""
raise NotImplementedError
class not_smartquotable:
"""A node which does not support smart-quotes."""
support_smartquotes = False
class toctree(nodes.General, nodes.Element, translatable):
"""Node for inserting a "TOC tree"."""
def preserve_original_messages(self) -> None:
# toctree entries
rawentries = self.setdefault('rawentries', [])
for title, docname in self['entries']:
if title:
rawentries.append(title)
# :caption: option
if self.get('caption'):
self['rawcaption'] = self['caption']
def apply_translated_message(self, original_message: str, translated_message: str) -> None:
# toctree entries
for i, (title, docname) in enumerate(self['entries']):
if title == original_message:
self['entries'][i] = (translated_message, docname)
# :caption: option
if self.get('rawcaption') == original_message:
self['caption'] = translated_message
def extract_original_messages(self) -> List[str]:
messages: List[str] = []
# toctree entries
messages.extend(self.get('rawentries', []))
# :caption: option
if 'rawcaption' in self:
messages.append(self['rawcaption'])
return messages
#############################################################
# Domain-specific object descriptions (class, function etc.)
#############################################################
class _desc_classes_injector:
"""Helper base class for injecting a fixes list of classes.
Use as the first base class.
"""
classes = [] # type: List[str]
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self['classes'].extend(self.classes)
# Top-level nodes
#################
class desc(nodes.Admonition, nodes.Element):
"""Node for a list of object signatures and a common description of them.
Contains one or more :py:class:`desc_signature` nodes
and then a single :py:class:`desc_content` node.
This node always has two classes:
- The name of the domain it belongs to, e.g., ``py`` or ``cpp``.
- The name of the object type in the domain, e.g., ``function``.
"""
# TODO: can we introduce a constructor
# that forces the specification of the domain and objtyp?
class desc_signature(nodes.Part, nodes.Inline, nodes.TextElement):
"""Node for a single object signature.
As default the signature is a single-line signature.
Set ``is_multiline = True`` to describe a multi-line signature.
In that case all child nodes must be :py:class:`desc_signature_line` nodes.
"""
@property
def child_text_separator(self):
if self.get('is_multiline'):
return ' '
else:
return super().child_text_separator
class desc_signature_line(nodes.Part, nodes.Inline, nodes.FixedTextElement):
"""Node for a line in a multi-line object signature.
It should only be used as a child of a :py:class:`desc_signature`
with ``is_multiline`` set to ``True``.
Set ``add_permalink = True`` for the line that should get the permalink.
"""
sphinx_line_type = ''
class desc_content(nodes.General, nodes.Element):
"""Node for object description content.
Must be the last child node in a :py:class:`desc` node.
"""
# Nodes for high-level structure in signatures
##############################################
# nodes to use within a desc_signature or desc_signature_line
class desc_name(_desc_classes_injector, nodes.Part, nodes.Inline, nodes.FixedTextElement):
"""Node for the main object name.
For example, in the declaration of a Python class ``MyModule.MyClass``,
the main name is ``MyClass``.
This node always has the class ``sig-name``.
"""
classes = ['sig-name', 'descname'] # 'descname' is for backwards compatibility
class desc_addname(_desc_classes_injector, nodes.Part, nodes.Inline, nodes.FixedTextElement):
"""Node for additional name parts for an object.
For example, in the declaration of a Python class ``MyModule.MyClass``,
the additional name part is ``MyModule.``.
This node always has the class ``sig-prename``.
"""
classes = ['sig-prename', 'descclassname'] # 'descclassname' is for backwards compatibility
# compatibility alias
desc_classname = desc_addname
class desc_type(nodes.Part, nodes.Inline, nodes.FixedTextElement):
"""Node for return types or object type names."""
class desc_returns(desc_type):
"""Node for a "returns" annotation (a la -> in Python)."""
def astext(self) -> str:
return ' -> ' + super().astext()
class desc_parameterlist(nodes.Part, nodes.Inline, nodes.FixedTextElement):
"""Node for a general parameter list."""
child_text_separator = ', '
def astext(self):
return '({})'.format(super().astext())
class desc_parameter(nodes.Part, nodes.Inline, nodes.FixedTextElement):
"""Node for a single parameter."""
class desc_optional(nodes.Part, nodes.Inline, nodes.FixedTextElement):
"""Node for marking optional parts of the parameter list."""
child_text_separator = ', '
def astext(self) -> str:
return '[' + super().astext() + ']'
class desc_annotation(nodes.Part, nodes.Inline, nodes.FixedTextElement):
"""Node for signature annotations (not Python 3-style annotations)."""
# Leaf nodes for markup of text fragments
#########################################
# Signature text elements, generally translated to node.inline
# in SigElementFallbackTransform.
# When adding a new one, add it to SIG_ELEMENTS.
class desc_sig_element(nodes.inline, _desc_classes_injector):
"""Common parent class of nodes for inline text of a signature."""
classes: List[str] = []
def __init__(self, rawsource: str = '', text: str = '',
*children: Element, **attributes: Any) -> None:
super().__init__(rawsource, text, *children, **attributes)
self['classes'].extend(self.classes)
# to not reinvent the wheel, the classes in the following desc_sig classes
# are based on those used in Pygments
class desc_sig_space(desc_sig_element):
"""Node for a space in a signature."""
classes = ["w"]
def __init__(self) -> None:
super().__init__(' ', ' ')
class desc_sig_name(desc_sig_element):
"""Node for an identifier in a signature."""
classes = ["n"]
class desc_sig_operator(desc_sig_element):
"""Node for an operator in a signature."""
classes = ["o"]
class desc_sig_punctuation(desc_sig_element):
"""Node for punctuation in a signature."""
classes = ["p"]
class desc_sig_keyword(desc_sig_element):
"""Node for a general keyword in a signature."""
classes = ["k"]
class desc_sig_keyword_type(desc_sig_element):
"""Node for a keyword which is a built-in type in a signature."""
classes = ["kt"]
class desc_sig_literal_number(desc_sig_element):
"""Node for a numeric literal in a signature."""
classes = ["m"]
class desc_sig_literal_string(desc_sig_element):
"""Node for a string literal in a signature."""
classes = ["s"]
class desc_sig_literal_char(desc_sig_element):
"""Node for a character literal in a signature."""
classes = ["sc"]
SIG_ELEMENTS = [desc_sig_space,
desc_sig_name,
desc_sig_operator,
desc_sig_punctuation,
desc_sig_keyword, desc_sig_keyword_type,
desc_sig_literal_number, desc_sig_literal_string, desc_sig_literal_char]
###############################################################
# new admonition-like constructs
class versionmodified(nodes.Admonition, nodes.TextElement):
"""Node for version change entries.
Currently used for "versionadded", "versionchanged" and "deprecated"
directives.
"""
class seealso(nodes.Admonition, nodes.Element):
"""Custom "see also" admonition."""
class productionlist(nodes.Admonition, nodes.Element):
"""Node for grammar production lists.
Contains ``production`` nodes.
"""
class production(nodes.Part, nodes.Inline, nodes.FixedTextElement):
"""Node for a single grammar production rule."""
# other directive-level nodes
class index(nodes.Invisible, nodes.Inline, nodes.TextElement):
"""Node for index entries.
This node is created by the ``index`` directive and has one attribute,
``entries``. Its value is a list of 5-tuples of ``(entrytype, entryname,
target, ignored, key)``.
*entrytype* is one of "single", "pair", "double", "triple".
*key* is categorization characters (usually a single character) for
general index page. For the details of this, please see also:
:rst:dir:`glossary` and issue #2320.
"""
class centered(nodes.Part, nodes.TextElement):
"""Deprecated."""
class acks(nodes.Element):
"""Special node for "acks" lists."""
class hlist(nodes.Element):
"""Node for "horizontal lists", i.e. lists that should be compressed to
take up less vertical space.
"""
class hlistcol(nodes.Element):
"""Node for one column in a horizontal list."""
class compact_paragraph(nodes.paragraph):
"""Node for a compact paragraph (which never makes a <p> node)."""
class glossary(nodes.Element):
"""Node to insert a glossary."""
class only(nodes.Element):
"""Node for "only" directives (conditional inclusion based on tags)."""
# meta-information nodes
class start_of_file(nodes.Element):
"""Node to mark start of a new file, used in the LaTeX builder only."""
class highlightlang(nodes.Element):
"""Inserted to set the highlight language and line number options for
subsequent code blocks.
"""
class tabular_col_spec(nodes.Element):
"""Node for specifying tabular columns, used for LaTeX output."""
class meta(nodes.Special, nodes.PreBibliographic, nodes.Element):
"""Node for meta directive -- same as docutils' standard meta node,
but pickleable.
"""
rawcontent = None
# inline nodes
class pending_xref(nodes.Inline, nodes.Element):
"""Node for cross-references that cannot be resolved without complete
information about all documents.
These nodes are resolved before writing output, in
BuildEnvironment.resolve_references.
"""
child_text_separator = ''
class pending_xref_condition(nodes.Inline, nodes.TextElement):
"""Node for cross-references that are used to choose appropriate
content of the reference by conditions on the resolving phase.
When the :py:class:`pending_xref` node contains one or more
**pending_xref_condition** nodes, the cross-reference resolver
should choose the content of the reference using defined conditions
in ``condition`` attribute of each pending_xref_condition nodes::
<pending_xref refdomain="py" reftarget="io.StringIO ...>
<pending_xref_condition condition="resolved">
<literal>
StringIO
<pending_xref_condition condition="*">
<literal>
io.StringIO
After the processing of cross-reference resolver, one of the content node
under pending_xref_condition node is chosen by its condition and to be
removed all of pending_xref_condition nodes::
# When resolved the cross-reference successfully
<reference>
<literal>
StringIO
# When resolution is failed
<reference>
<literal>
io.StringIO
.. note:: This node is only allowed to be placed under pending_xref node.
It is not allows to place it under other nodes. In addition,
pending_xref node must contain only pending_xref_condition
nodes if it contains one or more pending_xref_condition nodes.
The pending_xref_condition node should have **condition** attribute.
Domains can be store their individual conditions into the attribute to
filter contents on resolving phase. As a reserved condition name,
``condition="*"`` is used for the fallback of resolution failure.
Additionally, as a recommended condition name, ``condition="resolved"``
is used for the representation of resolstion success in the intersphinx
module.
.. versionadded:: 4.0
"""
class number_reference(nodes.reference):
"""Node for number references, similar to pending_xref."""
class download_reference(nodes.reference):
"""Node for download references, similar to pending_xref."""
class literal_emphasis(nodes.emphasis, not_smartquotable):
"""Node that behaves like `emphasis`, but further text processors are not
applied (e.g. smartypants for HTML output).
"""
class literal_strong(nodes.strong, not_smartquotable):
"""Node that behaves like `strong`, but further text processors are not
applied (e.g. smartypants for HTML output).
"""
class manpage(nodes.Inline, nodes.FixedTextElement):
"""Node for references to manpages."""
def setup(app: "Sphinx") -> Dict[str, Any]:
app.add_node(toctree)
app.add_node(desc)
app.add_node(desc_signature)
app.add_node(desc_signature_line)
app.add_node(desc_addname)
app.add_node(desc_type)
app.add_node(desc_returns)
app.add_node(desc_name)
app.add_node(desc_parameterlist)
app.add_node(desc_parameter)
app.add_node(desc_optional)
app.add_node(desc_annotation)
app.add_node(desc_content)
for n in SIG_ELEMENTS:
app.add_node(n)
app.add_node(versionmodified)
app.add_node(seealso)
app.add_node(productionlist)
app.add_node(production)
app.add_node(index)
app.add_node(centered)
app.add_node(acks)
app.add_node(hlist)
app.add_node(hlistcol)
app.add_node(compact_paragraph)
app.add_node(glossary)
app.add_node(only)
app.add_node(start_of_file)
app.add_node(highlightlang)
app.add_node(tabular_col_spec)
app.add_node(meta)
app.add_node(pending_xref)
app.add_node(number_reference)
app.add_node(download_reference)
app.add_node(literal_emphasis)
app.add_node(literal_strong)
app.add_node(manpage)
return {
'version': 'builtin',
'parallel_read_safe': True,
'parallel_write_safe': True,
}
|