Debian Codegraph @

docutils/writers/html5_polyglot/__init__.py

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 # $Id: __init__.py 10291 2026-01-14 20:46:05Z milde $
2 # :Author: Günter Milde <[email protected]>
3 # Based on the html4css1 writer by David Goodger.
4 # :Maintainer: [email protected]
5 # :Copyright: © 2005, 2009, 2015 Günter Milde,
6 # portions from html4css1 © David Goodger.
7 # :License: Released under the terms of the `2-Clause BSD license`_, in short:
8 #
9 # Copying and distribution of this file, with or without modification,
10 # are permitted in any medium without royalty provided the copyright
11 # notice and this notice are preserved.
12 # This file is offered as-is, without any warranty.
13 #
14 # .. _2-Clause BSD license: https://opensource.org/licenses/BSD-2-Clause
15
16 # Use "best practice" as recommended by the W3C:
17 # http://www.w3.org/2009/cheatsheet/
18
19 """
20 Plain HyperText Markup Language document tree Writer.
21
22 The output conforms to the `HTML 5` specification.
23
24 The cascading style sheet "minimal.css" is required for proper viewing,
25 the style sheet "plain.css" improves reading experience.
26 """
27
28 from __future__ import annotations
29
30 __docformat__ = 'reStructuredText'
31
32 from pathlib import Path
33
34 from docutils import frontend, nodes
35 from docutils.writers import _html_base
36
37
38 class Writer(_html_base.Writer):
39
40 supported = ('html5', 'xhtml', 'html')
41 """Formats this writer supports."""
42
43 default_stylesheets = ['minimal.css', 'plain.css']
44 default_stylesheet_dirs = ['.', str(Path(__file__).parent)]
45 default_template = Path(__file__).parent / 'template.txt'
46
47 # use a copy of the parent spec with some modifications
48 settings_spec = frontend.filter_settings_spec(
49 _html_base.Writer.settings_spec,
50 template=(
51 f'Template file. (UTF-8 encoded, default: "{default_template}")',
52 ['--template'],
53 {'default': default_template, 'metavar': '<file>'}),
54 stylesheet_path=(
55 'Comma separated list of stylesheet paths. '
56 'Relative paths are expanded if a matching file is found in '
57 'the --stylesheet-dirs. With --link-stylesheet, '
58 'the path is rewritten relative to the output HTML file. '
59 '(default: "%s")' % ','.join(default_stylesheets),
60 ['--stylesheet-path'],
61 {'metavar': '<file[,file,...]>', 'overrides': 'stylesheet',
62 'validator': frontend.validate_comma_separated_list,
63 'default': default_stylesheets}),
64 stylesheet_dirs=(
65 'Comma-separated list of directories where stylesheets are found. '
66 'Used by --stylesheet-path when expanding relative path '
67 'arguments. (default: "%s")' % ','.join(default_stylesheet_dirs),
68 ['--stylesheet-dirs'],
69 {'metavar': '<dir[,dir,...]>',
70 'validator': frontend.validate_comma_separated_list,
71 'default': default_stylesheet_dirs}),
72 initial_header_level=(
73 'Specify the initial header level. Does not affect document '
74 'title & subtitle (see --no-doc-title). (default: 2 for "<h2>")',
75 ['--initial-header-level'],
76 {'choices': '1 2 3 4 5 6 auto'.split(), 'default': '2',
77 'metavar': '<level>'}),
78 no_xml_declaration=(
79 'Omit the XML declaration (default).',
80 ['--no-xml-declaration'],
81 {'dest': 'xml_declaration', 'action': 'store_false'}),
82 )
83 settings_spec = settings_spec + (
84 'HTML5 Writer Options',
85 '',
86 ((frontend.SUPPRESS_HELP, # Obsoleted by "--image-loading"
87 ['--embed-images'],
88 {'action': 'store_true',
89 'validator': frontend.validate_boolean}),
90 (frontend.SUPPRESS_HELP, # Obsoleted by "--image-loading"
91 ['--link-images'],
92 {'dest': 'embed_images', 'action': 'store_false'}),
93 ('Suggest at which point images should be loaded: '
94 '"embed", "link" (default), or "lazy".',
95 ['--image-loading'],
96 {'metavar': '<strategy>', 'choices': ('embed', 'link', 'lazy'),
97 # 'default': 'link' # default set in _html_base.py
98 }),
99 ('Append a self-link to section headings.',
100 ['--section-self-link'],
101 {'default': False, 'action': 'store_true'}),
102 ('Do not append a self-link to section headings. (default)',
103 ['--no-section-self-link'],
104 {'dest': 'section_self_link', 'action': 'store_false'}),
105 )
106 )
107
108 config_section = 'html5 writer'
109
110 def __init__(self) -> None:
111 self.parts = {}
112 self.translator_class = HTMLTranslator
113
114
115 class HTMLTranslator(_html_base.HTMLTranslator):
116 """
117 This writer generates `polyglot markup`: HTML5 that is also valid XML.
118
119 Safe subclassing: when overriding, treat ``visit_*`` and ``depart_*``
120 methods as a unit to prevent breaks due to internal changes. See the
121 docstring of docutils.writers._html_base.HTMLTranslator for details
122 and examples.
123 """
124
125 # self.starttag() arguments for the main document
126 documenttag_args = {'tagname': 'main'}
127
128 # add meta tag to fix rendering in mobile browsers
129 def __init__(self, document) -> None:
130 super().__init__(document)
131 self.meta.append('<meta name="viewport" '
132 'content="width=device-width, initial-scale=1" />\n')
133
134 # <acronym> tag obsolete in HTML5. Use the <abbr> tag instead.
135 def visit_acronym(self, node) -> None:
136 # @@@ implementation incomplete ("title" attribute)
137 self.body.append(self.starttag(node, 'abbr', ''))
138
139 def depart_acronym(self, node) -> None:
140 self.body.append('</abbr>')
141
142 # no standard meta tag name in HTML5, use separate "author" meta tags
143 # https://www.w3.org/TR/html5/document-metadata.html#standard-metadata-names
144 def visit_authors(self, node) -> None:
145 self.visit_docinfo_item(node, 'authors', meta=False)
146 for subnode in node:
147 self.meta.append('<meta name="author" content='
148 f'"{self.attval(subnode.astext())}" />\n')
149
150 def depart_authors(self, node) -> None:
151 self.depart_docinfo_item()
152
153 # use the <figcaption> semantic tag.
154 def visit_caption(self, node) -> None:
155 if isinstance(node.parent, nodes.figure):
156 self.body.append(self.starttag(node, 'figcaption'))
157 self.body.append('<p>')
158
159 def depart_caption(self, node) -> None:
160 self.body.append('</p>\n')
161 # <figcaption> is closed in depart_figure(), as legend may follow.
162
163 # use HTML block-level tags if matching class value found
164 supported_block_tags = {'ins', 'del'}
165
166 def visit_container(self, node) -> None:
167 # If there is exactly one of the "supported block tags" in
168 # the list of class values, use it as tag name:
169 classes = node['classes']
170 tags = [cls for cls in classes
171 if cls in self.supported_block_tags]
172 if len(tags) == 1:
173 node.html5tagname = tags[0]
174 classes.remove(tags[0])
175 else:
176 node.html5tagname = 'div'
177 self.body.append(self.starttag(node, node.html5tagname,
178 CLASS='docutils container'))
179
180 def depart_container(self, node) -> None:
181 self.body.append(f'</{node.html5tagname}>\n')
182 del node.html5tagname
183
184 # no standard meta tag name in HTML5, use dcterms.rights
185 # see https://wiki.whatwg.org/wiki/MetaExtensions
186 def visit_copyright(self, node) -> None:
187 self.visit_docinfo_item(node, 'copyright', meta=False)
188 self.meta.append('<meta name="dcterms.rights" '
189 f'content="{self.attval(node.astext())}" />\n')
190
191 def depart_copyright(self, node) -> None:
192 self.depart_docinfo_item()
193
194 # no standard meta tag name in HTML5, use dcterms.date
195 def visit_date(self, node) -> None:
196 self.visit_docinfo_item(node, 'date', meta=False)
197 self.meta.append('<meta name="dcterms.date" '
198 f'content="{self.attval(node.astext())}" />\n')
199
200 def depart_date(self, node) -> None:
201 self.depart_docinfo_item()
202
203 # use new HTML5 <figure> and <figcaption> elements
204 def visit_figure(self, node) -> None:
205 atts = {}
206 if 'width' in node:
207 atts['style'] = f"width: {node['width']}"
208 if node.get('align'):
209 atts['class'] = f"align-{node['align']}"
210 self.body.append(self.starttag(node, 'figure', **atts))
211
212 def depart_figure(self, node) -> None:
213 if len(node) > 1:
214 self.body.append('</figcaption>\n')
215 self.body.append('</figure>\n')
216
217 # use HTML5 <footer> element
218 def visit_footer(self, node) -> None:
219 self.context.append(len(self.body))
220
221 def depart_footer(self, node) -> None:
222 start = self.context.pop()
223 footer = [self.starttag(node, 'footer')]
224 footer.extend(self.body[start:])
225 footer.append('</footer>\n')
226 self.footer.extend(footer)
227 self.body_suffix[:0] = footer
228 del self.body[start:]
229
230 # use HTML5 <header> element
231 def visit_header(self, node) -> None:
232 self.context.append(len(self.body))
233
234 def depart_header(self, node) -> None:
235 start = self.context.pop()
236 header = [self.starttag(node, 'header')]
237 header.extend(self.body[start:])
238 header.append('</header>\n')
239 self.body_prefix.extend(header)
240 self.header.extend(header)
241 del self.body[start:]
242
243 # use HTML text-level tags if matching class value found
244 supported_inline_tags = {'code', 'kbd', 'dfn', 'samp', 'var',
245 'bdi', 'del', 'ins', 'mark', 'small',
246 'b', 'i', 'q', 's', 'u'}
247
248 # Use `supported_inline_tags` if found in class values
249 def visit_inline(self, node) -> None:
250 classes = node['classes']
251 node.html5tagname = 'span'
252 # Special handling for "code" directive content
253 if (isinstance(node.parent, nodes.literal_block)
254 and 'code' in node.parent.get('classes')
255 or isinstance(node.parent, nodes.literal)
256 and getattr(node.parent, 'html5tagname', None) == 'code'):
257 if classes == ['ln']:
258 # line numbers are not part of the "fragment of computer code"
259 if self.body[-1] == '<code>':
260 del self.body[-1]
261 else:
262 self.body.append('</code>')
263 node.html5tagname = 'small'
264 else:
265 tags = [cls for cls in self.supported_inline_tags
266 if cls in classes]
267 if len(tags):
268 node.html5tagname = tags[0]
269 classes.remove(node.html5tagname)
270 self.body.append(self.starttag(node, node.html5tagname, ''))
271
272 def depart_inline(self, node) -> None:
273 self.body.append(f'</{node.html5tagname}>')
274 if (node.html5tagname == 'small' and node.get('classes') == ['ln']
275 and isinstance(node.parent, nodes.literal_block)):
276 self.body.append(f'<code data-lineno="{node.astext()}">')
277 del node.html5tagname
278
279 # place inside HTML5 <figcaption> element (together with caption)
280 def visit_legend(self, node) -> None:
281 if not isinstance(node.previous_sibling(), nodes.caption):
282 self.body.append('<figcaption>\n')
283 self.body.append(self.starttag(node, 'div', CLASS='legend'))
284
285 def depart_legend(self, node) -> None:
286 self.body.append('</div>\n')
287 # <figcaption> closed in visit_figure()
288
289 # use HTML5 text-level tags if matching class value found
290 def visit_literal(self, node):
291 classes = node['classes']
292 html5tagname = 'span'
293 tags = [cls for cls in self.supported_inline_tags
294 if cls in classes]
295 if len(tags):
296 html5tagname = tags[0]
297 classes.remove(html5tagname)
298 if html5tagname == 'code':
299 node.html5tagname = html5tagname
300 self.body.append(self.starttag(node, html5tagname, ''))
301 return
302 self.body.append(
303 self.starttag(node, html5tagname, '', CLASS='docutils literal'))
304 text = node.astext()
305 # remove hard line breaks (except if in a parsed-literal block)
306 if not isinstance(node.parent, nodes.literal_block):
307 text = text.replace('\n', ' ')
308 # Protect text like ``--an-option`` and the regular expression
309 # ``[+]?(\d+(\.\d*)?|\.\d+)`` from bad line wrapping
310 for token in self.words_and_spaces.findall(text):
311 if token.strip() and self.in_word_wrap_point.search(token):
312 self.body.append(
313 f'<span class="pre">{self.encode(token)}</span>')
314 else:
315 self.body.append(self.encode(token))
316 self.body.append(f'</{html5tagname}>')
317 # Content already processed:
318 raise nodes.SkipNode
319
320 def depart_literal(self, node) -> None:
321 # skipped unless literal element is from "code" role:
322 self.depart_inline(node)
323
324 # Meta tags: 'lang' attribute replaced by 'xml:lang' in XHTML 1.1
325 # HTML5/polyglot recommends using both
326 def visit_meta(self, node) -> None:
327 if node.hasattr('lang'):
328 node['xml:lang'] = node['lang']
329 self.meta.append(self.emptytag(node, 'meta',
330 **node.non_default_attributes()))
331
332 def depart_meta(self, node) -> None:
333 pass
334
335 # no standard meta tag name in HTML5
336 def visit_organization(self, node) -> None:
337 self.visit_docinfo_item(node, 'organization', meta=False)
338
339 def depart_organization(self, node) -> None:
340 self.depart_docinfo_item()
341
342 # use the new HTML5 element <section>
343 def visit_section(self, node) -> None:
344 self.section_level += 1
345 self.body.append(
346 self.starttag(node, 'section'))
347
348 def depart_section(self, node) -> None:
349 self.section_level -= 1
350 self.body.append('</section>\n')
351
352 # use the new HTML5 element <aside>
353 def visit_sidebar(self, node) -> None:
354 self.body.append(
355 self.starttag(node, 'aside', CLASS='sidebar'))
356 self.in_sidebar = True
357
358 def depart_sidebar(self, node) -> None:
359 self.body.append('</aside>\n')
360 self.in_sidebar = False
361
362 # Use new HTML5 element <aside> or <nav>
363 # Add class value to <body>, if there is a ToC in the document
364 # (see responsive.css how this is used for a navigation sidebar).
365 def visit_topic(self, node) -> None:
366 atts = {'classes': ['topic']}
367 if 'contents' in node['classes']:
368 node.html5tagname = 'nav'
369 del atts['classes']
370 if isinstance(node.parent, nodes.document):
371 atts['role'] = 'doc-toc'
372 self.body_prefix[0] = '</head>\n<body class="with-toc">\n'
373 elif 'abstract' in node['classes']:
374 node.html5tagname = 'div'
375 atts['role'] = 'doc-abstract'
376 elif 'dedication' in node['classes']:
377 node.html5tagname = 'div'
378 atts['role'] = 'doc-dedication'
379 else:
380 node.html5tagname = 'aside'
381 self.body.append(self.starttag(node, node.html5tagname, **atts))
382
383 def depart_topic(self, node) -> None:
384 self.body.append(f'</{node.html5tagname}>\n')
385 del node.html5tagname
386
387 # append self-link
388 def section_title_tags(self, node):
389 start_tag, close_tag = super().section_title_tags(node)
390 ids = node.parent['ids']
391 if (ids and getattr(self.settings, 'section_self_link', None)
392 and not isinstance(node.parent, nodes.document)):
393 self_link = ('<a class="self-link" title="link to this section"'
394 f' href="#{ids[-1]}"></a>')
395 close_tag = close_tag.replace('</h', self_link + '</h')
396 return start_tag, close_tag