Debian Codegraph @

docutils/writers/html5_polyglot/__init__.py

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