Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/docutils/__init__.py: 63%

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

84 statements  

1# $Id: __init__.py 10357 2026-06-14 21:16:29Z milde $ 

2# Author: David Goodger <goodger@python.org> 

3# Copyright: This module has been placed in the public domain. 

4 

5""" 

6This is the Docutils (Python Documentation Utilities) package. 

7 

8Package Structure 

9================= 

10 

11Modules: 

12 

13- __init__.py: Contains component base classes, exception classes, and 

14 Docutils version information. 

15 

16- core.py: Contains the ``Publisher`` class and ``publish_*()`` convenience 

17 functions. 

18 

19- frontend.py: Runtime settings (command-line interface, configuration files) 

20 processing, for Docutils front-ends. 

21 

22- io.py: Provides a uniform API for low-level input and output. 

23 

24- nodes.py: Docutils document tree (doctree) node class library. 

25 

26- statemachine.py: A finite state machine specialized for 

27 regular-expression-based text filters. 

28 

29Subpackages: 

30 

31- languages: Language-specific mappings of terms. 

32 

33- parsers: Syntax-specific input parser modules or packages. 

34 

35- readers: Context-specific input handlers which understand the data 

36 source and manage a parser. 

37 

38- transforms: Modules used by readers and writers to modify 

39 the Docutils document tree. 

40 

41- utils: Contains the ``Reporter`` system warning class and miscellaneous 

42 utilities used by readers, writers, and transforms. 

43 

44 utils/urischemes.py: Contains a complete mapping of known URI addressing 

45 scheme names to descriptions. 

46 

47- utils/math: Contains functions for conversion of mathematical notation 

48 between different formats (LaTeX, MathML, text, ...). 

49 

50- writers: Format-specific output translators. 

51""" 

52 

53from __future__ import annotations 

54 

55from collections import namedtuple 

56 

57TYPE_CHECKING = False 

58if TYPE_CHECKING: 

59 from collections.abc import Sequence 

60 from typing import Any, ClassVar, Literal, Union 

61 

62 from docutils.transforms import Transform 

63 

64 _Components = Literal['reader', 'parser', 'writer', 'input', 'output'] 

65 _OptionTuple = tuple[str, list[str], dict[str, Any]] 

66 _ReleaseLevels = Literal['alpha', 'beta', 'candidate', 'final'] 

67 _SettingsSpecTuple = Union[ 

68 tuple[str|None, str|None, Sequence[_OptionTuple]], 

69 tuple[str|None, str|None, Sequence[_OptionTuple], 

70 str|None, str|None, Sequence[_OptionTuple]], 

71 tuple[str|None, str|None, Sequence[_OptionTuple], 

72 str|None, str|None, Sequence[_OptionTuple], 

73 str|None, str|None, Sequence[_OptionTuple]], 

74 ] 

75 

76 

77__docformat__ = 'reStructuredText' 

78 

79__version__ = '1.0b1.dev' 

80"""Docutils version identifier (complies with PEP 440):: 

81 

82 major.minor[.micro][releaselevel[serial]][.dev] 

83 

84For version comparison operations, use `__version_info__` (see, below) 

85rather than parsing the text of `__version__`. 

86 

87https://docutils.sourceforge.io/docs/dev/policies.html#version-identification 

88""" 

89 

90__version_details__ = '' 

91"""Optional extra version details (e.g. 'snapshot 2005-05-29, r3410'). 

92 

93For development and release status, use `__version__ and `__version_info__`. 

94""" 

95 

96 

97class VersionInfo(namedtuple('VersionInfo', 

98 'major minor micro releaselevel serial release')): 

99 __slots__ = () 

100 

101 major: int 

102 minor: int 

103 micro: int 

104 releaselevel: _ReleaseLevels 

105 serial: int 

106 release: bool 

107 

108 def __new__(cls, 

109 major: int = 0, minor: int = 0, micro: int = 0, 

110 releaselevel: _ReleaseLevels = 'final', 

111 serial: int = 0, release: bool = True, 

112 ) -> VersionInfo: 

113 releaselevels = ('alpha', 'beta', 'candidate', 'final') 

114 if releaselevel not in releaselevels: 

115 raise ValueError('releaselevel must be one of %r.' 

116 % (releaselevels, )) 

117 if releaselevel == 'final': 

118 if not release: 

119 raise ValueError('releaselevel "final" must not be used ' 

120 'with development versions (leads to wrong ' 

121 'version ordering of the related __version__') 

122 # cf. https://peps.python.org/pep-0440/#summary-of-permitted-suffixes-and-relative-ordering # NoQA: E501 

123 if serial != 0: 

124 raise ValueError('"serial" must be 0 for final releases') 

125 

126 return super().__new__(cls, major, minor, micro, 

127 releaselevel, serial, release) 

128 

129 def __lt__(self, other: object) -> bool: 

130 if isinstance(other, tuple): 

131 other = VersionInfo(*other) 

132 return tuple.__lt__(self, other) 

133 

134 def __gt__(self, other: object) -> bool: 

135 if isinstance(other, tuple): 

136 other = VersionInfo(*other) 

137 return tuple.__gt__(self, other) 

138 

139 def __le__(self, other: object) -> bool: 

140 if isinstance(other, tuple): 

141 other = VersionInfo(*other) 

142 return tuple.__le__(self, other) 

143 

144 def __ge__(self, other: object) -> bool: 

145 if isinstance(other, tuple): 

146 other = VersionInfo(*other) 

147 return tuple.__ge__(self, other) 

148 

149 

