Debian Codegraph @

docutils/writers/__init__.py

raw symbols SCIP
1 # $Id: __init__.py 10045 2025-03-09 01:02:23Z aa-turner $
2 # Author: David Goodger <[email protected]>
3 # Copyright: This module has been placed in the public domain.
4
5 """
6 This package contains Docutils Writer modules.
7 """
8
9 from __future__ import annotations
10
11 __docformat__ = 'reStructuredText'
12
13 import importlib
14 import sys
15 import urllib
16 from pathlib import Path
17
18 import docutils
19 from docutils import Component, languages, nodes, utils
20 from docutils.transforms import universal
21
22 TYPE_CHECKING = False
23 if TYPE_CHECKING:
24 from typing import Any, Final
25
26 from docutils.io import Output
27 from docutils.languages import LanguageModule
28 from docutils.nodes import StrPath
29 from docutils.transforms import Transform
30
31
32 class Writer(Component):
33
34 """
35 Abstract base class for docutils Writers.
36
37 Each writer module or package must export a subclass also called 'Writer'.
38 Each writer must support all standard node types listed in
39 `docutils.nodes.node_class_names`.
40
41 The `write()` method is the main entry point.
42 """
43
44 component_type: Final = 'writer'
45 config_section: Final = 'writers'
46
47 def get_transforms(self) -> list[type[Transform]]:
48 return super().get_transforms() + [universal.Messages,
49 universal.FilterMessages,
50 universal.StripClassesAndElements]
51
52 document: nodes.document | None = None
53 """The document to write (Docutils doctree); set by `write()`."""
54
55 output: str | bytes | None = None
56 """Final translated form of `document`
57
58 (`str` for text, `bytes` for binary formats); set by `translate()`.
59 """
60
61 language: LanguageModule | None = None
62 """Language module for the document; set by `write()`."""
63
64 destination: Output | None = None
65 """`docutils.io` Output object; where to write the document.
66
67 Set by `write()`.
68 """
69
70 def __init__(self) -> None:
71
72 self.parts: dict[str, Any] = {}
73 """Mapping of document part names to fragments of `self.output`.
74
75 See `Writer.assemble_parts()` below and
76 <https://docutils.sourceforge.io/docs/api/publisher.html>.
77 """
78
79 def write(self,
80 document: nodes.document,
81 destination: Output
82 ) -> str | bytes | None:
83 """
84 Process a document into its final form.
85
86 Translate `document` (a Docutils document tree) into the Writer's
87 native format, and write it out to its `destination` (a
88 `docutils.io.Output` subclass object).
89
90 Normally not overridden or extended in subclasses.
91 """
92 self.document = document
93 self.language = languages.get_language(
94 document.settings.language_code,
95 document.reporter)
96 self.destination = destination
97 self.translate()
98 return self.destination.write(self.output)
99
100 def translate(self) -> None:
101 """
102 Do final translation of `self.document` into `self.output`. Called
103 from `write`. Override in subclasses.
104
105 Usually done with a `docutils.nodes.NodeVisitor` subclass, in
106 combination with a call to `docutils.nodes.Node.walk()` or
107 `docutils.nodes.Node.walkabout()`. The ``NodeVisitor`` subclass must
108 support all standard elements (listed in
109 `docutils.nodes.node_class_names`) and possibly non-standard elements
110 used by the current Reader as well.
111 """
112 raise NotImplementedError('subclass must override this method')
113
114 def assemble_parts(self) -> None:
115 """Assemble the `self.parts` dictionary. Extend in subclasses.
116
117 See <https://docutils.sourceforge.io/docs/api/publisher.html>.
118 """
119 self.parts['whole'] = self.output
120 self.parts['encoding'] = self.document.settings.output_encoding
121 self.parts['errors'] = (
122 self.document.settings.output_encoding_error_handler)
123 self.parts['version'] = docutils.__version__
124
125
126 class UnfilteredWriter(Writer):
127
128 """
129 A writer that passes the document tree on unchanged (e.g. a
130 serializer.)
131
132 Documents written by UnfilteredWriters are typically reused at a
133 later date using a subclass of `readers.ReReader`.
134 """
135
136 def get_transforms(self) -> list[type[Transform]]:
137 # Do not add any transforms. When the document is reused
138 # later, the then-used writer will add the appropriate
139 # transforms.
140 return Component.get_transforms(self)
141
142
143 class DoctreeTranslator(nodes.NodeVisitor):
144 """
145 Generic Docutils document tree translator base class.
146
147 Adds auxiliary methods and attributes that are used by several
148 Docutils writers to the `nodes.NodeVisitor` abstract superclass.
149 """
150
151 def __init__(self, document) -> None:
152 super().__init__(document)
153 self.settings = document.settings
154
155 def uri2path(self, uri: str, output_path: StrPath|None = None) -> Path:
156 """Return filesystem path corresponding to a `URI reference`__.
157
158 The `root_prefix`__ setting` is applied to URI references starting
159 with "/" (but not to absolute Windows paths or "file" URIs).
160
161 If `output_path` (defaults to the `output_path`__ setting) is
162 not empty, relative paths are adjusted.
163 (To work in the output document, URI references with relative path
164 relate to the output directory. For access by the writer, paths
165 must be relative to the working directory.)
166
167 Use case:
168 The <image> element refers to the image via a "URI reference".
169 The corresponding filesystem path is required to read the
170 image size from the file or to embed the image in the output.
171
172 A filesystem path is also expected by the "LaTeX" output format
173 (with relative paths unchanged, relating to the output directory,
174 set `output_path` to the empty string).
175
176 Provisional: the function's location, interface and behaviour
177 may change without advance warning.
178
179 __ https://www.rfc-editor.org/rfc/rfc3986.html#section-4.1
180 __ https://docutils.sourceforge.io/docs/user/config.html#root-prefix
181 __ https://docutils.sourceforge.io/docs/user/config.html#output-path
182 """
183 if output_path is None:
184 output_path = self.settings.output_path
185 if uri.startswith('file:'):
186 return Path.from_uri(uri)
187 uri_parts = urllib.parse.urlsplit(uri)
188 if uri_parts.scheme != '':
189 raise ValueError(f'Cannot get file path corresponding to {uri}.')
190 # extract and adjust path from "relative URI reference"
191 path = urllib.parse.unquote(uri_parts.path)
192 if self.settings.root_prefix and path.startswith('/'):
193 return Path(self.settings.root_prefix) / path.removeprefix('/')
194 path = Path(path)
195 # adjust relative paths (but not "d:/foo" or similar)
196 if output_path and not path.is_absolute():
197 dest_dir = Path(output_path).parent.resolve()
198 path = Path(utils.relative_path(None, dest_dir/path))
199 # TODO: support paths relative to the *source* directory?
200 # source_path, line = utils.get_source_line(node)
201 # if source_path:
202 # source_dir = Path(source_path).parent.resolve()
203 # path = Path(utils.relative_path(None, source_dir/path)
204 return path
205
206
207 if sys.version_info[:2] < (3, 13):
208 # Backport `pathlib.Path.from_uri()` class method:
209 import pathlib
210
211 # subclassing from Path must consider the OS flavour
212 # https://stackoverflow.com/questions/29850801/subclass-pathlib-path-fails
213 class Path(type(pathlib.Path())): # noqa: F811 (redefinition of 'Path')
214 """`pathlib.Path` with `from_uri()` classmethod backported from 3.13.
215 """
216
217 # `from_uri()` is copied from
218 # https://github.com/python/cpython/blob/3.13/Lib/pathlib/_local.py
219 # with minor adaptions
220 @classmethod
221 def from_uri(cls, uri):
222 """Return a new path from the given 'file' URI."""
223 if not uri.startswith('file:'):
224 raise ValueError(f"URI does not start with 'file:': {uri!r}")
225 path = uri[5:]
226 if path[:3] == '///':
227 # Remove empty authority
228 path = path[2:]
229 elif path[:12] == '//localhost/':
230 # Remove 'localhost' authority
231 path = path[11:]
232 if path[:3] == '///' or (path[:1] == '/' and path[2:3] in ':|'):
233 # Remove slash before DOS device/UNC path
234 path = path[1:]
235 if path[1:2] == '|':
236 # Replace bar with colon in DOS drive
237 path = path[:1] + ':' + path[2:]
238 path = cls(urllib.parse.unquote(path))
239 if not path.is_absolute():
240 raise ValueError(f"URI is not absolute: {uri!r}")
241 return path
242
243
244 WRITER_ALIASES = {'html': 'html4css1', # will change to html5 in Docutils 2.0
245 'html4': 'html4css1',
246 'xhtml10': 'html4css1',
247 'html5': 'html5_polyglot',
248 'xhtml': 'html5_polyglot',
249 's5': 's5_html',
250 'latex': 'latex2e',
251 'xelatex': 'xetex',
252 'luatex': 'xetex',
253 'lualatex': 'xetex',
254 'odf': 'odf_odt',
255 'odt': 'odf_odt',
256 'ooffice': 'odf_odt',
257 'openoffice': 'odf_odt',
258 'libreoffice': 'odf_odt',
259 'pprint': 'pseudoxml',
260 'pformat': 'pseudoxml',
261 'pdf': 'rlpdf',
262 'xml': 'docutils_xml',
263 }
264
265
266 def get_writer_class(writer_name: str) -> type[Writer]:
267 """Return the Writer class from the `writer_name` module."""
268 name = writer_name.lower()
269 name = WRITER_ALIASES.get(name, name)
270 try:
271 module = importlib.import_module('docutils.writers.'+name)
272 except ImportError:
273 try:
274 module = importlib.import_module(name)
275 except ImportError as err:
276 raise ImportError(f'Writer "{writer_name}" not found. {err}')
277 return module.Writer