__init__.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. # $Id: __init__.py 9103 2022-07-05 20:04:21Z grubert $
  2. # Author: David Goodger <goodger@python.org>
  3. # Copyright: This module has been placed in the public domain.
  4. """
  5. This is the Docutils (Python Documentation Utilities) package.
  6. Package Structure
  7. =================
  8. Modules:
  9. - __init__.py: Contains component base classes, exception classes, and
  10. Docutils version information.
  11. - core.py: Contains the ``Publisher`` class and ``publish_*()`` convenience
  12. functions.
  13. - frontend.py: Runtime settings (command-line interface, configuration files)
  14. processing, for Docutils front-ends.
  15. - io.py: Provides a uniform API for low-level input and output.
  16. - nodes.py: Docutils document tree (doctree) node class library.
  17. - statemachine.py: A finite state machine specialized for
  18. regular-expression-based text filters.
  19. Subpackages:
  20. - languages: Language-specific mappings of terms.
  21. - parsers: Syntax-specific input parser modules or packages.
  22. - readers: Context-specific input handlers which understand the data
  23. source and manage a parser.
  24. - transforms: Modules used by readers and writers to modify
  25. the Docutils document tree.
  26. - utils: Contains the ``Reporter`` system warning class and miscellaneous
  27. utilities used by readers, writers, and transforms.
  28. utils/urischemes.py: Contains a complete mapping of known URI addressing
  29. scheme names to descriptions.
  30. - utils/math: Contains functions for conversion of mathematical notation
  31. between different formats (LaTeX, MathML, text, ...).
  32. - writers: Format-specific output translators.
  33. """
  34. from collections import namedtuple
  35. __docformat__ = 'reStructuredText'
  36. __version__ = '0.19'
  37. """Docutils version identifier (complies with PEP 440)::
  38. major.minor[.micro][releaselevel[serial]][.dev]
  39. For version comparison operations, use `__version_info__` (see, below)
  40. rather than parsing the text of `__version__`.
  41. https://docutils.sourceforge.io/docs/dev/policies.html#version-identification
  42. """
  43. __version_details__ = ''
  44. """Optional extra version details (e.g. 'snapshot 2005-05-29, r3410').
  45. For development and release status, use `__version__ and `__version_info__`.
  46. """
  47. class VersionInfo(namedtuple('VersionInfo',
  48. 'major minor micro releaselevel serial release')):
  49. def __new__(cls, major=0, minor=0, micro=0,
  50. releaselevel='final', serial=0, release=True):
  51. releaselevels = ('alpha', 'beta', 'candidate', 'final')
  52. if releaselevel not in releaselevels:
  53. raise ValueError('releaselevel must be one of %r.'
  54. % (releaselevels, ))
  55. if releaselevel == 'final':
  56. if not release:
  57. raise ValueError('releaselevel "final" must not be used '
  58. 'with development versions (leads to wrong '
  59. 'version ordering of the related __version__')
  60. # cf. https://peps.python.org/pep-0440/#summary-of-permitted-suffixes-and-relative-ordering # noqa
  61. if serial != 0:
  62. raise ValueError('"serial" must be 0 for final releases')
  63. return super().__new__(cls, major, minor, micro,
  64. releaselevel, serial, release)
  65. def __lt__(self, other):
  66. if isinstance(other, tuple):
  67. other = VersionInfo(*other)
  68. return tuple.__lt__(self, other)
  69. def __gt__(self, other):
  70. if isinstance(other, tuple):
  71. other = VersionInfo(*other)
  72. return tuple.__gt__(self, other)
  73. def __le__(self, other):
  74. if isinstance(other, tuple):
  75. other = VersionInfo(*other)
  76. return tuple.__le__(self, other)
  77. def __ge__(self, other):
  78. if isinstance(other, tuple):
  79. other = VersionInfo(*other)
  80. return tuple.__ge__(self, other)
  81. __version_info__ = VersionInfo(
  82. major=0,
  83. minor=19,
  84. micro=0,
  85. releaselevel='final', # one of 'alpha', 'beta', 'candidate', 'final'
  86. serial=0, # pre-release number (0 for final releases and snapshots)
  87. release=True # True for official releases and pre-releases
  88. )
  89. """Comprehensive version information tuple.
  90. https://docutils.sourceforge.io/docs/dev/policies.html#version-identification
  91. """
  92. class ApplicationError(Exception): pass
  93. class DataError(ApplicationError): pass
  94. class SettingsSpec:
  95. """
  96. Runtime setting specification base class.
  97. SettingsSpec subclass objects used by `docutils.frontend.OptionParser`.
  98. """
  99. # TODO: replace settings_specs with a new data structure
  100. # Backwards compatiblity:
  101. # Drop-in components:
  102. # Sphinx supplies settings_spec in the current format in some places
  103. # Myst parser provides a settings_spec tuple
  104. #
  105. # Sphinx reads a settings_spec in order to set a default value
  106. # in writers/html.py:59
  107. # https://github.com/sphinx-doc/sphinx/blob/4.x/sphinx/writers/html.py
  108. # This should be changed (before retiring the old format)
  109. # to use `settings_default_overrides` instead.
  110. settings_spec = ()
  111. """Runtime settings specification. Override in subclasses.
  112. Defines runtime settings and associated command-line options, as used by
  113. `docutils.frontend.OptionParser`. This is a tuple of:
  114. - Option group title (string or `None` which implies no group, just a list
  115. of single options).
  116. - Description (string or `None`).
  117. - A sequence of option tuples. Each consists of:
  118. - Help text (string)
  119. - List of option strings (e.g. ``['-Q', '--quux']``).
  120. - Dictionary of keyword arguments sent to the OptionParser/OptionGroup
  121. ``add_option`` method.
  122. Runtime setting names are derived implicitly from long option names
  123. ('--a-setting' becomes ``settings.a_setting``) or explicitly from the
  124. 'dest' keyword argument.
  125. Most settings will also have a 'validator' keyword & function. The
  126. validator function validates setting values (from configuration files
  127. and command-line option arguments) and converts them to appropriate
  128. types. For example, the ``docutils.frontend.validate_boolean``
  129. function, **required by all boolean settings**, converts true values
  130. ('1', 'on', 'yes', and 'true') to 1 and false values ('0', 'off',
  131. 'no', 'false', and '') to 0. Validators need only be set once per
  132. setting. See the `docutils.frontend.validate_*` functions.
  133. See the optparse docs for more details.
  134. - More triples of group title, description, options, as many times as
  135. needed. Thus, `settings_spec` tuples can be simply concatenated.
  136. """
  137. settings_defaults = None
  138. """A dictionary of defaults for settings not in `settings_spec` (internal
  139. settings, intended to be inaccessible by command-line and config file).
  140. Override in subclasses."""
  141. settings_default_overrides = None
  142. """A dictionary of auxiliary defaults, to override defaults for settings
  143. defined in other components' `setting_specs`. Override in subclasses."""
  144. relative_path_settings = ()
  145. """Settings containing filesystem paths. Override in subclasses.
  146. Settings listed here are to be interpreted relative to the current working
  147. directory."""
  148. config_section = None
  149. """The name of the config file section specific to this component
  150. (lowercase, no brackets). Override in subclasses."""
  151. config_section_dependencies = None
  152. """A list of names of config file sections that are to be applied before
  153. `config_section`, in order (from general to specific). In other words,
  154. the settings in `config_section` are to be overlaid on top of the settings
  155. from these sections. The "general" section is assumed implicitly.
  156. Override in subclasses."""
  157. class TransformSpec:
  158. """
  159. Runtime transform specification base class.
  160. TransformSpec subclass objects used by `docutils.transforms.Transformer`.
  161. """
  162. def get_transforms(self):
  163. """Transforms required by this class. Override in subclasses."""
  164. if self.default_transforms != ():
  165. import warnings
  166. warnings.warn('TransformSpec: the "default_transforms" attribute '
  167. 'will be removed in Docutils 2.0.\n'
  168. 'Use get_transforms() method instead.',
  169. DeprecationWarning)
  170. return list(self.default_transforms)
  171. return []
  172. # Deprecated; for compatibility.
  173. default_transforms = ()
  174. unknown_reference_resolvers = ()
  175. """List of functions to try to resolve unknown references. Unknown
  176. references have a 'refname' attribute which doesn't correspond to any
  177. target in the document. Called when the transforms in
  178. `docutils.transforms.references` are unable to find a correct target. The
  179. list should contain functions which will try to resolve unknown
  180. references, with the following signature::
  181. def reference_resolver(node):
  182. '''Returns boolean: true if resolved, false if not.'''
  183. If the function is able to resolve the reference, it should also remove
  184. the 'refname' attribute and mark the node as resolved::
  185. del node['refname']
  186. node.resolved = 1
  187. Each function must have a "priority" attribute which will affect the order
  188. the unknown_reference_resolvers are run::
  189. reference_resolver.priority = 100
  190. Override in subclasses."""
  191. class Component(SettingsSpec, TransformSpec):
  192. """Base class for Docutils components."""
  193. component_type = None
  194. """Name of the component type ('reader', 'parser', 'writer'). Override in
  195. subclasses."""
  196. supported = ()
  197. """Name and aliases for this component. Override in subclasses."""
  198. def supports(self, format):
  199. """
  200. Is `format` supported by this component?
  201. To be used by transforms to ask the dependent component if it supports
  202. a certain input context or output format.
  203. """
  204. return format in self.supported