Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/docutils/frontend.py: 31%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# $Id: frontend.py 10375 2026-06-27 17:26:02Z milde $
2# Author: David Goodger <goodger@python.org>
3# Copyright: This module has been placed in the public domain.
5"""
6Command-line and common processing for Docutils front-end tools.
8This module is provisional.
9Major changes will happen with the transition from the
10"optparse" module to "arparse" in Docutils 2.0 or later.
12Applications should use the high-level API provided by `docutils.core`.
13See https://docutils.sourceforge.io/docs/api/runtime-settings.html.
15Exports the following classes:
17* `OptionParser`: Standard Docutils command-line processing.
18 Deprecated. Will be replaced by an ArgumentParser.
19* `Option`: Customized version of `optparse.Option`; validation support.
20 Deprecated. Will be removed.
21* `Values`: Runtime settings; objects are simple structs
22 (``object.attribute``). Supports cumulative list settings (attributes).
23 Deprecated. Will be removed.
24* `ConfigParser`: Standard Docutils config file processing.
25 Provisional. Details will change.
27Also exports the following functions:
29Interface function:
30 `get_default_settings()`. New in 0.19.
32Option callbacks:
33 `store_multiple()`, `read_config_file()`. Deprecated. To be removed.
35Setting validators:
36 `validate_encoding()`, `validate_encoding_error_handler()`,
37 `validate_encoding_and_error_handler()`,
38 `validate_boolean()`, `validate_ternary()`,
39 `validate_nonnegative_int()`, `validate_threshold()`,
40 `validate_colon_separated_string_list()`,
41 `validate_comma_separated_list()`,
42 `validate_url_trailing_slash()`,
43 `validate_dependency_file()`,
44 `validate_strip_class()`
45 `validate_smartquotes_locales()`.
47 Provisional.
49Misc:
50 `make_paths_absolute()`, `filter_settings_spec()`. Provisional.
51"""
53from __future__ import annotations
55__docformat__ = 'reStructuredText'
58import codecs
59import configparser
60import optparse
61import os
62import os.path
63import sys
64import warnings
65from optparse import SUPPRESS_HELP
66from pathlib import Path
68import docutils
69from docutils import io, utils
71TYPE_CHECKING = False
72if TYPE_CHECKING:
73 from collections.abc import Iterable, Mapping, Sequence
74 from typing import Any, ClassVar, Literal, Protocol
76 from docutils import SettingsSpec, _OptionTuple, _SettingsSpecTuple
77 from docutils.io import StrPath
79 class _OptionValidator(Protocol):
80 def __call__(
81 self,
82 setting: str,
83 value: str | None,
84 option_parser: OptionParser,
85 /,
86 config_parser: ConfigParser | None = None,
87 config_section: str | None = None,
88 ) -> Any:
89 ...
92def store_multiple(option: optparse.Option,
93 opt: str,
94 value: Any,
95 parser: OptionParser,
96 *args: str,
97 **kwargs: Any,
98 ) -> None:
99 """
100 Store multiple values in `parser.values`. (Option callback.)
102 Store `None` for each attribute named in `args`, and store the value for
103 each key (attribute name) in `kwargs`.
105 Deprecated. Will be removed with the switch to from optparse to argparse.
106 """
107 for attribute in args:
108 setattr(parser.values, attribute, None)
109 for key, value in kwargs.items():
110 setattr(parser.values, key, value)
113def read_config_file(option: optparse.Option,
114 opt: str,
115 value: Any,
116 parser: OptionParser,
117 ) -> None:
118 """
119 Read a configuration file during option processing. (Option callback.)
121 Deprecated. Will be removed with the switch to from optparse to argparse.
122 """
123 try:
124 new_settings = parser.get_config_file_settings(value)
125 except ValueError as err:
126 parser.error(err)
127 parser.values.update(new_settings, parser)
130def validate_encoding(setting: str,
131 value: str | None = None,
132 option_parser: OptionParser | None = None,
133 config_parser: ConfigParser | None = None,
134 config_section: str | None = None,
135 ) -> str | None:
136 # All arguments except `value` are ignored
137 # (kept for compatibility with "optparse" module).
138 # If there is only one positional argument, it is interpreted as `value`.
139 if value is None:
140 value = setting
141 try:
142 codecs.lookup(value)
143 except LookupError:
144 raise LookupError(f'unknown encoding: "{value}"')
145 return value
148def validate_encoding_error_handler(
149 setting: str,
150 value: str | None = None,
151 option_parser: OptionParser | None = None,
152 config_parser: ConfigParser | None = None,
153 config_section: str | None = None,
154 ) -> str:
155 # All arguments except `value` are ignored
156 # (kept for compatibility with "optparse" module).
157 # If there is only one positional argument, it is interpreted as `value`.
158 if value is None:
159 value = setting
160 try:
161 codecs.lookup_error(value)
162 except LookupError:
163 raise LookupError(
164 'unknown encoding error handler: "%s" (choices: '
165 '"strict", "ignore", "replace", "backslashreplace", '
166 '"xmlcharrefreplace", and possibly others; see documentation for '
167 'the Python ``codecs`` module)' % value)
168 return value
171def validate_encoding_and_error_handler(
172 setting: str,
173 value: str | None = None,
174 option_parser: OptionParser | None = None,
175 config_parser: ConfigParser | None = None,
176 config_section: str | None = None,
177 ) -> str:
178 """Check/normalize encoding settings
180 Side-effect: if an error handler is included in the value, it is inserted
181 into the appropriate place as if it were a separate setting/option.
183 All arguments except `value` are ignored
184 (kept for compatibility with "optparse" module).
185 If there is only one positional argument, it is interpreted as `value`.
186 """
187 if ':' in value:
188 encoding, handler = value.split(':')
189 validate_encoding_error_handler(handler)
190 if config_parser:
191 config_parser.set(config_section, setting + '_error_handler',
192 handler)
193 else:
194 setattr(option_parser.values, setting + '_error_handler', handler)
195 else:
196 encoding = value
197 return validate_encoding(encoding)
200def validate_boolean(setting: str | bool,
201 value: str | None = None,
202 option_parser: OptionParser | None = None,
203 config_parser: ConfigParser | None = None,
204 config_section: str | None = None,
205 ) -> bool:
206 """Check/normalize boolean settings:
208 :True: '1', 'on', 'yes', 'true'
209 :False: '0', 'off', 'no','false', ''
211 All arguments except `value` are ignored
212 (kept for compatibility with "optparse" module).
213 If there is only one positional argument, it is interpreted as `value`.
214 """
215 if value is None:
216 value = setting
217 if isinstance(value, bool):
218 return value
219 try:
220 return OptionParser.booleans[value.strip().lower()]
221 except KeyError:
222 raise LookupError('unknown boolean value: "%s"' % value)
225def validate_ternary(setting: str | bool,
226 value: str | None = None,
227 option_parser: OptionParser | None = None,
228 config_parser: ConfigParser | None = None,
229 config_section: str | None = None,
230 ) -> str | bool | None:
231 """Check/normalize three-value settings:
233 :True: '1', 'on', 'yes', 'true'
234 :False: '0', 'off', 'no','false', ''
235 :any other value: returned as-is.
237 All arguments except `value` are ignored
238 (kept for compatibility with "optparse" module).
239 If there is only one positional argument, it is interpreted as `value`.
240 """
241 if value is None:
242 value = setting
243 if isinstance(value, bool) or value is None:
244 return value
245 try:
246 return OptionParser.booleans[value.strip().lower()]
247 except KeyError:
248 return value
251def validate_nonnegative_int(setting: str | int,
252 value: str | None = None,
253 option_parser: OptionParser | None = None,
254 config_parser: ConfigParser | None = None,
255 config_section: str | None = None,
256 ) -> int:
257 # All arguments except `value` are ignored
258 # (kept for compatibility with "optparse" module).
259 # If there is only one positional argument, it is interpreted as `value`.
260 if value is None:
261 value = setting
262 value = int(value)
263 if value < 0:
264 raise ValueError('negative value; must be positive or zero')
265 return value
268def validate_threshold(setting: str | int,
269 value: str | None = None,
270 option_parser: OptionParser | None = None,
271 config_parser: ConfigParser | None = None,
272 config_section: str | None = None,
273 ) -> int:
274 # All arguments except `value` are ignored
275 # (kept for compatibility with "optparse" module).
276 # If there is only one positional argument, it is interpreted as `value`.
277 if value is None:
278 value = setting
279 try:
280 return int(value)
281 except ValueError:
282 try:
283 return OptionParser.thresholds[value.lower()]
284 except (KeyError, AttributeError):
285 raise LookupError('unknown threshold: %r.' % value)
288def validate_colon_separated_string_list(
289 setting: str | list[str],
290 value: str | None = None,
291 option_parser: OptionParser | None = None,
292 config_parser: ConfigParser | None = None,
293 config_section: str | None = None,
294 ) -> list[str]:
295 # All arguments except `value` are ignored
296 # (kept for compatibility with "optparse" module).
297 # If there is only one positional argument, it is interpreted as `value`.
298 if value is None:
299 value = setting
300 if not isinstance(value, list):
301 value = value.split(':')
302 else:
303 last = value.pop()
304 value.extend(last.split(':'))
305 return value
308def validate_comma_separated_list(
309 setting: str | list[str],
310 value: str | None = None,
311 option_parser: OptionParser | None = None,
312 config_parser: ConfigParser | None = None,
313 config_section: str | None = None,
314 ) -> list[str]:
315 """Check/normalize list arguments (split at "," and strip whitespace).
317 All arguments except `value` are ignored
318 (kept for compatibility with "optparse" module).
319 If there is only one positional argument, it is interpreted as `value`.
320 """
321 if value is None:
322 value = setting
323 # `value` may be ``bytes``, ``str``, or a ``list`` (when given as
324 # command line option and "action" is "append").
325 if not isinstance(value, list):
326 value = [value]
327 # this function is called for every option added to `value`
328 # -> split the last item and append the result:
329 last = value.pop()
330 items = [i.strip(' \t\n') for i in last.split(',') if i.strip(' \t\n')]
331 value.extend(items)
332 return value
335def validate_math_output(setting: str,
336 value: str | None = None,
337 option_parser: OptionParser | None = None,
338 config_parser: ConfigParser | None = None,
339 config_section: str | None = None,
340 ) -> tuple[()] | tuple[str, str]:
341 """Check "math-output" setting, return list with "format" and "options".
343 See also https://docutils.sourceforge.io/docs/user/config.html#math-output
345 Argument list for compatibility with "optparse" module.
346 All arguments except `value` are ignored.
347 If there is only one positional argument, it is interpreted as `value`.
348 """
349 if value is None:
350 value = setting
352 formats = ('html', 'latex', 'mathml', 'mathjax')
353 tex2mathml_converters = ('', 'latexml', 'ttm', 'blahtexml', 'pandoc')
355 if not value:
356 return ()
357 values = value.split(maxsplit=1)
358 format = values[0].lower()
359 try:
360 options = values[1]
361 except IndexError:
362 options = ''
363 if format not in formats:
364 raise LookupError(f'Unknown math output format: "{value}",\n'
365 f' choose from {formats}.')
366 if format == 'mathml':
367 converter = options.lower()
368 if converter not in tex2mathml_converters:
369 raise LookupError(f'MathML converter "{options}" not supported,\n'
370 f' choose from {tex2mathml_converters}.')
371 options = converter
372 return format, options
375def validate_url_trailing_slash(setting: str | None,
376 value: str | None = None,
377 option_parser: OptionParser | None = None,
378 config_parser: ConfigParser | None = None,
379 config_section: str | None = None,
380 ) -> str:
381 # All arguments except `value` are ignored
382 # (kept for compatibility with "optparse" module).
383 # If there is only one positional argument, it is interpreted as `value`.
384 if value is None:
385 value = setting
386 if not value:
387 return './'
388 elif value.endswith('/'):
389 return value
390 else:
391 return value + '/'
394def validate_dependency_file(setting: str | None,
395 value: str | None = None,
396 option_parser: OptionParser | None = None,
397 config_parser: ConfigParser | None = None,
398 config_section: str | None = None,
399 ) -> utils.DependencyList:
400 # All arguments except `value` are ignored
401 # (kept for compatibility with "optparse" module).
402 # If there is only one positional argument, it is interpreted as `value`.
403 if value is None:
404 value = setting
405 try:
406 return utils.DependencyList(value)
407 except OSError:
408 # TODO: warn/info?
409 return utils.DependencyList(None)
412def validate_strip_class(setting: str,
413 value: str | None = None,
414 option_parser: OptionParser | None = None,
415 config_parser: ConfigParser | None = None,
416 config_section: str | None = None,
417 ) -> list[str]:
418 # All arguments except `value` are ignored
419 # (kept for compatibility with "optparse" module).
420 # If there is only one positional argument, it is interpreted as `value`.
421 if value is None:
422 value = setting
423 # value is a comma separated string list:
424 value = validate_comma_separated_list(value)
425 # validate list elements:
426 for cls in value:
427 normalized = docutils.nodes.make_id(cls)
428 if cls != normalized:
429 raise ValueError('Invalid class value %r (perhaps %r?)'
430 % (cls, normalized))
431 return value
434def validate_smartquotes_locales(
435 setting: str | list[str | tuple[str, str]],
436 value: str | None = None,
437 option_parser: OptionParser | None = None,
438 config_parser: ConfigParser | None = None,
439 config_section: str | None = None,
440 ) -> list[tuple[str, Sequence[str]]]:
441 """Check/normalize a comma separated list of smart quote definitions.
443 Return a list of (language-tag, quotes) string tuples.
445 All arguments except `value` are ignored
446 (kept for compatibility with "optparse" module).
447 If there is only one positional argument, it is interpreted as `value`.
448 """
449 if value is None:
450 value = setting
451 # value is a comma separated string list:
452 value = validate_comma_separated_list(value)
453 # validate list elements
454 lc_quotes = []
455 for item in value:
456 try:
457 lang, quotes = item.split(':', 1)
458 except AttributeError:
459 # this function is called for every option added to `value`
460 # -> ignore if already a tuple:
461 lc_quotes.append(item)
462 continue
463 except ValueError:
464 raise ValueError('Invalid value "%s".'
465 ' Format is "<language>:<quotes>".'
466 % item.encode('ascii', 'backslashreplace'))
467 # parse colon separated string list:
468 quotes = quotes.strip()
469 multichar_quotes = quotes.split(':')
470 if len(multichar_quotes) == 4:
471 quotes = multichar_quotes
472 elif len(quotes) != 4:
473 raise ValueError('Invalid value "%s". Please specify 4 quotes\n'
474 ' (primary open/close; secondary open/close).'
475 % item.encode('ascii', 'backslashreplace'))
476 lc_quotes.append((lang, quotes))
477 return lc_quotes
480def make_paths_absolute(pathdict: dict[str, list[StrPath] | StrPath],
481 keys: tuple[str],
482 base_path: StrPath | None = None,
483 ) -> None:
484 """
485 Interpret filesystem path settings relative to the `base_path` given.
487 Paths are values in `pathdict` whose keys are in `keys`. Get `keys` from
488 `OptionParser.relative_path_settings`.
489 """
490 if base_path is None:
491 base_path = Path.cwd()
492 else:
493 base_path = Path(base_path)
494 if sys.platform == 'win32' and sys.version_info[:2] <= (3, 9):
495 base_path = base_path.absolute()
496 for key in keys:
497 if key in pathdict:
498 value = pathdict[key]
499 if isinstance(value, (list, tuple)):
500 value = [str((base_path/path).resolve()) for path in value]
501 elif value:
502 value = str((base_path/value).resolve())
503 pathdict[key] = value
506def make_one_path_absolute(base_path: StrPath, path: StrPath) -> str:
507 # deprecated, will be removed
508 warnings.warn('frontend.make_one_path_absolute() will be removed '
509 'in Docutils 2.0 or later.',
510 DeprecationWarning, stacklevel=2)
511 return os.path.abspath(os.path.join(base_path, path))
514def filter_settings_spec(settings_spec: _SettingsSpecTuple,
515 *exclude: str,
516 **replace: _OptionTuple,
517 ) -> _SettingsSpecTuple:
518 """Return a copy of `settings_spec` excluding/replacing some settings.
520 `settings_spec` is a tuple of configuration settings
521 (cf. `docutils.SettingsSpec.settings_spec`).
523 Optional positional arguments are names of to-be-excluded settings.
524 Keyword arguments are option specification replacements.
525 (See the html4strict writer for an example.)
526 """
527 settings = list(settings_spec)
528 # every third item is a sequence of option tuples
529 for i in range(2, len(settings), 3):
530 newopts: list[_OptionTuple] = []
531 for opt_spec in settings[i]:
532 # opt_spec is ("<help>", [<option strings>], {<keyword args>})
533 opt_name = [opt_string[2:].replace('-', '_')
534 for opt_string in opt_spec[1]
535 if opt_string.startswith('--')][0]
536 if opt_name in exclude:
537 continue
538 if opt_name in replace.keys():
539 newopts.append(replace[opt_name])
540 else:
541 newopts.append(opt_spec)
542 settings[i] = tuple(newopts)
543 return tuple(settings)
546class Values(optparse.Values):
547 """Storage for option values.
549 Updates list attributes by extension rather than by replacement.
550 Works in conjunction with the `OptionParser.lists` instance attribute.
552 Deprecated. Will be removed when switching to the "argparse" module.
553 """
555 def __init__(self, defaults: dict[str, Any] | None = None) -> None:
556 warnings.warn('frontend.Values class will be removed '
557 'in Docutils 2.0 or later.',
558 DeprecationWarning, stacklevel=2)
559 super().__init__(defaults=defaults)
560 if getattr(self, 'record_dependencies', None) is None:
561 # Set up dummy dependency list.
562 self.record_dependencies = utils.DependencyList()
564 def update(self,
565 other_dict: Values | Mapping[str, Any],
566 option_parser: OptionParser,
567 ) -> None:
568 if isinstance(other_dict, Values):
569 other_dict = other_dict.__dict__
570 other_dict = dict(other_dict) # also works with ConfigParser sections
571 for setting in option_parser.lists.keys():
572 if hasattr(self, setting) and setting in other_dict:
573 value = getattr(self, setting)
574 if value:
575 value += other_dict[setting]
576 del other_dict[setting]
577 self._update_loose(other_dict)
579 def copy(self) -> Values:
580 """Return a shallow copy of `self`."""
581 with warnings.catch_warnings():
582 warnings.filterwarnings('ignore', category=DeprecationWarning)
583 return self.__class__(defaults=self.__dict__)
585 def setdefault(self, name: str, default: Any) -> Any:
586 """Return ``self.name`` or ``default``.
588 If ``self.name`` is unset, set ``self.name = default``.
589 """
590 if getattr(self, name, None) is None:
591 setattr(self, name, default)
592 return getattr(self, name)
595class Option(optparse.Option):
596 """Add validation and override support to `optparse.Option`.
598 Deprecated. Will be removed.
599 """
601 ATTRS = optparse.Option.ATTRS + ['validator', 'overrides']
603 validator: _OptionValidator
604 overrides: str | None
606 def __init__(self, *args: str | None, **kwargs: Any) -> None:
607 warnings.warn('The frontend.Option class will be removed '
608 'in Docutils 2.0 or later.',
609 DeprecationWarning, stacklevel=2)
610 super().__init__(*args, **kwargs)
612 def process(self,
613 opt: str,
614 value: Any,
615 values: Values,
616 parser: OptionParser,
617 ) -> int:
618 """
619 Call the validator function on applicable settings and
620 evaluate the 'overrides' option.
621 Extends `optparse.Option.process`.
622 """
623 result = super().process(opt, value, values, parser)
624 setting = self.dest
625 if setting:
626 if self.validator:
627 value = getattr(values, setting)
628 try:
629 new_value = self.validator(setting, value, parser)
630 except Exception as err:
631 raise optparse.OptionValueError(
632 'Error in option "%s":\n %s'
633 % (opt, io.error_string(err)))
634 setattr(values, setting, new_value)
635 if self.overrides:
636 setattr(values, self.overrides, None)
637 return result
640class OptionParser(optparse.OptionParser, docutils.SettingsSpec):
641 """
642 Settings parser for command-line and library use.
644 The `settings_spec` specification here and in other Docutils components
645 are merged to build the set of command-line options and runtime settings
646 for this process.
648 Common settings (defined below) and component-specific settings must not
649 conflict. Short options are reserved for common settings, and components
650 are restricted to using long options.
652 Deprecated.
653 Will be replaced by a subclass of `argparse.ArgumentParser`.
654 """
656 standard_config_files: ClassVar[list[str]] = [
657 '/etc/docutils.conf', # system-wide
658 './docutils.conf', # project-specific
659 '~/.docutils'] # user-specific
660 """Docutils configuration files, using ConfigParser syntax.
662 Filenames will be tilde-expanded later. Later files override earlier ones.
663 """
665 threshold_choices: ClassVar[tuple[str]] = (
666 'info', '1', 'warning', '2', 'error', '3', 'severe', '4', 'none', '5')
667 """Possible inputs for for --report and --halt threshold values."""
669 thresholds: ClassVar[dict[str, int]] = {
670 'info': 1, 'warning': 2, 'error': 3, 'severe': 4, 'none': 5}
671 """Lookup table for --report and --halt threshold values."""
673 booleans: ClassVar[dict[str, bool]] = {
674 '1': True, 'on': True, 'yes': True, 'true': True,
675 '0': False, 'off': False, 'no': False, 'false': False, '': False}
676 """Lookup table for boolean configuration file settings."""
678 default_error_encoding: ClassVar[str] = (
679 getattr(sys.stderr, 'encoding', None)
680 or io._locale_encoding
681 or 'ascii')
683 default_error_encoding_error_handler: ClassVar[str] = 'backslashreplace'
685 settings_spec = (
686 'General Docutils Options',
687 None,
688 (('Output destination name. (default: stdout)',
689 ['--output', '-o'],
690 {'dest': 'output_path', 'metavar': '<destination>'}),
691 ('Specify the document title as metadata.',
692 ['--title'], {'metavar': '<title>'}),
693 ('Include a "Generated by Docutils" credit and link.',
694 ['--generator', '-g'],
695 {'action': 'store_true', 'validator': validate_boolean}),
696 ('Do not include a generator credit.',
697 ['--no-generator'],
698 {'dest': 'generator', 'action': 'store_false'}),
699 ('Include the date at the end of the document (UTC).',
700 ['--date', '-d'],
701 {'dest': 'datestamp', 'action': 'store_const', 'const': '%Y-%m-%d'}),
702 ('Include the time & date (UTC).',
703 ['--time', '-t'],
704 {'dest': 'datestamp', 'action': 'store_const',
705 'const': '%Y-%m-%d %H:%M UTC'}),
706 ('Do not include a datestamp of any kind.',
707 ['--no-datestamp'],
708 {'dest': 'datestamp', 'action': 'store_const', 'const': None}),
709 ('Base directory for absolute paths when reading '
710 'from the local filesystem. (default: "")',
711 ['--root-prefix'],
712 {'default': '', 'metavar': '<path>'}),
713 ('Include a "View document source" link.',
714 ['--source-link', '-s'],
715 {'action': 'store_true', 'validator': validate_boolean}),
716 ('Use <URL> for a source link; implies --source-link.',
717 ['--source-url'], {'metavar': '<URL>'}),
718 ('Do not include a "View document source" link.',
719 ['--no-source-link'],
720 {'action': 'callback', 'callback': store_multiple,
721 'callback_args': ('source_link', 'source_url')}),
722 ('Link from section headers to TOC entries. (default)',
723 ['--toc-entry-backlinks'],
724 {'dest': 'toc_backlinks', 'action': 'store_const', 'const': 'entry',
725 'default': 'entry'}),
726 ('Link from section headers to the top of the TOC.',
727 ['--toc-top-backlinks'],
728 {'dest': 'toc_backlinks', 'action': 'store_const', 'const': 'top'}),
729 ('Disable backlinks to the table of contents.',
730 ['--no-toc-backlinks'],
731 {'dest': 'toc_backlinks', 'action': 'store_false'}),
732 ('Link from footnotes/citations to references. (default)',
733 ['--footnote-backlinks'],
734 {'action': 'store_true', 'default': True,
735 'validator': validate_boolean}),
736 ('Disable backlinks from footnotes and citations.',
737 ['--no-footnote-backlinks'],
738 {'dest': 'footnote_backlinks', 'action': 'store_false'}),
739 ('Enable section numbering by Docutils. (default)',
740 ['--section-numbering'],
741 {'dest': 'sectnum_xform', 'action': 'store_true',
742 'default': True, 'validator': validate_boolean}),
743 ('Disable section numbering by Docutils.',
744 ['--no-section-numbering'],
745 {'dest': 'sectnum_xform', 'action': 'store_false'}),
746 ('Remove comment elements from the document tree.',
747 ['--strip-comments'],
748 {'action': 'store_true', 'validator': validate_boolean}),
749 ('Leave comment elements in the document tree. (default)',
750 ['--leave-comments'],
751 {'dest': 'strip_comments', 'action': 'store_false'}),
752 ('Remove all elements with classes="<class>" from the document tree. '
753 'Warning: potentially dangerous; use with caution. '
754 '(multiple-use option.)',
755 ['--strip-elements-with-class'],
756 {'dest': 'strip_elements_with_classes', 'action': 'append',
757 'metavar': '<class>', 'validator': validate_strip_class}),
758 ('Remove all classes="<class>" attributes from elements in the '
759 'document tree. Warning: potentially dangerous; use with caution. '
760 '(multiple-use option.)',
761 ['--strip-class'],
762 {'dest': 'strip_classes', 'action': 'append',
763 'metavar': '<class>', 'validator': validate_strip_class}),
764 ('Report system messages at or higher than <level>: "info" or "1", '
765 '"warning"/"2" (default), "error"/"3", "severe"/"4", "none"/"5"',
766 ['--report', '-r'],
767 {'dest': 'report_level', 'choices': threshold_choices, 'default': 2,
768 'metavar': '<level>', 'validator': validate_threshold}),
769 ('Report all system messages. (Same as "--report=1".)',
770 ['--verbose', '-v'],
771 {'dest': 'report_level', 'action': 'store_const', 'const': 1}),
772 ('Report no system messages. (Same as "--report=5".)',
773 ['--quiet', '-q'],
774 {'dest': 'report_level', 'action': 'store_const', 'const': 5}),
775 ('Halt execution at system messages at or above <level>. '
776 'Levels as in --report. Default: 4 (severe).',
777 ['--halt'],
778 {'dest': 'halt_level', 'choices': threshold_choices, 'default': 4,
779 'metavar': '<level>', 'validator': validate_threshold}),
780 ('Halt at the slightest problem. Same as "--halt=info".',
781 ['--strict'],
782 {'dest': 'halt_level', 'action': 'store_const', 'const': 1}),
783 ('Enable a non-zero exit status for non-halting system messages at '
784 'or above <level>. Default: 5 (disabled).',
785 ['--exit-status'],
786 {'dest': 'exit_status_level', 'choices': threshold_choices,
787 'default': 5,
788 'metavar': '<level>', 'validator': validate_threshold}),
789 ('Enable debug-level system messages and diagnostics.',
790 ['--debug'],
791 {'action': 'store_true', 'validator': validate_boolean}),
792 ('Disable debug output. (default)',
793 ['--no-debug'],
794 {'dest': 'debug', 'action': 'store_false'}),
795 ('Send the output of system messages to <file>.',
796 ['--warnings'],
797 {'dest': 'warning_stream', 'metavar': '<file>'}),
798 ('Enable Python tracebacks when Docutils is halted.',
799 ['--traceback'],
800 {'action': 'store_true', 'validator': validate_boolean}),
801 ('Disable Python tracebacks. (default)',
802 ['--no-traceback'],
803 {'dest': 'traceback', 'action': 'store_false'}),
804 ('Specify the encoding and optionally the '
805 'error handler of input text. (default: utf-8)',
806 ['--input-encoding'],
807 {'metavar': '<name[:handler]>', 'default': 'utf-8',
808 'validator': validate_encoding_and_error_handler}),
809 (SUPPRESS_HELP, ['--input-encoding-error-handler'],
810 {'default': 'strict', 'validator': validate_encoding_error_handler}),
811 ('Specify the text encoding and optionally the error handler for '
812 'output. (default: utf-8)',
813 ['--output-encoding'],
814 {'metavar': '<name[:handler]>', 'default': 'utf-8',
815 'validator': validate_encoding_and_error_handler}),
816 (SUPPRESS_HELP, ['--output-encoding-error-handler'],
817 {'default': 'strict', 'validator': validate_encoding_error_handler}),
818 ('Specify text encoding and optionally the error handler'
819 f' for error output. (default: {default_error_encoding})',
820 ['--error-encoding', '-e'],
821 {'metavar': '<name[:handler]>', 'default': default_error_encoding,
822 'validator': validate_encoding_and_error_handler}),
823 (SUPPRESS_HELP, ['--error-encoding-error-handler'],
824 {'default': default_error_encoding_error_handler,
825 'validator': validate_encoding_error_handler}),
826 ('Specify the language (as BCP 47 language tag). (default: en)',
827 ['--language', '-l'],
828 {'dest': 'language_code', 'metavar': '<tag>', 'default': 'en'}),
829 ('Write output file dependencies to <file>.',
830 ['--record-dependencies'],
831 {'metavar': '<file>', 'validator': validate_dependency_file,
832 'default': None}), # default file set in Values class
833 ('Read configuration settings from <file>, if it exists.',
834 ['--config'],
835 {'metavar': '<file>', 'type': 'string',
836 'action': 'callback', 'callback': read_config_file}),
837 ("Show this program's version number and exit.",
838 ['--version', '-V'],
839 {'action': 'version'}),
840 ('Show this help message and exit.',
841 ['--help', '-h'],
842 {'action': 'help'}),
843 # Typically not useful for non-programmatical use:
844 (SUPPRESS_HELP, ['--id-prefix'], {'default': ''}),
845 (SUPPRESS_HELP, ['--auto-id-prefix'], {'default': '%'}),
846 (SUPPRESS_HELP, ['--output-path'], {}),
847 # Hidden options, for development use only:
848 (SUPPRESS_HELP, ['--dump-settings'], {'action': 'store_true'}),
849 (SUPPRESS_HELP, ['--dump-internals'], {'action': 'store_true'}),
850 (SUPPRESS_HELP, ['--dump-transforms'], {'action': 'store_true'}),
851 (SUPPRESS_HELP, ['--dump-pseudo-xml'], {'action': 'store_true'}),
852 (SUPPRESS_HELP, ['--expose-internal-attribute'],
853 {'dest': 'expose_internals', 'action': 'append',
854 'validator': validate_colon_separated_string_list}),
855 (SUPPRESS_HELP, ['--strict-visitor'], {'action': 'store_true'}),
856 ))
857 """Runtime settings and command-line options common to all Docutils front
858 ends. Setting specs specific to individual Docutils components are also
859 used (see `populate_from_components()`)."""
861 settings_defaults = {'_disable_config': None,
862 '_source': None,
863 '_destination': None,
864 '_config_files': None}
865 """Defaults for settings without command-line option equivalents.
867 See https://docutils.sourceforge.io/docs/user/config.html#internal-settings
868 """
870 relative_path_settings: tuple[str, ...] = () # will be modified
872 config_section = 'general'
874 version_template: ClassVar[str] = '%%prog (Docutils %s%s, Python %s, on %s)' % ( # NoQA: E501
875 docutils.__version__,
876 (details := docutils.__version_details__) and f' [{details}]' or '',
877 sys.version.split()[0],
878 sys.platform)
879 """Default version message."""
881 def __init__(self,
882 components: Iterable[SettingsSpec] = (),
883 defaults: Mapping[str, Any] | None = None,
884 read_config_files: bool | None = False,
885 *args,
886 **kwargs,
887 ) -> None:
888 """Set up OptionParser instance.
890 `components` is a list of Docutils components each containing a
891 ``.settings_spec`` attribute.
892 `defaults` is a mapping of setting default overrides.
893 """
895 self.lists: dict[str, Literal[True]] = {}
896 """Set of list-type settings."""
898 self.config_files: list[str] = []
899 """List of paths of applied configuration files."""
901 self.relative_path_settings = ('warning_stream',) # will be modified
903 warnings.warn(
904 'The frontend.OptionParser class will be replaced by a subclass '
905 'of argparse.ArgumentParser in Docutils 2.0 or later.\n '
906 'To get default settings, use frontend.get_default_settings().',
907 DeprecationWarning, stacklevel=2)
908 super().__init__(option_class=Option, add_help_option=False,
909 formatter=optparse.TitledHelpFormatter(width=78),
910 *args, **kwargs)
911 if not self.version:
912 self.version = self.version_template
913 self.components: tuple[SettingsSpec, ...] = (self, *components)
914 self.populate_from_components(self.components)
915 self.defaults.update(defaults or {})
916 if read_config_files and not self.defaults['_disable_config']:
917 try:
918 config_settings = self.get_standard_config_settings()
919 except ValueError as err:
920 self.error(str(err))
921 self.defaults.update(config_settings.__dict__)
923 def populate_from_components(self, components: Iterable[SettingsSpec],
924 ) -> None:
925 """Collect settings specification from components.
927 For each component, populate from the `SettingsSpec.settings_spec`
928 structure, then from the `SettingsSpec.settings_defaults` dictionary.
929 After all components have been processed, check for and populate from
930 each component's `SettingsSpec.settings_default_overrides` dictionary.
931 """
932 for component in components:
933 if component is None:
934 continue
935 settings_spec = component.settings_spec
936 self.relative_path_settings += component.relative_path_settings
937 for i in range(0, len(settings_spec), 3):
938 title, description, option_spec = settings_spec[i:i+3]
939 if title:
940 group = optparse.OptionGroup(self, title, description)
941 self.add_option_group(group)
942 else:
943 group = self # single options
944 for (help_text, option_strings, kwargs) in option_spec:
945 option = group.add_option(help=help_text, *option_strings,
946 **kwargs)
947 if kwargs.get('action') == 'append':
948 self.lists[option.dest] = True
949 if component.settings_defaults:
950 self.defaults.update(component.settings_defaults)
951 for component in components:
952 if component and component.settings_default_overrides:
953 self.defaults.update(component.settings_default_overrides)
955 @classmethod
956 def get_standard_config_files(cls) -> Sequence[StrPath]:
957 """Return list of config files, from environment or standard."""
958 if 'DOCUTILSCONFIG' in os.environ:
959 config_files = os.environ['DOCUTILSCONFIG'].split(os.pathsep)
960 else:
961 config_files = cls.standard_config_files
962 return [os.path.expanduser(f) for f in config_files if f.strip()]
964 def get_standard_config_settings(self) -> Values:
965 with warnings.catch_warnings():
966 warnings.filterwarnings('ignore', category=DeprecationWarning)
967 settings = Values()
968 for filename in self.get_standard_config_files():
969 settings.update(self.get_config_file_settings(filename), self)
970 return settings
972 def get_config_file_settings(self, config_file: str) -> dict[str, Any]:
973 """Returns a dictionary containing appropriate config file settings."""
974 config_parser = ConfigParser()
975 # parse config file, add filename if found and successfully read.
976 applied = set()
977 with warnings.catch_warnings():
978 warnings.filterwarnings('ignore', category=DeprecationWarning)
979 self.config_files += config_parser.read(config_file, self)
980 settings = Values()
981 for component in self.components:
982 if not component:
983 continue
984 for section in (tuple(component.config_section_dependencies or ())
985 + (component.config_section,)):
986 if section in applied:
987 continue
988 applied.add(section)
989 if config_parser.has_section(section):
990 settings.update(config_parser[section], self)
991 make_paths_absolute(settings.__dict__,
992 self.relative_path_settings,
993 os.path.dirname(config_file))
994 return settings.__dict__
996 def check_values(self, values: Values, args: list[str]) -> Values:
997 """Store positional arguments as runtime settings.
999 Provisional. Handling of positional arguments will change
1000 in Docutils 2.0 (see RELEASE-NOTES).
1001 """
1002 values._source, values._destination = self.check_args(args)
1003 make_paths_absolute(values.__dict__, self.relative_path_settings)
1004 values._config_files = self.config_files
1005 return values
1007 def check_args(self, args: list[str]) -> tuple[str|None]:
1008 # internal, provisional:
1009 # will be removed in Docutils 2.0 when multiple sources are allowed.
1010 source = None
1011 if args:
1012 source = args.pop(0)
1013 if source == '-': # means stdin
1014 source = None
1015 if args:
1016 self.error('Only 1 argument allowed.')
1017 return source, None
1019 def get_default_values(self) -> Values:
1020 """Needed to get custom `Values` instances."""
1021 with warnings.catch_warnings():
1022 warnings.filterwarnings('ignore', category=DeprecationWarning)
1023 defaults = Values(self.defaults)
1024 defaults._config_files = self.config_files
1025 return defaults
1027 def get_option_by_dest(self, dest: str) -> Option:
1028 """
1029 Get an option by its dest.
1031 If you're supplying a dest which is shared by several options,
1032 it is undefined which option of those is returned.
1034 A KeyError is raised if there is no option with the supplied
1035 dest.
1036 """
1037 for group in self.option_groups + [self]:
1038 for option in group.option_list:
1039 if option.dest == dest:
1040 return option
1041 raise KeyError('No option with dest == %r.' % dest)
1044class ConfigParser(configparser.RawConfigParser):
1045 """Parser for Docutils configuration files.
1047 See https://docutils.sourceforge.io/docs/user/config.html.
1049 Option key normalization includes conversion of '-' to '_'.
1051 Config file encoding is "utf-8". Encoding errors are reported
1052 and the affected file(s) skipped.
1054 This class is provisional and will change in future versions.
1055 """
1057 old_settings: ClassVar[dict[str, tuple[str, str]]] = {
1058 'pep_stylesheet': ('pep_html writer', 'stylesheet'),
1059 'pep_stylesheet_path': ('pep_html writer', 'stylesheet_path'),
1060 'pep_template': ('pep_html writer', 'template')}
1061 """{old setting: (new section, new setting)} mapping, used by
1062 `handle_old_config`, to convert settings from the old [options] section.
1063 """
1065 old_warning: ClassVar[str] = (
1066 'The "[option]" section is deprecated.\n'
1067 'Support for old-format configuration files will be removed in '
1068 'Docutils 2.0. Please revise your configuration files. '
1069 'See <https://docutils.sourceforge.io/docs/user/config.html>, '
1070 'section "Old-Format Configuration Files".')
1072 not_utf8_error: ClassVar[str] = """\
1073Unable to read configuration file "%s": content not encoded as UTF-8.
1074Skipping "%s" configuration file.
1075"""
1077 def read(self,
1078 filenames: str | Sequence[str],
1079 option_parser: OptionParser | None = None,
1080 ) -> list[str]:
1081 # Currently, if a `docutils.frontend.OptionParser` instance is
1082 # supplied, setting values are validated.
1083 if option_parser is not None:
1084 warnings.warn('frontend.ConfigParser.read(): parameter '
1085 '"option_parser" will be removed '
1086 'in Docutils 2.0 or later.',
1087 DeprecationWarning, stacklevel=2)
1088 read_ok = []
1089 if isinstance(filenames, str):
1090 filenames = [filenames]
1091 for filename in filenames:
1092 # Config files are UTF-8-encoded:
1093 try:
1094 read_ok += super().read(filename, encoding='utf-8')
1095 except UnicodeDecodeError:
1096 sys.stderr.write(self.not_utf8_error % (filename, filename))
1097 continue
1098 if 'options' in self:
1099 self.handle_old_config(filename)
1100 if option_parser is not None:
1101 self.validate_settings(filename, option_parser)
1102 return read_ok
1104 def handle_old_config(self, filename: str) -> None:
1105 warnings.warn_explicit(self.old_warning, ConfigDeprecationWarning,
1106 filename, 0)
1107 try:
1108 options = dict(self['options'])
1109 except KeyError:
1110 options = {}
1111 if not self.has_section('general'):
1112 self.add_section('general')
1113 for key, value in options.items():
1114 if key in self.old_settings:
1115 section, setting = self.old_settings[key]
1116 if not self.has_section(section):
1117 self.add_section(section)
1118 else:
1119 section = 'general'
1120 setting = key
1121 if not self.has_option(section, setting):
1122 self.set(section, setting, value)
1123 self.remove_section('options')
1125 def validate_settings(self, filename: str, option_parser: OptionParser,
1126 ) -> None:
1127 """
1128 Call the validator function and implement overrides on all applicable
1129 settings.
1130 """
1131 for section in self.sections():
1132 for setting in self.options(section):
1133 try:
1134 option = option_parser.get_option_by_dest(setting)
1135 except KeyError:
1136 continue
1137 if option.validator:
1138 value = self.get(section, setting)
1139 try:
1140 new_value = option.validator(
1141 setting, value, option_parser,
1142 config_parser=self, config_section=section)
1143 except Exception as err:
1144 raise ValueError(f'Error in config file "{filename}", '
1145 f'section "[{section}]":\n'
1146 f' {io.error_string(err)}\n'
1147 f' {setting} = {value}')
1148 self.set(section, setting, new_value)
1149 if option.overrides:
1150 self.set(section, option.overrides, None)
1152 def optionxform(self, optionstr: str) -> str:
1153 """
1154 Lowercase and transform '-' to '_'.
1156 So the cmdline form of option names can be used in config files.
1157 """
1158 return optionstr.lower().replace('-', '_')
1161class ConfigDeprecationWarning(FutureWarning):
1162 """Warning for deprecated configuration file features."""
1165def get_default_settings(*components: type[SettingsSpec]) -> Values:
1166 """Return default runtime settings for `components`.
1168 Return a `frontend.Values` instance with defaults for generic Docutils
1169 settings and settings from the `components` (`SettingsSpec` instances).
1171 This corresponds to steps 1 and 2 in the `runtime settings priority`__.
1173 __ https://docutils.sourceforge.io/docs/api/runtime-settings.html
1174 #settings-priority
1175 """
1176 with warnings.catch_warnings():
1177 warnings.filterwarnings('ignore', category=DeprecationWarning)
1178 return OptionParser(components).get_default_values()