Debian Codegraph @

docutils/parsers/rst/directives/misc.py

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