Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/docutils/parsers/rst/directives/__init__.py: 33%
175 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 06:06 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 06:06 +0000
1# $Id$
2# Author: David Goodger <goodger@python.org>
3# Copyright: This module has been placed in the public domain.
5"""
6This package contains directive implementation modules.
7"""
9__docformat__ = 'reStructuredText'
11import re
12import codecs
13from importlib import import_module
15from docutils import nodes, parsers
16from docutils.utils import split_escaped_whitespace, escape2null
17from docutils.parsers.rst.languages import en as _fallback_language_module
20_directive_registry = {
21 'attention': ('admonitions', 'Attention'),
22 'caution': ('admonitions', 'Caution'),
23 'code': ('body', 'CodeBlock'),
24 'danger': ('admonitions', 'Danger'),
25 'error': ('admonitions', 'Error'),
26 'important': ('admonitions', 'Important'),
27 'note': ('admonitions', 'Note'),
28 'tip': ('admonitions', 'Tip'),
29 'hint': ('admonitions', 'Hint'),
30 'warning': ('admonitions', 'Warning'),
31 'admonition': ('admonitions', 'Admonition'),
32 'sidebar': ('body', 'Sidebar'),
33 'topic': ('body', 'Topic'),
34 'line-block': ('body', 'LineBlock'),
35 'parsed-literal': ('body', 'ParsedLiteral'),
36 'math': ('body', 'MathBlock'),
37 'rubric': ('body', 'Rubric'),
38 'epigraph': ('body', 'Epigraph'),
39 'highlights': ('body', 'Highlights'),
40 'pull-quote': ('body', 'PullQuote'),
41 'compound': ('body', 'Compound'),
42 'container': ('body', 'Container'),
43 # 'questions': ('body', 'question_list'),
44 'table': ('tables', 'RSTTable'),
45 'csv-table': ('tables', 'CSVTable'),
46 'list-table': ('tables', 'ListTable'),
47 'image': ('images', 'Image'),
48 'figure': ('images', 'Figure'),
49 'contents': ('parts', 'Contents'),
50 'sectnum': ('parts', 'Sectnum'),
51 'header': ('parts', 'Header'),
52 'footer': ('parts', 'Footer'),
53 # 'footnotes': ('parts', 'footnotes'),
54 # 'citations': ('parts', 'citations'),
55 'target-notes': ('references', 'TargetNotes'),
56 'meta': ('misc', 'Meta'),
57 # 'imagemap': ('html', 'imagemap'),
58 'raw': ('misc', 'Raw'),
59 'include': ('misc', 'Include'),
60 'replace': ('misc', 'Replace'),
61 'unicode': ('misc', 'Unicode'),
62 'class': ('misc', 'Class'),
63 'role': ('misc', 'Role'),
64 'default-role': ('misc', 'DefaultRole'),
65 'title': ('misc', 'Title'),
66 'date': ('misc', 'Date'),
67 'restructuredtext-test-directive': ('misc', 'TestDirective'),
68 }
69"""Mapping of directive name to (module name, class name). The
70directive name is canonical & must be lowercase. Language-dependent
71names are defined in the ``language`` subpackage."""
73_directives = {}
74"""Cache of imported directives."""
77def directive(directive_name, language_module, document):
78 """
79 Locate and return a directive function from its language-dependent name.
80 If not found in the current language, check English. Return None if the
81 named directive cannot be found.
82 """
83 normname = directive_name.lower()
84 messages = []
85 msg_text = []
86 if normname in _directives:
87 return _directives[normname], messages
88 canonicalname = None
89 try:
90 canonicalname = language_module.directives[normname]
91 except AttributeError as error:
92 msg_text.append('Problem retrieving directive entry from language '
93 'module %r: %s.' % (language_module, error))
94 except KeyError:
95 msg_text.append('No directive entry for "%s" in module "%s".'
96 % (directive_name, language_module.__name__))
97 if not canonicalname:
98 try:
99 canonicalname = _fallback_language_module.directives[normname]
100 msg_text.append('Using English fallback for directive "%s".'
101 % directive_name)
102 except KeyError:
103 msg_text.append('Trying "%s" as canonical directive name.'
104 % directive_name)
105 # The canonical name should be an English name, but just in case:
106 canonicalname = normname
107 if msg_text:
108 message = document.reporter.info(
109 '\n'.join(msg_text), line=document.current_line)
110 messages.append(message)
111 try:
112 modulename, classname = _directive_registry[canonicalname]
113 except KeyError:
114 # Error handling done by caller.
115 return None, messages
116 try:
117 module = import_module('docutils.parsers.rst.directives.'+modulename)
118 except ImportError as detail:
119 messages.append(document.reporter.error(
120 'Error importing directive module "%s" (directive "%s"):\n%s'
121 % (modulename, directive_name, detail),
122 line=document.current_line))
123 return None, messages
124 try:
125 directive = getattr(module, classname)
126 _directives[normname] = directive
127 except AttributeError:
128 messages.append(document.reporter.error(
129 'No directive class "%s" in module "%s" (directive "%s").'
130 % (classname, modulename, directive_name),
131 line=document.current_line))
132 return None, messages
133 return directive, messages
136def register_directive(name, directive):
137 """
138 Register a nonstandard application-defined directive function.
139 Language lookups are not needed for such functions.
140 """
141 _directives[name] = directive
144def flag(argument):
145 """
146 Check for a valid flag option (no argument) and return ``None``.
147 (Directive option conversion function.)
149 Raise ``ValueError`` if an argument is found.
150 """
151 if argument and argument.strip():
152 raise ValueError('no argument is allowed; "%s" supplied' % argument)
153 else:
154 return None
157def unchanged_required(argument):
158 """
159 Return the argument text, unchanged.
160 (Directive option conversion function.)
162 Raise ``ValueError`` if no argument is found.
163 """
164 if argument is None:
165 raise ValueError('argument required but none supplied')
166 else:
167 return argument # unchanged!
170def unchanged(argument):
171 """
172 Return the argument text, unchanged.
173 (Directive option conversion function.)
175 No argument implies empty string ("").
176 """
177 if argument is None:
178 return ''
179 else:
180 return argument # unchanged!
183def path(argument):
184 """
185 Return the path argument unwrapped (with newlines removed).
186 (Directive option conversion function.)
188 Raise ``ValueError`` if no argument is found.
189 """
190 if argument is None:
191 raise ValueError('argument required but none supplied')
192 else:
193 return ''.join(s.strip() for s in argument.splitlines())
196def uri(argument):
197 """
198 Return the URI argument with unescaped whitespace removed.
199 (Directive option conversion function.)
201 Raise ``ValueError`` if no argument is found.
202 """
203 if argument is None:
204 raise ValueError('argument required but none supplied')
205 else:
206 parts = split_escaped_whitespace(escape2null(argument))
207 return ' '.join(''.join(nodes.unescape(part).split())
208 for part in parts)
211def nonnegative_int(argument):
212 """
213 Check for a nonnegative integer argument; raise ``ValueError`` if not.
214 (Directive option conversion function.)
215 """
216 value = int(argument)
217 if value < 0:
218 raise ValueError('negative value; must be positive or zero')
219 return value
222def percentage(argument):
223 """
224 Check for an integer percentage value with optional percent sign.
225 (Directive option conversion function.)
226 """
227 try:
228 argument = argument.rstrip(' %')
229 except AttributeError:
230 pass
231 return nonnegative_int(argument)
234length_units = ['em', 'ex', 'px', 'in', 'cm', 'mm', 'pt', 'pc']
237def get_measure(argument, units):
238 """
239 Check for a positive argument of one of the units and return a
240 normalized string of the form "<value><unit>" (without space in
241 between).
242 (Directive option conversion function.)
244 To be called from directive option conversion functions.
245 """
246 match = re.match(r'^([0-9.]+) *(%s)$' % '|'.join(units), argument)
247 try:
248 float(match.group(1))
249 except (AttributeError, ValueError):
250 raise ValueError(
251 'not a positive measure of one of the following units:\n%s'
252 % ' '.join('"%s"' % i for i in units))
253 return match.group(1) + match.group(2)
256def length_or_unitless(argument):
257 return get_measure(argument, length_units + [''])
260def length_or_percentage_or_unitless(argument, default=''):
261 """
262 Return normalized string of a length or percentage unit.
263 (Directive option conversion function.)
265 Add <default> if there is no unit. Raise ValueError if the argument is not
266 a positive measure of one of the valid CSS units (or without unit).
268 >>> length_or_percentage_or_unitless('3 pt')
269 '3pt'
270 >>> length_or_percentage_or_unitless('3%', 'em')
271 '3%'
272 >>> length_or_percentage_or_unitless('3')
273 '3'
274 >>> length_or_percentage_or_unitless('3', 'px')
275 '3px'
276 """
277 try:
278 return get_measure(argument, length_units + ['%'])
279 except ValueError:
280 try:
281 return get_measure(argument, ['']) + default
282 except ValueError:
283 # raise ValueError with list of valid units:
284 return get_measure(argument, length_units + ['%'])
287def class_option(argument):
288 """
289 Convert the argument into a list of ID-compatible strings and return it.
290 (Directive option conversion function.)
292 Raise ``ValueError`` if no argument is found.
293 """
294 if argument is None:
295 raise ValueError('argument required but none supplied')
296 names = argument.split()
297 class_names = []
298 for name in names:
299 class_name = nodes.make_id(name)
300 if not class_name:
301 raise ValueError('cannot make "%s" into a class name' % name)
302 class_names.append(class_name)
303 return class_names
306unicode_pattern = re.compile(
307 r'(?:0x|x|\\x|U\+?|\\u)([0-9a-f]+)$|&#x([0-9a-f]+);$', re.IGNORECASE)
310def unicode_code(code):
311 r"""
312 Convert a Unicode character code to a Unicode character.
313 (Directive option conversion function.)
315 Codes may be decimal numbers, hexadecimal numbers (prefixed by ``0x``,
316 ``x``, ``\x``, ``U+``, ``u``, or ``\u``; e.g. ``U+262E``), or XML-style
317 numeric character entities (e.g. ``☮``). Other text remains as-is.
319 Raise ValueError for illegal Unicode code values.
320 """
321 try:
322 if code.isdigit(): # decimal number
323 return chr(int(code))
324 else:
325 match = unicode_pattern.match(code)
326 if match: # hex number
327 value = match.group(1) or match.group(2)
328 return chr(int(value, 16))
329 else: # other text
330 return code
331 except OverflowError as detail:
332 raise ValueError('code too large (%s)' % detail)
335def single_char_or_unicode(argument):
336 """
337 A single character is returned as-is. Unicode character codes are
338 converted as in `unicode_code`. (Directive option conversion function.)
339 """
340 char = unicode_code(argument)
341 if len(char) > 1:
342 raise ValueError('%r invalid; must be a single character or '
343 'a Unicode code' % char)
344 return char
347def single_char_or_whitespace_or_unicode(argument):
348 """
349 As with `single_char_or_unicode`, but "tab" and "space" are also supported.
350 (Directive option conversion function.)
351 """
352 if argument == 'tab':
353 char = '\t'
354 elif argument == 'space':
355 char = ' '
356 else:
357 char = single_char_or_unicode(argument)
358 return char
361def positive_int(argument):
362 """
363 Converts the argument into an integer. Raises ValueError for negative,
364 zero, or non-integer values. (Directive option conversion function.)
365 """
366 value = int(argument)
367 if value < 1:
368 raise ValueError('negative or zero value; must be positive')
369 return value
372def positive_int_list(argument):
373 """
374 Converts a space- or comma-separated list of values into a Python list
375 of integers.
376 (Directive option conversion function.)
378 Raises ValueError for non-positive-integer values.
379 """
380 if ',' in argument:
381 entries = argument.split(',')
382 else:
383 entries = argument.split()
384 return [positive_int(entry) for entry in entries]
387def encoding(argument):
388 """
389 Verifies the encoding argument by lookup.
390 (Directive option conversion function.)
392 Raises ValueError for unknown encodings.
393 """
394 try:
395 codecs.lookup(argument)
396 except LookupError:
397 raise ValueError('unknown encoding: "%s"' % argument)
398 return argument
401def choice(argument, values):
402 """
403 Directive option utility function, supplied to enable options whose
404 argument must be a member of a finite set of possible values (must be
405 lower case). A custom conversion function must be written to use it. For
406 example::
408 from docutils.parsers.rst import directives
410 def yesno(argument):
411 return directives.choice(argument, ('yes', 'no'))
413 Raise ``ValueError`` if no argument is found or if the argument's value is
414 not valid (not an entry in the supplied list).
415 """
416 try:
417 value = argument.lower().strip()
418 except AttributeError:
419 raise ValueError('must supply an argument; choose from %s'
420 % format_values(values))
421 if value in values:
422 return value
423 else:
424 raise ValueError('"%s" unknown; choose from %s'
425 % (argument, format_values(values)))
428def format_values(values):
429 return '%s, or "%s"' % (', '.join('"%s"' % s for s in values[:-1]),
430 values[-1])
433def value_or(values, other):
434 """
435 Directive option conversion function.
437 The argument can be any of `values` or `argument_type`.
438 """
439 def auto_or_other(argument):
440 if argument in values:
441 return argument
442 else:
443 return other(argument)
444 return auto_or_other
447def parser_name(argument):
448 """
449 Return a docutils parser whose name matches the argument.
450 (Directive option conversion function.)
452 Return `None`, if the argument evaluates to `False`.
453 Raise `ValueError` if importing the parser module fails.
454 """
455 if not argument:
456 return None
457 try:
458 return parsers.get_parser_class(argument)
459 except ImportError as err:
460 raise ValueError(str(err))