150__version_info__ = VersionInfo( 

151 major=1, 

152 minor=0, 

153 micro=0, 

154 releaselevel='beta', # one of 'alpha', 'beta', 'candidate', 'final' 

155 serial=1, # pre-release number (0 for final releases and snapshots) 

156 release=False # True for official releases and pre-releases 

157 ) 

158"""Comprehensive version information tuple. 

159 

160https://docutils.sourceforge.io/docs/dev/policies.html#version-identification 

161""" 

162 

163 

164class ApplicationError(Exception): pass 

165class DataError(ApplicationError): pass 

166 

167 

168class SettingsSpec: 

169 

170 """ 

171 Runtime setting specification base class. 

172 

173 SettingsSpec subclass objects used by `docutils.frontend.OptionParser`. 

174 """ 

175 

176 # TODO: replace settings_specs with a new data structure 

177 # Backwards compatiblity: 

178 # Drop-in components: 

179 # Sphinx supplies settings_spec in the current format in some places 

180 # Myst parser provides a settings_spec tuple 

181 # 

182 # Sphinx reads a settings_spec in order to set a default value 

183 # in writers/html.py:59 

184 # https://github.com/sphinx-doc/sphinx/blob/4.x/sphinx/writers/html.py 

185 # This should be changed (before retiring the old format) 

186 # to use `settings_default_overrides` instead. 

187 settings_spec: ClassVar[_SettingsSpecTuple] = () 

188 """Runtime settings specification. Override in subclasses. 

189 

190 Defines runtime settings and associated command-line options, as used by 

191 `docutils.frontend.OptionParser`. This is a tuple of: 

192 

193 - Option group title (string or `None` which implies no group, just a list 

194 of single options). 

195 

196 - Description (string or `None`). 

197 

198 - A sequence of option tuples. Each consists of: 

199 

200 - Help text (string) 

201 

202 - List of option strings (e.g. ``['-Q', '--quux']``). 

203 

204 - Dictionary of keyword arguments sent to the OptionParser/OptionGroup 

205 ``add_option`` method. 

206 

207 Runtime setting names are derived implicitly from long option names 

208 ('--a-setting' becomes ``settings.a_setting``) or explicitly from the 

209 'dest' keyword argument. 

210 

211 Most settings will also have a 'validator' keyword & function. The 

212 validator function validates setting values (from configuration files 

213 and command-line option arguments) and converts them to appropriate 

214 types. For example, the ``docutils.frontend.validate_boolean`` 

215 function, **required by all boolean settings**, converts true values 

216 ('1', 'on', 'yes', and 'true') to 1 and false values ('0', 'off', 

217 'no', 'false', and '') to 0. Validators need only be set once per 

218 setting. See the `docutils.frontend.validate_*` functions. 

219 

220 See the optparse docs for more details. 

221 

222 - More triples of group title, description, options, as many times as 

223 needed. Thus, `settings_spec` tuples can be simply concatenated. 

224 """ 

225 

226 settings_defaults: ClassVar[dict[str, Any] | None] = None 

227 """A dictionary of defaults for settings not in `settings_spec` (internal 

228 settings, intended to be inaccessible by command-line and config file). 

229 Override in subclasses.""" 

230 

231 settings_default_overrides: ClassVar[dict[str, Any] | None] = None 

232 """A dictionary of auxiliary defaults, to override defaults for settings 

233 defined in other components' `setting_specs`. Override in subclasses.""" 

234 

235 relative_path_settings: ClassVar[tuple[str, ...]] = () 

236 """Settings containing filesystem paths. Override in subclasses. 

237 Settings listed here are to be interpreted relative to the current working 

238 directory.""" 

239 

240 config_section: ClassVar[str | None] = None 

241 """The name of the config file section specific to this component 

242 (lowercase, no brackets). Override in subclasses.""" 

243 

244 config_section_dependencies: ClassVar[tuple[str, ...] | None] = None 

245 """A list of names of config file sections that are to be applied before 

246 `config_section`, in order (from general to specific). In other words, 

247 the settings in `config_section` are to be overlaid on top of the settings 

248 from these sections. The "general" section is assumed implicitly. 

249 Override in subclasses.""" 

250 

251 

252class TransformSpec: 

253 """ 

254 Runtime transform specification base class. 

255 

256 Provides the interface to register "transforms" and helper functions 

257 to resolve references with a `docutils.transforms.Transformer`. 

258 

259 https://docutils.sourceforge.io/docs/ref/transforms.html 

260 """ 

261 

262 def get_transforms(self) -> list[type[Transform]]: 

263 """Transforms required by this class. Override in subclasses.""" 

264 if self.default_transforms != (): 

265 import warnings 

266 warnings.warn('TransformSpec: the "default_transforms" attribute ' 

267 'will be removed in Docutils 2.0.\n' 

268 'Use get_transforms() method instead.', 

269 DeprecationWarning) 

270 return list(self.default_transforms) 

271 return [] 

272 

273 # Deprecated; for compatibility. 

274 default_transforms: ClassVar[tuple[()]] = () 

275 

276 

277class Component(SettingsSpec, TransformSpec): 

278 

279 """Base class for Docutils components.""" 

280 

281 component_type: ClassVar[_Components | None] = None 

282 """Name of the component type ('reader', 'parser', 'writer'). 

283 Override in subclasses.""" 

284 

285 supported: ClassVar[tuple[str, ...]] = () 

286 """Name and aliases for this component. Override in subclasses.""" 

287 

288 def supports(self, format: str) -> bool: 

289 """ 

290 Is `format` supported by this component? 

291 

292 To be used by transforms to ask the dependent component if it supports 

293 a certain input context or output format. 

294 """ 

295 return format in self.supported