Debian Codegraph @

docutils/parsers/rst/directives/misc.py

raw symbols ◀ ▶ SCIP
2 Debian patches touch this file
1 # $Id: misc.py 10302 2026-03-27 08:40:56Z milde $
2 # Authors: David Goodger <[email protected]>; Dethe Elza
3 # Copyright: This module has been placed in the public domain.
4
5 """Miscellaneous directives."""
6
7 from __future__ import annotations
8
9 __docformat__ = 'reStructuredText'
10
•11 import os
12 import re
13 import time
14 from pathlib import Path
15 from urllib.request import urlopen
16 from urllib.error import URLError
17
•18 import docutils
19 from docutils import frontend, io, nodes, statemachine, utils
20 from docutils.parsers.rst import Directive, convert_directive_function
21 from docutils.parsers.rst import directives, roles, states
22 from docutils.parsers.rst.directives.body import CodeBlock, NumberLines
23 from docutils.transforms import misc
24
25 TYPE_CHECKING = False
26 if TYPE_CHECKING:
27 from docutils.nodes import StrPath
28
29
30 def adapt_path(path: str, source='', root_prefix='') -> str:
31 # Adapt path to files to include or embed.
32 # `root_prefix` is prepended to absolute paths (cf. root_prefix setting),
33 # `source` is the `current_source` of the including directive (which may
34 # be a file included by the main document).
35 if root_prefix and path.startswith('/'):
36 base = Path(root_prefix)
37 path = path[1:]
38 else:
39 base = Path(source).parent
40 # pepend "base" and convert to relative path for shorter system messages
41 return utils.relative_path(None, base/path)
42
43
44 class Include(Directive):
45
46 """
47 Include content read from a separate source file.
48
49 Content may be parsed by the parser, or included as a literal
50 block. The encoding of the included file can be specified. Only
51 a part of the given file argument may be included by specifying
52 start and end line or text to match before and/or after the text
53 to be used.
54
55 https://docutils.sourceforge.io/docs/ref/rst/directives.html#include
56 """
57
58 required_arguments = 1
59 optional_arguments = 0
60 final_argument_whitespace = True
61 option_spec = {'literal': directives.flag,
62 'code': directives.unchanged,
63 'encoding': directives.encoding,
64 'parser': directives.parser_name,
65 'tab-width': int,
66 'start-line': int,
67 'end-line': int,
68 'start-after': directives.unchanged,
69 'end-before': directives.unchanged,
70 # ignored except for 'literal' or 'code':
71 'number-lines': directives.value_or((None,), int),
72 'class': directives.class_option,
73 'name': directives.unchanged}
74
•75 standard_include_path = Path(docutils._datadir(states.__file__)) / 'include'
76
77 def run(self) -> list:
78 """Include a file as part of the content of this reST file.
79
80 Depending on the options, the file content (or a clipping) is
81 converted to nodes and returned or inserted into the input stream.
82 """
83 self.settings = settings = self.state.document.settings
84 if not settings.file_insertion_enabled:
85 raise self.warning('"%s" directive disabled.' % self.name)
86 self.tab_width = self.options.get('tab-width', settings.tab_width)
87 self.clip_options = (self.options.get('start-line', None),
88 self.options.get('end-line', None),
89 self.options.get('start-after', None),
90 self.options.get('end-before', None))
91 path = directives.path(self.arguments[0])
92 if path.startswith('<') and path.endswith('>'):
93 path = '/' + path[1:-1]
94 root_prefix = self.standard_include_path
95 else:
96 root_prefix = settings.root_prefix
97 path = adapt_path(path,
98 self.state.document.current_source,
99 root_prefix)
100 self.options['source'] = path
101
102 inputstring = self.read_file(path)
103
104 if 'literal' in self.options:
105 return self.as_literal_block(inputstring)
106 if 'code' in self.options:
107 return self.as_code_block(inputstring)
108 if 'parser' in self.options:
109 return self.custom_parse(inputstring)
110 self.insert_into_input_lines(inputstring)
111 return []
112
113 def read_file(self, path: StrPath) -> str:
114 """Read text file at `path`. Clip and return content.
115
116 Provisional.
117 """
118 encoding = self.options.get('encoding', self.settings.input_encoding)
119 error_handler = self.settings.input_encoding_error_handler
120 try:
121 include_file = io.FileInput(source_path=path,
122 encoding=encoding,
123 error_handler=error_handler)
124 except UnicodeEncodeError:
125 raise self.error(f'Problems with "{self.name}" directive path:\n'
126 f'Cannot encode input file path "{path}" '
127 '(wrong locale?).')
128 except OSError as error:
129 raise self.error(f'Problems with "{self.name}" directive path:\n'
130 f'{io.error_string(error)}.')
131 else:
132 self.settings.record_dependencies.add(path)
133 try:
134 text = include_file.read()
135 except UnicodeError as error:
136 raise self.error(f'Problem with "{self.name}" directive:\n'
137 + io.error_string(error))
138 # Clip to-be-included content
139 startline, endline, starttext, endtext = self.clip_options
140 if startline or (endline is not None):
141 lines = text.splitlines()
142 text = '\n'.join(lines[startline:endline])
143 # start-after/end-before: no restrictions on newlines in match-text,
144 # and no restrictions on matching inside lines vs. line boundaries
145 # exception: emtpy string matches an empty line
146 if starttext == "":
147 # skip content before an empty line
148 starttext = '\n\n'
149 if starttext:
150 # skip content in text before *and incl.* a matching text
151 after_index = text.find(starttext)
152 if after_index < 0:
153 raise self.error('Problem with "start-after" option of '
154 f'"{self.name}" directive:\nText not found.')
155 else:
156 text = text[after_index + len(starttext):]
157 if endtext == "":
158 # skip content after an empty line
159 before_index = text.find('\n\n')
160 if before_index > 0:
161 text = text[:before_index+1]
162 elif endtext:
163 # skip content in text after *and incl.* a matching text
164 before_index = text.find(endtext)
165 if before_index < 0:
166 raise self.error('Problem with "end-before" option of '
167 f'"{self.name}" directive:\nText not found.')
168 text = text[:before_index]
169 return text
170
171 def as_literal_block(self, text: str) -> list[nodes.literal_block]:
172 """Return list with literal_block containing `text`.
173
174 Provisional
175 """
176 source = self.options['source']
177 # Convert tabs to spaces unless `tab_width` is negative.
178 if self.tab_width >= 0:
179 text = text.expandtabs(self.tab_width)
180 literal_block = nodes.literal_block(
181 '', source=source, classes=self.options.get('class', []))
182 literal_block.source = source
183 literal_block.line = self.options.get('start-line', 0) + 1
184 self.add_name(literal_block)
185 if 'number-lines' in self.options:
186 firstline = self.options['number-lines']
187 if firstline is None:
188 firstline = 1
189 text = text.removesuffix('\n')
190 lastline = firstline + len(text.splitlines())
191 tokens = NumberLines([([], text)], firstline, lastline)
192 for classes, value in tokens:
193 if classes:
194 literal_block += nodes.inline('', value, classes=classes)
195 else:
196 literal_block += nodes.Text(value)
197 else:
198 literal_block += nodes.Text(text)
199 return [literal_block]
200
201 def as_code_block(self, text: str) -> list[nodes.literal_block]:
202 """Pass `text` to the `CodeBlock` directive class.
203
204 Provisional.
205 """
206 # convert tabs to spaces unless `tab_width` is negative:
207 if self.tab_width >= 0:
208 text = text.expandtabs(self.tab_width)
209 codeblock = CodeBlock(self.name,
210 [self.options.pop('code')], # pass as argument
211 self.options,
212 [text.removesuffix('\n')], # content
213 self.lineno,
214 self.content_offset,
215 self.block_text,
216 self.state,
217 self.state_machine,
218 )
219 return codeblock.run()
220
221 def custom_parse(self, text: str) -> list:
222 """Parse with custom parser.
223
224 Parse with ``self.options['parser']`` into a new (dummy) document,
225 apply the parser's default transforms,
226 return child elements.
227
228 Provisional.
229 """
230 parser = self.options['parser']()
231 settings = frontend.get_default_settings(parser)
232 # update with current document settings
233 for k, v in self.settings.__dict__.items():
234 setattr(settings, k, v)
235 settings._source = self.options['source']
236 document = utils.new_document(settings._source, settings)
237 document.include_log = self.state.document.include_log
238 document.names = self.state.document.names
239 document.ids = self.state.document.ids
240 document.nameids = self.state.document.nameids
241 document.nametypes = self.state.document.nametypes
242 parser.parse(text, document)
243 self.state.document.parse_messages.extend(document.parse_messages)
244 # clean up doctree and complete parsing
245 document.transformer.populate_from_components((parser,))
246 document.transformer.apply_transforms()
247 self.state.document.transform_messages.extend(
248 document.transform_messages)
249 return document.children
250
251 def insert_into_input_lines(self, text: str) -> None:
252 """Insert file content into the rST input of the calling parser.
253
254 Provisional.
255 """
256 source = self.options['source']
257 textlines = statemachine.string2lines(text, self.tab_width,
258 convert_whitespace=True)
259 # Sanity checks:
260 # excessively long lines
261 for i, line in enumerate(textlines):
262 if len(line) > self.settings.line_length_limit:
263 line_no = i + 1 + self.options.get('start-line', 0)
264 raise self.warning(f'"{source}": line {line_no} exceeds the'
265 ' line-length-limit.')
266 # circular inclusion
267 include_log = self.state.document.include_log
268 if not include_log: # new document, initialize with document source
269 current_source = utils.relative_path(
270 None, self.state.document.current_source)
271 include_log.append((current_source, (None, None, None, None)))
272 if (source, self.clip_options) in include_log:
273 source_chain = (pth for (pth, opt) in reversed(include_log))
274 inclusion_chain = '\n> '.join((source, *source_chain))
275 raise self.warning(f'circular inclusion in "{self.name}"'
276 f' directive:\n{inclusion_chain}')
277 include_log.append((source, self.clip_options))
278 # marker for removing log entry (cf. parsers.rst.states.Body.comment())
279 textlines += ['', f'.. end of inclusion from "{source}"']
280
281 self.state_machine.insert_input(textlines, source)
282 # TODO: if startline != 0, line numbers are wrong.
283
284
285 class Raw(Directive):
286
287 """
288 Pass through content unchanged
289
290 Content is included in output based on type argument
291
292 Content may be included inline (content section of directive) or
293 imported from a file or url.
294 """
295
296 required_arguments = 1
297 optional_arguments = 0
298 final_argument_whitespace = True
299 option_spec = {'file': directives.path,
300 'url': directives.uri,
301 'encoding': directives.encoding,
302 'class': directives.class_option}
303 has_content = True
304
305 def run(self):
306 settings = self.state.document.settings
307 if (not settings.raw_enabled
308 or (not settings.file_insertion_enabled
309 and ('file' in self.options or 'url' in self.options))):
310 raise self.warning('"%s" directive disabled.' % self.name)
311 attributes = {'format': ' '.join(self.arguments[0].lower().split())}
312 encoding = self.options.get('encoding', settings.input_encoding)
313 error_handler = settings.input_encoding_error_handler
314 if self.content:
315 if 'file' in self.options or 'url' in self.options:
316 raise self.error(
317 '"%s" directive may not both specify an external file '
318 'and have content.' % self.name)
319 text = '\n'.join(self.content)
320 elif 'file' in self.options:
321 if 'url' in self.options:
322 raise self.error(
323 'The "file" and "url" options may not be simultaneously '
324 'specified for the "%s" directive.' % self.name)
325 path = adapt_path(self.options['file'],
326 self.state.document.current_source,
327 settings.root_prefix)
328 try:
329 raw_file = io.FileInput(source_path=path,
330 encoding=encoding,
331 error_handler=error_handler)
332 except OSError as error:
333 raise self.error(f'Problems with "{self.name}" directive '
334 f'path:\n{io.error_string(error)}.')
335 else:
336 # TODO: currently, raw input files are recorded as
337 # dependencies even if not used for the chosen output format.
338 settings.record_dependencies.add(path)
339 try:
340 text = raw_file.read()
341 except UnicodeError as error:
342 raise self.error(f'Problem with "{self.name}" directive:\n'
343 + io.error_string(error))
344 attributes['source'] = path
345 elif 'url' in self.options:
346 source = self.options['url']
347 try:
348 raw_text = urlopen(source).read()
349 except (URLError, OSError) as error:
350 raise self.error(f'Problems with "{self.name}" directive URL '
351 f'"{self.options["url"]}":\n'
352 f'{io.error_string(error)}.')
353 raw_file = io.StringInput(source=raw_text, source_path=source,
354 encoding=encoding,
355 error_handler=error_handler)
356 try:
357 text = raw_file.read()
358 except UnicodeError as error:
359 raise self.error(f'Problem with "{self.name}" directive:\n'
360 + io.error_string(error))
361 attributes['source'] = source
362 else:
363 # This will always fail because there is no content.
364 self.assert_has_content()
365 raw_node = nodes.raw('', text, classes=self.options.get('class', []),
366 **attributes)
367 (raw_node.source,
368 raw_node.line) = self.state_machine.get_source_and_line(self.lineno)
369 return [raw_node]
370
371
372 class Replace(Directive):
373
374 has_content = True
375
376 def run(self):
377 if not isinstance(self.state, states.SubstitutionDef):
378 raise self.error(
379 'Invalid context: the "%s" directive can only be used within '
380 'a substitution definition.' % self.name)
381 self.assert_has_content()
382 text = '\n'.join(self.content)
383 element = nodes.Element(text)
384 self.state.nested_parse(self.content, self.content_offset,
385 element)
386 # element might contain [paragraph] + system_message(s)
387 node = None
388 messages = []
389 for elem in element:
390 if not node and isinstance(elem, nodes.paragraph):
391 node = elem
392 elif isinstance(elem, nodes.system_message):
393 elem['backrefs'] = []
394 messages.append(elem)
395 else:
396 return [
397 self.reporter.error(
398 f'Error in "{self.name}" directive: may contain '
399 'a single paragraph only.', line=self.lineno)]
400 if node:
401 return messages + node.children
402 return messages
403
404
405 class Unicode(Directive):
406
407 r"""
408 Convert Unicode character codes (numbers) to characters. Codes may be
409 decimal numbers, hexadecimal numbers (prefixed by ``0x``, ``x``, ``\x``,
410 ``U+``, ``u``, or ``\u``; e.g. ``U+262E``), or XML-style numeric character
411 entities (e.g. ``&#x262E;``). Text following ".." is a comment and is
412 ignored. Spaces are ignored, and any other text remains as-is.
413 """
414
415 required_arguments = 1
416 optional_arguments = 0
417 final_argument_whitespace = True
418 option_spec = {'trim': directives.flag,
419 'ltrim': directives.flag,
420 'rtrim': directives.flag}
421
422 comment_pattern = re.compile(r'( |\n|^)\.\. ')
423
424 def run(self):
425 if not isinstance(self.state, states.SubstitutionDef):
426 raise self.error(
427 'Invalid context: the "%s" directive can only be used within '
428 'a substitution definition.' % self.name)
429 substitution_definition = self.state_machine.node
430 if 'trim' in self.options:
431 substitution_definition.attributes['ltrim'] = 1
432 substitution_definition.attributes['rtrim'] = 1
433 if 'ltrim' in self.options:
434 substitution_definition.attributes['ltrim'] = 1
435 if 'rtrim' in self.options:
436 substitution_definition.attributes['rtrim'] = 1
437 codes = self.comment_pattern.split(self.arguments[0])[0].split()
438 element = nodes.Element()
439 for code in codes:
440 try:
441 decoded = directives.unicode_code(code)
442 except ValueError as error:
443 raise self.error('Invalid character code: %s\n%s'
444 % (code, io.error_string(error)))
445 element += nodes.Text(decoded)
446 return element.children
447
448
449 class Class(Directive):
450
451 """
452 Set a "class" attribute on the directive content or the next element.
453 When applied to the next element, a "pending" element is inserted, and a
454 transform does the work later.
455 """
456
457 required_arguments = 1
458 optional_arguments = 0
459 final_argument_whitespace = True
460 has_content = True
461
462 def run(self):
463 try:
464 class_value = directives.class_option(self.arguments[0])
465 except ValueError:
466 raise self.error(
467 'Invalid class attribute value for "%s" directive: "%s".'
468 % (self.name, self.arguments[0]))
469 node_list = []
470 if self.content:
471 container = nodes.Element()
472 self.state.nested_parse(self.content, self.content_offset,
473 container)
474 for node in container:
475 node['classes'].extend(class_value)
476 node_list.extend(container.children)
477 else:
478 pending = nodes.pending(
479 misc.ClassAttribute,
480 {'class': class_value, 'directive': self.name},
481 self.block_text)
482 self.state_machine.document.note_pending(pending)
483 node_list.append(pending)
484 return node_list
485
486
487 class Role(Directive):
488
489 has_content = True
490
491 argument_pattern = re.compile(r'(%s)\s*(\(\s*(%s)\s*\)\s*)?$'
492 % ((states.Inliner.simplename,) * 2))
493
494 def run(self):
495 """Dynamically create and register a custom interpreted text role."""
496 if self.content_offset > self.lineno or not self.content:
497 raise self.error('"%s" directive requires arguments on the first '
498 'line.' % self.name)
499 args = self.content[0]
500 match = self.argument_pattern.match(args)
501 if not match:
502 raise self.error('"%s" directive arguments not valid role names: '
503 '"%s".' % (self.name, args))
504 new_role_name = match.group(1)
505 base_role_name = match.group(3)
506 messages = []
507 if base_role_name:
508 base_role, messages = roles.role(
509 base_role_name, self.state_machine.language, self.lineno,
510 self.state.reporter)
511 if base_role is None:
512 error = self.state.reporter.error(
513 'Unknown interpreted text role "%s".' % base_role_name,
514 nodes.literal_block(self.block_text, self.block_text),
515 line=self.lineno)
516 return messages + [error]
517 else:
518 base_role = roles.generic_custom_role
519 assert not hasattr(base_role, 'arguments'), (
520 'Supplemental directive arguments for "%s" directive not '
521 'supported (specified by "%r" role).' % (self.name, base_role))
522 try:
523 converted_role = convert_directive_function(base_role)
524 (arguments, options, content, content_offset
525 ) = self.state.parse_directive_block(
526 self.content[1:], self.content_offset,
527 converted_role, option_presets={})
528 except states.MarkupError as detail:
529 error = self.reporter.error(
530 'Error in "%s" directive:\n%s.' % (self.name, detail),
531 nodes.literal_block(self.block_text, self.block_text),
532 line=self.lineno)
533 return messages + [error]
534 if 'class' not in options:
535 try:
536 options['class'] = directives.class_option(new_role_name)
537 except ValueError as detail:
538 error = self.reporter.error(
539 'Invalid argument for "%s" directive:\n%s.'
540 % (self.name, detail),
541 nodes.literal_block(self.block_text, self.block_text),
542 line=self.lineno)
543 return messages + [error]
544 role = roles.CustomRole(new_role_name, base_role, options, content)
545 roles.register_local_role(new_role_name, role)
546 return messages
547
548
549 class DefaultRole(Directive):
550
551 """Set the default interpreted text role."""
552
553 optional_arguments = 1
554 final_argument_whitespace = False
555
556 def run(self):
557 if not self.arguments:
558 if '' in roles._roles:
559 # restore the "default" default role
560 del roles._roles['']
561 return []
562 role_name = self.arguments[0]
563 role, messages = roles.role(role_name, self.state_machine.language,
564 self.lineno, self.state.reporter)
565 if role is None:
566 error = self.state.reporter.error(
567 'Unknown interpreted text role "%s".' % role_name,
568 nodes.literal_block(self.block_text, self.block_text),
569 line=self.lineno)
570 return messages + [error]
571 roles._roles[''] = role
572 return messages
573
574
575 class Title(Directive):
576
577 required_arguments = 1
578 optional_arguments = 0
579 final_argument_whitespace = True
580
581 def run(self):
582 self.state_machine.document['title'] = self.arguments[0]
583 return []
584
585
586 class MetaBody(states.SpecializedBody):
587
588 def field_marker(self, match, context, next_state):
589 """Meta element."""
590 node, blank_finish = self.parsemeta(match)
591 self.parent += node
592 return [], next_state, []
593
594 def parsemeta(self, match):
595 name = self.parse_field_marker(match)
596 name = nodes.unescape(utils.escape2null(name))
597 (indented, indent, line_offset, blank_finish
598 ) = self.state_machine.get_first_known_indented(match.end())
599 node = nodes.meta()
600 node['content'] = nodes.unescape(utils.escape2null(
601 ' '.join(indented)))
602 if not indented:
603 line = self.state_machine.line
604 msg = self.reporter.info(
605 'No content for meta tag "%s".' % name,
606 nodes.literal_block(line, line))
607 return msg, blank_finish
608 tokens = name.split()
609 try:
610 attname, val = utils.extract_name_value(tokens[0])[0]
611 node[attname.lower()] = val
612 except utils.NameValueError:
613 node['name'] = tokens[0]
614 for token in tokens[1:]:
615 try:
616 attname, val = utils.extract_name_value(token)[0]
617 node[attname.lower()] = val
618 except utils.NameValueError as detail:
619 line = self.state_machine.line
620 msg = self.reporter.error(
621 'Error parsing meta tag attribute "%s": %s.'
622 % (token, detail), nodes.literal_block(line, line))
623 return msg, blank_finish
624 return node, blank_finish
625
626
627 class Meta(Directive):
628
629 has_content = True
630
631 SMkwargs = {'state_classes': (MetaBody,)}
632
633 def run(self):
634 self.assert_has_content()
635 node = nodes.Element()
636 new_line_offset, blank_finish = self.state.nested_list_parse(
637 self.content, self.content_offset, node,
638 initial_state='MetaBody', blank_finish=True,
639 state_machine_kwargs=self.SMkwargs)
640 if (new_line_offset - self.content_offset) != len(self.content):
641 # incomplete parse of block?
642 error = self.reporter.error(
643 'Invalid meta directive.',
644 nodes.literal_block(self.block_text, self.block_text),
645 line=self.lineno)
646 node += error
647 # insert at begin of document
648 index = self.state.document.first_child_not_matching_class(
649 (nodes.Titular, nodes.meta)) or 0
650 self.state.document[index:index] = node.children
651 return []
652
653
654 class Date(Directive):
655
656 has_content = True
657
658 def run(self):
659 if not isinstance(self.state, states.SubstitutionDef):
660 raise self.error(
661 'Invalid context: the "%s" directive can only be used within '
662 'a substitution definition.' % self.name)
663 format_str = '\n'.join(self.content) or '%Y-%m-%d'
664 # @@@
665 # Use timestamp from the `SOURCE_DATE_EPOCH`_ environment variable?
666 # Pro: Docutils-generated documentation
667 # can easily be part of `reproducible software builds`__
668 #
669 # __ https://reproducible-builds.org/
670 #
671 # Con: Changes the specs, hard to predict behaviour,
672 #
673 # See also the discussion about \date \time \year in TeX
674 # http://tug.org/pipermail/tex-k/2016-May/002704.html
•675 source_date_epoch = os.environ.get('SOURCE_DATE_EPOCH')
676 if source_date_epoch:
677 text = time.strftime(format_str,
678 time.gmtime(int(source_date_epoch)))
679 else:
680 text = time.strftime(format_str)
681 return [nodes.Text(text)]
682
683
684 class TestDirective(Directive):
685
686 """This directive is useful only for testing purposes."""
687
688 optional_arguments = 1
689 final_argument_whitespace = True
690 option_spec = {'option': directives.unchanged_required}
691 has_content = True
692
693 def run(self):
694 if self.content:
695 text = '\n'.join(self.content)
696 info = self.reporter.info(
697 'Directive processed. Type="%s", arguments=%r, options=%r, '
698 'content:' % (self.name, self.arguments, self.options),
699 nodes.literal_block(text, text), line=self.lineno)
700 else:
701 info = self.reporter.info(
702 'Directive processed. Type="%s", arguments=%r, options=%r, '
703 'content: None' % (self.name, self.arguments, self.options),
704 line=self.lineno)
705 return [info]