Debian Codegraph @

docutils/writers/_html_base.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 # :Author: David Goodger, Günter Milde
3 # Based on the html4css1 writer by David Goodger.
4 # :Maintainer: [email protected]
5 # :Revision: $Revision: 10272 $
6 # :Date: $Date: 2005-06-28$
7 # :Copyright: © 2016 David Goodger, Günter Milde
8 # :License: Released under the terms of the `2-Clause BSD license`_, in short:
9 #
10 # Copying and distribution of this file, with or without modification,
11 # are permitted in any medium without royalty provided the copyright
12 # notice and this notice are preserved.
13 # This file is offered as-is, without any warranty.
14 #
15 # .. _2-Clause BSD license: https://opensource.org/licenses/BSD-2-Clause
16
17 """Common definitions for Docutils HTML writers."""
18
19 from __future__ import annotations
20
21 __docformat__ = 'reStructuredText'
22
23 import base64
24 import mimetypes
25 import os
26 import os.path
27 import re
28 import warnings
29 import xml.etree.ElementTree as ET
30 from pathlib import Path
31
32 import docutils
33 from docutils import frontend, languages, nodes, utils, writers
34 from docutils.parsers.rst.directives import length_or_percentage_or_unitless
35 from docutils.parsers.rst.directives.images import PIL
36 from docutils.transforms import writer_aux
37 from docutils.utils.math import (latex2mathml, math2html, tex2mathml_extern,
38 unichar2tex, wrap_math_code, MathError)
39
40 TYPE_CHECKING = False
41 if TYPE_CHECKING:
42 from docutils.transforms import Transform
43
44
45 class Writer(writers.Writer):
46
47 supported = ('html', 'xhtml') # update in subclass
48 """Formats this writer supports."""
49
50 settings_spec = (
51 'HTML Writer Options',
52 None,
53 (('Specify the template file (UTF-8 encoded). '
54 '(default: writer dependent)',
55 ['--template'],
56 {'metavar': '<file>'}),
57 ('Comma separated list of stylesheet URLs. '
58 'Overrides previous --stylesheet and --stylesheet-path settings.',
59 ['--stylesheet'],
60 {'metavar': '<URL[,URL,...]>', 'overrides': 'stylesheet_path',
61 'validator': frontend.validate_comma_separated_list}),
62 ('Comma separated list of stylesheet paths. '
63 'Relative paths are expanded if a matching file is found in '
64 'the --stylesheet-dirs. With --link-stylesheet, '
65 'the path is rewritten relative to the output HTML file. '
66 '(default: writer dependent)',
67 ['--stylesheet-path'],
68 {'metavar': '<file[,file,...]>', 'overrides': 'stylesheet',
69 'validator': frontend.validate_comma_separated_list}),
70 ('Comma-separated list of directories where stylesheets are found. '
71 'Used by --stylesheet-path when expanding relative path arguments. '
72 '(default: writer dependent)',
73 ['--stylesheet-dirs'],
74 {'metavar': '<dir[,dir,...]>',
75 'validator': frontend.validate_comma_separated_list}),
76 ('Embed the stylesheet(s) in the output HTML file. The stylesheet '
77 'files must be accessible during processing. (default)',
78 ['--embed-stylesheet'],
79 {'default': True, 'action': 'store_true',
80 'validator': frontend.validate_boolean}),
81 ('Link to the stylesheet(s) in the output HTML file. ',
82 ['--link-stylesheet'],
83 {'dest': 'embed_stylesheet', 'action': 'store_false'}),
84 ('Specify the initial header level. '
85 'Does not affect document title & subtitle (see --no-doc-title).'
86 '(default: writer dependent).',
87 ['--initial-header-level'],
88 {'choices': '1 2 3 4 5 6 auto'.split(), 'default': '2',
89 'metavar': '<level>'}),
90 ('Format for footnote references: one of "superscript" or '
91 '"brackets". (default: "brackets")',
92 ['--footnote-references'],
93 {'choices': ['superscript', 'brackets'], 'default': 'brackets',
94 'metavar': '<format>',
95 'overrides': 'trim_footnote_reference_space'}),
96 ('Format for block quote attributions: '
97 'one of "dash" (em-dash prefix), "parentheses"/"parens", or "none". '
98 '(default: "dash")',
99 ['--attribution'],
100 {'choices': ['dash', 'parentheses', 'parens', 'none'],
101 'default': 'dash', 'metavar': '<format>'}),
102 ('Remove extra vertical whitespace between items of "simple" bullet '
103 'lists and enumerated lists. (default)',
104 ['--compact-lists'],
105 {'default': True, 'action': 'store_true',
106 'validator': frontend.validate_boolean}),
107 ('Disable compact simple bullet and enumerated lists.',
108 ['--no-compact-lists'],
109 {'dest': 'compact_lists', 'action': 'store_false'}),
110 ('Remove extra vertical whitespace between items of simple field '
111 'lists. (default)',
112 ['--compact-field-lists'],
113 {'default': True, 'action': 'store_true',
114 'validator': frontend.validate_boolean}),
115 ('Disable compact simple field lists.',
116 ['--no-compact-field-lists'],
117 {'dest': 'compact_field_lists', 'action': 'store_false'}),
118 ('Class value(s) assigned to all tables. '
119 'Defined styles: borderless, booktabs, '
120 'align-left, align-center, align-right, '
121 'colwidths-auto, colwidths-grid.',
122 ['--table-style'],
123 {'metavar': '<style>', 'default': ''}),
124 ('Math output format (one of "MathML", "HTML", "MathJax", '
125 'or "LaTeX") and option(s). (default: "MathML")',
126 ['--math-output'],
127 {'metavar': '<format [option(s)]>', 'default': 'MathML',
128 'validator': frontend.validate_math_output}),
129 ('Prepend an XML declaration. ',
130 ['--xml-declaration'],
131 {'default': False, 'action': 'store_true',
132 'validator': frontend.validate_boolean}),
133 ('Omit the XML declaration.',
134 ['--no-xml-declaration'],
135 {'dest': 'xml_declaration', 'action': 'store_false'}),
136 ('Obfuscate email addresses to confuse harvesters while still '
137 'keeping email links usable with standards-compliant browsers.',
138 ['--cloak-email-addresses'],
139 {'action': 'store_true', 'validator': frontend.validate_boolean}),
140 )
141 )
142
143 settings_defaults = {'output_encoding_error_handler': 'xmlcharrefreplace'}
144
145 relative_path_settings = ('template',)
146
147 config_section = 'html base writer' # overwrite in subclass
148 config_section_dependencies = ('writers', 'html writers')
149
150 visitor_attributes = (
151 'head_prefix', 'head', 'stylesheet', 'body_prefix',
152 'body_pre_docinfo', 'docinfo', 'body', 'body_suffix',
153 'title', 'subtitle', 'header', 'footer', 'meta', 'fragment',
154 'html_prolog', 'html_head', 'html_title', 'html_subtitle',
155 'html_body')
156
157 def get_transforms(self) -> list[type[Transform]]:
158 return super().get_transforms() + [writer_aux.Admonitions]
159
160 def translate(self) -> None:
161 self.visitor = visitor = self.translator_class(self.document)
162 self.document.walkabout(visitor)
163 for attr in self.visitor_attributes:
164 setattr(self, attr, getattr(visitor, attr))
165 self.output = self.apply_template()
166
167 def apply_template(self) -> str:
168 template_path = Path(self.document.settings.template)
169 template = template_path.read_text(encoding='utf-8')
170 return template % self.interpolation_dict()
171
172 def interpolation_dict(self):
173 subs = {}
174 settings = self.document.settings
175 for attr in self.visitor_attributes:
176 subs[attr] = ''.join(getattr(self, attr)).rstrip('\n')
177 subs['encoding'] = settings.output_encoding
178 subs['version'] = docutils.__version__
179 return subs
180
181 def assemble_parts(self) -> None:
182 super().assemble_parts()
183 for part in self.visitor_attributes:
184 self.parts[part] = ''.join(getattr(self, part))
185
186
187 class HTMLTranslator(writers.DoctreeTranslator):
188
189 """
190 Generic Docutils to HTML translator.
191
192 See the `html4css1` and `html5_polyglot` writers for full featured
193 HTML translators.
194
195 .. IMPORTANT::
196 The `visit_*` and `depart_*` methods use a
197 heterogeneous stack, `self.context`.
198 When subclassing, make sure to be consistent in its use!
199
200 Examples for robust coding:
201
202 a) Override both `visit_*` and `depart_*` methods, don't call the
203 parent functions.
204
205 b) Extend both and unconditionally call the parent functions::
206
207 def visit_example(self, node):
208 if foo:
209 self.body.append('<div class="foo">')
210 html4css1.HTMLTranslator.visit_example(self, node)
211
212 def depart_example(self, node):
213 html4css1.HTMLTranslator.depart_example(self, node)
214 if foo:
215 self.body.append('</div>')
216
217 c) Extend both, calling the parent functions under the same
218 conditions::
219
220 def visit_example(self, node):
221 if foo:
222 self.body.append('<div class="foo">\n')
223 else: # call the parent method
224 _html_base.HTMLTranslator.visit_example(self, node)
225
226 def depart_example(self, node):
227 if foo:
228 self.body.append('</div>\n')
229 else: # call the parent method
230 _html_base.HTMLTranslator.depart_example(self, node)
231
232 d) Extend one method (call the parent), but don't otherwise use the
233 `self.context` stack::
234
235 def depart_example(self, node):
236 _html_base.HTMLTranslator.depart_example(self, node)
237 if foo:
238 # implementation-specific code
239 # that does not use `self.context`
240 self.body.append('</div>\n')
241
242 This way, changes in stack use will not bite you.
243 """
244
245 doctype = '<!DOCTYPE html>\n'
246
247 head_prefix_template = ('<html xmlns="http://www.w3.org/1999/xhtml"'
248 ' xml:lang="%(lang)s" lang="%(lang)s">\n<head>\n')
249 content_type = '<meta charset="%s" />\n'
250 generator = (
251 f'<meta name="generator" content="Docutils {docutils.__version__}: '
252 'https://docutils.sourceforge.io/" />\n')
253 # `starttag()` arguments for the main document (HTML5 uses <main>)
254 documenttag_args = {'tagname': 'div', 'CLASS': 'document'}
255
256 # Template for the MathJax script in the header:
257 mathjax_script = '<script type="text/javascript" src="%s"></script>\n'
258
259 mathjax_url = 'file:/usr/share/javascript/mathjax/MathJax.js'
260 """
261 URL of the MathJax javascript library.
262
263 The MathJax library ought to be installed on the same
264 server as the rest of the deployed site files and specified
265 in the `math-output` setting appended to "mathjax".
266 See `Docutils Configuration`__.
267
268 __ https://docutils.sourceforge.io/docs/user/config.html#math-output
269
270 The fallback tries a local MathJax installation at
271 ``/usr/share/javascript/mathjax/MathJax.js``.
272 """
273
274 stylesheet_link = '<link rel="stylesheet" href="%s" type="text/css" />\n'
275 embedded_stylesheet = '<style type="text/css">\n\n%s\n</style>\n'
276 words_and_spaces = re.compile(r'[^ \n]+| +|\n')
277 # wrap point inside word:
278 in_word_wrap_point = re.compile(r'.+\W\W.+|[-?].+')
279 lang_attribute = 'lang' # name changes to 'xml:lang' in XHTML 1.1
280
281 special_characters = {ord('&'): '&amp;',
282 ord('<'): '&lt;',
283 ord('"'): '&quot;',
284 ord('>'): '&gt;',
285 ord('@'): '&#64;', # may thwart address harvesters
286 }
287 """Character references for characters with a special meaning in HTML."""
288
289 videotypes = ('video/mp4', 'video/webm', 'video/ogg')
290 """MIME types supported by the HTML5 <video> element."""
291
292 def __init__(self, document) -> None:
293 super().__init__(document)
294 # process settings
295 settings = self.settings
296 self.language = languages.get_language(
297 settings.language_code, document.reporter)
298 if settings.initial_header_level == 'auto':
299 if len(document) and document[0].next_node(
300 nodes.title, include_self=True, descend=False):
301 self.initial_header_level = 2
302 else:
303 self.initial_header_level = 1
304 else:
305 self.initial_header_level = int(settings.initial_header_level)
306 # image_loading (only defined for HTML5 writer)
307 _image_loading_default = 'link'
308 # convert legacy setting embed_images:
309 if getattr(settings, 'embed_images', None) is not None:
310 if settings.embed_images:
311 _image_loading_default = 'embed'
312 warnings.warn('The configuration setting "embed_images"\n'
313 ' will be removed in Docutils 2.0. '
314 f'Use "image_loading: {_image_loading_default}".',
315 FutureWarning, stacklevel=8)
316 self.image_loading = getattr(settings,
317 'image_loading', _image_loading_default)
318 # backwards compatibiltiy: validate/convert programatically set strings
319 if isinstance(self.settings.math_output, str):
320 self.settings.math_output = frontend.validate_math_output(
321 self.settings.math_output)
322 (self.math_output,
323 self.math_options) = self.settings.math_output
324
325 # set up "parts" (cf. docs/api/publisher.html#publish-parts-details)
326 #
327 self.body = [] # equivalent to `fragment`, ≠ `html_body`
328 self.body_prefix = ['</head>\n<body>\n'] # + optional header
329 self.body_pre_docinfo = [] # document heading (title and subtitle)
330 self.body_suffix = ['</body>\n</html>\n'] # + optional footer
331 self.docinfo = []
332 self.footer = []
333 self.fragment = [] # main content of the document ("naked" body)
334 self.head = []
335 self.head_prefix = [] # everything up to and including <head>
336 self.header = []
337 self.html_body = []
338 self.html_head = [self.content_type] # charset not interpolated
339 self.html_prolog = []
340 self.html_subtitle = []
341 self.html_title = []
342 self.meta = [self.generator]
343 self.stylesheet = [self.stylesheet_call(path)
344 for path in utils.get_stylesheet_list(settings)]
345 self.title = []
346 self.subtitle = []
347 if settings.xml_declaration:
348 self.head_prefix.append(
349 utils.xml_declaration(settings.output_encoding))
350 self.html_prolog.append(
351 utils.xml_declaration('%s')) # encoding not interpolated
352 if (settings.output_encoding
353 and settings.output_encoding.lower() != 'unicode'):
354 self.meta.insert(0, self.content_type % settings.output_encoding)
355
356 # bookkeeping attributes; reflect state of translator
357 #
358 self.context = []
359 """Heterogeneous stack.
360
361 Used by visit_* and depart_* functions in conjunction with the tree
362 traversal. Make sure that the pops correspond to the pushes.
363 """
364 self.section_level = 0
365 self.colspecs = []
366 self.compact_p = True
367 self.compact_simple = False
368 self.compact_field_list = False
369 self.in_docinfo = False
370 self.in_sidebar = False
371 self.in_document_title = 0 # len(self.body) or 0
372 self.in_mailto = False
373 self.author_in_authors = False # for html4css1
374 self.math_header = []
375 self.messages = []
376 """Queue of system_message nodes (writing issues).
377
378 Call `report_messages()` in `depart_*_block()` methods to clean up!
379 """
380
381 def astext(self):
382 return ''.join(self.head_prefix + self.head
383 + self.stylesheet + self.body_prefix
384 + self.body_pre_docinfo + self.docinfo
385 + self.body + self.body_suffix)
386
387 def attval(self, text,
388 whitespace=re.compile('[\n\r\t\v\f]')):
389 """Cleanse, HTML encode, and return attribute value text."""
390 encoded = self.encode(whitespace.sub(' ', text))
391 if self.in_mailto and self.settings.cloak_email_addresses:
392 # Cloak at-signs ("%40") and periods with HTML entities.
393 encoded = encoded.replace('%40', '&#37;&#52;&#48;')
394 encoded = encoded.replace('.', '&#46;')
395 return encoded
396
397 def cloak_email(self, addr):
398 """Try to hide the link text of a email link from harversters."""
399 # Surround at-signs and periods with <span> tags. ("@" has
400 # already been encoded to "&#64;" by the `encode` method.)
401 addr = addr.replace('&#64;', '<span>&#64;</span>')
402 return addr.replace('.', '<span>&#46;</span>')
403
404 def cloak_mailto(self, uri):
405 """Try to hide a mailto: URL from harvesters."""
406 # Encode "@" using a URL octet reference (see RFC 1738).
407 # Further cloaking with HTML entities will be done in the
408 # `attval` function.
409 return uri.replace('@', '%40')
410
411 def encode(self, text):
412 """Encode special characters in `text` & return."""
413 # Use only named entities known in both XML and HTML
414 # other characters are automatically encoded "by number" if required.
415 # @@@ A codec to do these and all other HTML entities would be nice.
416 text = str(text)
417 return text.translate(self.special_characters)
418
419 def image_size(self, node: nodes.image) -> dict[str, str]:
420 """Determine the image size from node arguments or the image file.
421
422 Return as dictionary of <img> attributes,
423 e.g., ``{height': '32', 'style': 'width: 4 em;'}``.
424
425 Auxiliary method called from `self.visit_image()`.
426 Provisional.
427 """
428 dimensions = ('width', 'height')
429 measures = {} # (value, unit)-tuples) for width and height
430 for dimension in dimensions:
431 if dimension in node:
432 measures[dimension] = nodes.parse_measure(node[dimension])
433 if 'scale' in node and len(measures) < 2:
434 # supplement with (unitless) values read from image file
435 imgsize = self.read_size_with_PIL(node)
436 if imgsize:
437 for dimension, value in zip(dimensions, imgsize):
438 if dimension not in measures:
439 measures[dimension] = (value, '')
440 # Scale and format as <img> attributes,
441 # use "width" and "hight" for unitless values and "style" else:
442 scaling_factor = node.get('scale', 100) / 100
443 size_atts = {}
444 declarations = [] # declarations for the "style" attribute
445 for dimension, (value, unit) in measures.items():
446 value *= scaling_factor
447 if unit:
448 declarations.append(f'{dimension}: {value:g}{unit};')
449 else:
450 size_atts[dimension] = f'{round(value)}'
451 if declarations:
452 size_atts['style'] = ' '.join(declarations)
453 return size_atts
454
455 def read_size_with_PIL(self, node) -> tuple[int, int] | None:
456 # Try reading size from image file.
457 # Internal auxiliary method called from `self.image_size()`.
458 # TODO: use https://github.com/shibukawa/imagesize_py
459 # faster, also handles SVG, attention: bug
460 reading_problems = []
461 uri = node['uri']
462 if not PIL:
463 reading_problems.append('Requires Python Imaging Library.')
464 if mimetypes.guess_type(uri)[0] in self.videotypes:
465 reading_problems.append('PIL cannot read video images.')
466 if not self.settings.file_insertion_enabled:
467 reading_problems.append('Reading external files disabled.')
468 if not reading_problems:
469 try:
470 imagepath = self.uri2path(uri)
471 with PIL.Image.open(imagepath) as img:
472 imgsize = img.size
473 except (ValueError, OSError, UnicodeEncodeError) as err:
474 reading_problems.append(str(err))
475 else:
476 self.settings.record_dependencies.add(imagepath)
477 if reading_problems:
478 msg = ['Cannot scale image!',
479 f'Could not get size from "{uri}":',
480 *reading_problems]
481 self.messages.append(self.document.reporter.warning(
482 '\n '.join(msg), base_node=node))
483 return None
484 return imgsize
485
486 def prepare_svg(self, code: str, node: nodes.Element, atts: dict) -> str:
487 # Parse SVG source `code` (ignoring comments and preamble code),
488 # add relevant attributes from `node` and `atts` to the root element.
489 #
490 # Internal auxiliary method called from `self.visit_image()`.
491 svg_ns = {'': 'http://www.w3.org/2000/svg',
492 'xlink': 'http://www.w3.org/1999/xlink'} # SVG namespace
493 # don't add SVG namespace to all elements
494 for key, value in svg_ns.items():
495 ET.register_namespace(key, value)
496 # Parse:
497 try:
498 svg = ET.fromstring(code)
499 except ET.ParseError as err:
500 self.messages.append(self.document.reporter.error(
501 f'Cannot parse SVG image "{node["uri"]}":\n {err}',
502 base_node=node))
503 return code
504 # Apply image node attributes:
505 if 'style' in atts:
506 # update style declarations
507 declaration_dict = {}
508 svg_declarations = svg.get('style', '').split(';')
509 node_declarations = atts['style'].split(';')
510 for declaration in svg_declarations + node_declarations:
511 if not declaration.strip():
512 continue
513 key, _, value = declaration.partition(':')
514 declaration_dict[key.strip()] = value.strip()
515 svg.set('style', ' '.join(f'{k}: {v};'
516 for k, v in declaration_dict.items()))
517 for dimension in ('width', 'height'):
518 if dimension in atts:
519 svg.set(dimension, atts[dimension])
520 if 'classes' in atts or node['classes']:
521 classes = svg.get('class', '').split()
522 classes += node['classes'] + atts.get('classes', [])
523 svg.set('class', ' '.join(classes))
524 if 'alt' in node and svg.find('title', svg_ns) is None:
525 svg_title = ET.Element('title')
526 svg_title.text = node['alt']
527 svg.insert(0, svg_title)
528 return ET.tostring(svg, encoding='unicode')
529
530 def stylesheet_call(self, path, adjust_path=None):
531 """Return code to reference or embed stylesheet file `path`"""
532 if adjust_path is None:
533 adjust_path = bool(self.settings.stylesheet_path)
534 if self.settings.embed_stylesheet:
535 try:
536 content = Path(path).read_text(encoding='utf-8')
537 except OSError as err:
538 msg = f'Cannot embed stylesheet: {err}'
539 self.document.reporter.error(msg)
540 return '<--- %s --->\n' % msg
541 else:
542 self.settings.record_dependencies.add(path)
543 return self.embedded_stylesheet % content
544 # else link to style file:
545 if adjust_path:
546 # rewrite path relative to output (cf. config.html#stylesheet-path)
547 path = utils.relative_path(self.settings.output_path, path)
548 return self.stylesheet_link % self.encode(path)
549
550 def starttag(self, node, tagname, suffix='\n', empty=False, **attributes):
551 """
552 Construct and return a start tag given a node (id & class attributes
553 are extracted), tag name, and optional attributes.
554 """
555 tagname = tagname.lower()
556 prefix = []
557 atts = {}
558 for (name, value) in attributes.items():
559 atts[name.lower()] = value
560 classes = atts.pop('classes', [])
561 languages = []
562 # unify class arguments and move language specification
563 for cls in node.get('classes', []) + atts.pop('class', '').split():
564 if cls.startswith('language-'):
565 languages.append(cls.removeprefix('language-'))
566 elif cls.strip() and cls not in classes:
567 classes.append(cls)
568 if languages:
569 # attribute name is 'lang' in XHTML 1.0 but 'xml:lang' in 1.1
570 atts[self.lang_attribute] = languages[0]
571 # filter classes that are processed by the writer:
572 internal = ('colwidths-auto', 'colwidths-given', 'colwidths-grid')
573 if isinstance(node, nodes.table):
574 classes = [cls for cls in classes if cls not in internal]
575 if classes:
576 atts['class'] = ' '.join(classes)
577 assert 'id' not in atts
578 ids = node.get('ids', [])
579 ids.extend(atts.pop('ids', []))
580 if ids:
581 atts['id'] = ids[0]
582 for id in ids[1:]:
583 # Add empty "span" elements for additional IDs. Note
584 # that we cannot use empty "a" elements because there
585 # may be targets inside of references, but nested "a"
586 # elements aren't allowed in XHTML (even if they do
587 # not all have a "href" attribute).
588 if empty or isinstance(node, (nodes.Sequential,
589 nodes.docinfo,
590 nodes.table)):
591 # Insert target right in front of element.
592 prefix.append('<span id="%s"></span>' % id)
593 else:
594 # Non-empty tag. Place the auxiliary <span> tag
595 # *inside* the element, as the first child.
596 suffix += '<span id="%s"></span>' % id
597 attlist = sorted(atts.items())
598 parts = [tagname]
599 for name, value in attlist:
600 # value=None was used for boolean attributes without
601 # value, but this isn't supported by XHTML.
602 assert value is not None
603 if isinstance(value, list):
604 values = [str(v) for v in value]
605 parts.append('%s="%s"' % (name.lower(),
606 self.attval(' '.join(values))))
607 else:
608 parts.append('%s="%s"' % (name.lower(),
609 self.attval(str(value))))
610 if empty:
611 infix = ' /'
612 else:
613 infix = ''
614 return f"{''.join(prefix)}<{' '.join(parts)}{infix}>{suffix}"
615
616 def emptytag(self, node, tagname, suffix='\n', **attributes):
617 """Construct and return an XML-compatible empty tag."""
618 return self.starttag(node, tagname, suffix, empty=True, **attributes)
619
620 def report_messages(self, node) -> None:
621 if isinstance(node.parent, (nodes.system_message, nodes.entry)):
622 return
623 while self.messages:
624 message = self.messages.pop(0)
625 if self.settings.report_level <= message['level']:
626 message.walkabout(self)
627
628 def set_class_on_child(self, node, class_, index=0) -> None:
629 """
630 Set class `class_` on the visible child no. index of `node`.
631 Do nothing if node has fewer children than `index`.
632 """
633 children = [n for n in node if not isinstance(n, nodes.Invisible)]
634 try:
635 child = children[index]
636 except IndexError:
637 return
638 child['classes'].append(class_)
639
640 # Visitor methods
641 # ---------------
642
643 def visit_Text(self, node) -> None:
644 text = node.astext()
645 encoded = self.encode(text)
646 if self.in_mailto and self.settings.cloak_email_addresses:
647 encoded = self.cloak_email(encoded)
648 self.body.append(encoded)
649
650 def depart_Text(self, node) -> None:
651 pass
652
653 def visit_abbreviation(self, node) -> None:
654 # @@@ implementation incomplete ("title" attribute)
655 self.body.append(self.starttag(node, 'abbr', ''))
656
657 def depart_abbreviation(self, node) -> None:
658 self.body.append('</abbr>')
659
660 def visit_acronym(self, node) -> None:
661 # @@@ implementation incomplete ("title" attribute)
662 self.body.append(self.starttag(node, 'acronym', ''))
663
664 def depart_acronym(self, node) -> None:
665 self.body.append('</acronym>')
666
667 def visit_address(self, node) -> None:
668 self.visit_docinfo_item(node, 'address', meta=False)
669 self.body.append(self.starttag(node, 'pre',
670 suffix='', CLASS='address'))
671
672 def depart_address(self, node) -> None:
673 self.body.append('\n</pre>\n')
674 self.depart_docinfo_item()
675
676 def visit_admonition(self, node) -> None:
677 self.body.append(self.starttag(node, 'aside', classes=['admonition']))
678
679 def depart_admonition(self, node=None) -> None:
680 self.body.append('</aside>\n')
681
682 attribution_formats = {'dash': ('\u2014', ''),
683 'parentheses': ('(', ')'),
684 'parens': ('(', ')'),
685 'none': ('', '')}
686
687 def visit_attribution(self, node) -> None:
688 prefix, suffix = self.attribution_formats[self.settings.attribution]
689 self.context.append(suffix)
690 self.body.append(
691 self.starttag(node, 'p', prefix, CLASS='attribution'))
692
693 def depart_attribution(self, node) -> None:
694 self.body.append(self.context.pop() + '</p>\n')
695
696 def visit_author(self, node) -> None:
697 if not isinstance(node.parent, nodes.authors):
698 self.visit_docinfo_item(node, 'author')
699 self.body.append('<p>')
700
701 def depart_author(self, node) -> None:
702 self.body.append('</p>')
703 if isinstance(node.parent, nodes.authors):
704 self.body.append('\n')
705 else:
706 self.depart_docinfo_item()
707
708 def visit_authors(self, node) -> None:
709 self.visit_docinfo_item(node, 'authors')
710
711 def depart_authors(self, node) -> None:
712 self.depart_docinfo_item()
713
714 def visit_block_quote(self, node) -> None:
715 self.body.append(self.starttag(node, 'blockquote'))
716
717 def depart_block_quote(self, node) -> None:
718 self.body.append('</blockquote>\n')
719
720 def check_simple_list(self, node) -> bool:
721 """Check for a simple list that can be rendered compactly."""
722 visitor = SimpleListChecker(self.document)
723 try:
724 node.walk(visitor)
725 except nodes.NodeFound:
726 return False
727 else:
728 return True
729
730 # Compact lists
731 # ------------
732 # Include definition lists and field lists (in addition to ordered
733 # and unordered lists) in the test if a list is "simple" (cf. the
734 # html4css1.HTMLTranslator docstring and the SimpleListChecker class at
735 # the end of this file).
736
737 def is_compactable(self, node):
738 # explicit class arguments have precedence
739 if 'compact' in node['classes']:
740 return True
741 if 'open' in node['classes']:
742 return False
743 # check config setting:
744 if (isinstance(node, (nodes.field_list, nodes.definition_list))
745 and not self.settings.compact_field_lists):
746 return False
747 if (isinstance(node, (nodes.enumerated_list, nodes.bullet_list))
748 and not self.settings.compact_lists):
749 return False
750 # Table of Contents:
751 if 'contents' in node.parent['classes']:
752 return True
753 # check the list items:
754 return self.check_simple_list(node)
755
756 def visit_bullet_list(self, node) -> None:
757 atts = {}
758 old_compact_simple = self.compact_simple
759 self.context.append((self.compact_simple, self.compact_p))
760 self.compact_p = None
761 self.compact_simple = self.is_compactable(node)
762 if self.compact_simple and not old_compact_simple:
763 atts['class'] = 'simple'
764 self.body.append(self.starttag(node, 'ul', **atts))
765
766 def depart_bullet_list(self, node) -> None:
767 self.compact_simple, self.compact_p = self.context.pop()
768 self.body.append('</ul>\n')
769
770 def visit_caption(self, node) -> None:
771 self.body.append(self.starttag(node, 'p', '', CLASS='caption'))
772
773 def depart_caption(self, node) -> None:
774 self.body.append('</p>\n')
775
776 # Use semantic tag and DPub role (HTML4 uses a table)
777 def visit_citation(self, node) -> None:
778 # role 'doc-bibloentry' requires wrapping in an element with
779 # role 'list' and an element with role 'doc-bibliography'
780 # https://www.w3.org/TR/dpub-aria-1.0/#doc-biblioentry)
781 if not isinstance(node.previous_sibling(), type(node)):
782 self.body.append('<div role="list" class="citation-list">\n')
783 self.body.append(self.starttag(node, 'div', classes=[node.tagname],
784 role="doc-biblioentry"))
785
786 def depart_citation(self, node) -> None:
787 self.body.append('</div>\n')
788 if not isinstance(node.next_node(descend=False, siblings=True),
789 type(node)):
790 self.body.append('</div>\n')
791
792 # Use DPub role (overwritten in HTML4)
793 def visit_citation_reference(self, node) -> None:
794 href = '#'
795 if 'refid' in node:
796 href += node['refid']
797 elif 'refname' in node:
798 href += self.document.nameids[node['refname']]
799 # else: # TODO system message (or already in the transform)?
800 # 'Citation reference missing.'
801 self.body.append(self.starttag(node, 'a', suffix='[', href=href,
802 classes=['citation-reference'],
803 role='doc-biblioref'))
804
805 def depart_citation_reference(self, node) -> None:
806 self.body.append(']</a>')
807
808 def visit_classifier(self, node) -> None:
809 self.body.append(self.starttag(node, 'span', '', CLASS='classifier'))
810
811 def depart_classifier(self, node) -> None:
812 self.body.append('</span>')
813 self.depart_term(node) # close the term element after last classifier
814
815 def visit_colspec(self, node) -> None:
816 self.colspecs.append(node)
817 # "stubs" list is an attribute of the tgroup element:
818 node.parent.stubs.append(node.attributes.get('stub'))
819
820 def depart_colspec(self, node) -> None:
821 # write out <colgroup> when all colspecs are processed
822 if isinstance(node.next_node(descend=False, siblings=True),
823 nodes.colspec):
824 return
825 if 'colwidths-auto' in node.parent.parent['classes'] or (
826 'colwidths-grid' not in self.settings.table_style
827 and 'colwidths-given' not in node.parent.parent['classes']):
828 return
829 self.body.append(self.starttag(node, 'colgroup'))
830 total_width = sum(node.propwidth() for node in self.colspecs)
831 for node in self.colspecs:
832 colwidth = node.propwidth() / total_width
833 self.body.append(self.emptytag(node, 'col',
834 style=f'width: {colwidth:.1%}'))
835 self.body.append('</colgroup>\n')
836
837 def visit_comment(self, node,
838 sub=re.compile('-(?=-)').sub):
839 """Escape double-dashes in comment text."""
840 self.body.append('<!-- %s -->\n' % sub('- ', node.astext()))
841 # Content already processed:
842 raise nodes.SkipNode
843
844 def visit_compound(self, node) -> None:
845 self.body.append(self.starttag(node, 'div', CLASS='compound'))
846
847 def depart_compound(self, node) -> None:
848 self.body.append('</div>\n')
849
850 def visit_container(self, node) -> None:
851 self.body.append(self.starttag(node, 'div',
852 CLASS='docutils container'))
853
854 def depart_container(self, node) -> None:
855 self.body.append('</div>\n')
856
857 def visit_contact(self, node) -> None:
858 self.visit_docinfo_item(node, 'contact', meta=False)
859
860 def depart_contact(self, node) -> None:
861 self.depart_docinfo_item()
862
863 def visit_copyright(self, node) -> None:
864 self.visit_docinfo_item(node, 'copyright')
865
866 def depart_copyright(self, node) -> None:
867 self.depart_docinfo_item()
868
869 def visit_date(self, node) -> None:
870 self.visit_docinfo_item(node, 'date')
871
872 def depart_date(self, node) -> None:
873 self.depart_docinfo_item()
874
875 def visit_decoration(self, node) -> None:
876 pass
877
878 def depart_decoration(self, node) -> None:
879 pass
880
881 def visit_definition(self, node) -> None:
882 if 'details' not in node.parent.parent['classes']:
883 self.body.append(self.starttag(node, 'dd', ''))
884
885 def depart_definition(self, node) -> None:
886 if 'details' not in node.parent.parent['classes']:
887 self.body.append('</dd>\n')
888
889 def visit_definition_list(self, node) -> None:
890 if 'details' in node['classes']:
891 self.body.append(self.starttag(node, 'div'))
892 else:
893 classes = ['simple'] if self.is_compactable(node) else []
894 self.body.append(self.starttag(node, 'dl', classes=classes))
895
896 def depart_definition_list(self, node) -> None:
897 if 'details' in node['classes']:
898 self.body.append('</div>\n')
899 else:
900 self.body.append('</dl>\n')
901
902 # Use a "details" disclosure element if parent has "class" arg "details".
903 def visit_definition_list_item(self, node) -> None:
904 if 'details' in node.parent['classes']:
905 atts = {}
906 if "open" in node.parent['classes']:
907 atts['open'] = 'open'
908 self.body.append(self.starttag(node, 'details', **atts))
909
910 def depart_definition_list_item(self, node) -> None:
911 if 'details' in node.parent['classes']:
912 self.body.append('</details>\n')
913
914 def visit_description(self, node) -> None:
915 self.body.append(self.starttag(node, 'dd', ''))
916
917 def depart_description(self, node) -> None:
918 self.body.append('</dd>\n')
919
920 def visit_docinfo(self, node) -> None:
921 self.context.append(len(self.body))
922 classes = ['docinfo']
923 if self.is_compactable(node):
924 classes.append('simple')
925 self.body.append(self.starttag(node, 'dl', classes=classes))
926
927 def depart_docinfo(self, node) -> None:
928 self.body.append('</dl>\n')
929 start = self.context.pop()
930 self.docinfo = self.body[start:]
931 self.body = []
932
933 def visit_docinfo_item(self, node, name, meta=True) -> None:
934 if meta:
935 self.meta.append(f'<meta name="{name}" '
936 f'content="{self.attval(node.astext())}" />\n')
937 self.body.append(f'<dt class="{name}">{self.language.labels[name]}'
938 '<span class="colon">:</span></dt>\n')
939 self.body.append(self.starttag(node, 'dd', '', CLASS=name))
940
941 def depart_docinfo_item(self) -> None:
942 self.body.append('</dd>\n')
943
944 def visit_doctest_block(self, node) -> None:
945 self.body.append(self.starttag(node, 'pre', suffix='',
946 classes=['code', 'python', 'doctest']))
947
948 def depart_doctest_block(self, node) -> None:
949 self.body.append('\n</pre>\n')
950
951 def visit_document(self, node) -> None:
952 title = (node.get('title')
953 or os.path.basename(node.get('source') or '')
954 or 'untitled Docutils document')
955 self.head.append(f'<title>{self.encode(title)}</title>\n')
956
957 def depart_document(self, node) -> None:
958 self.head_prefix.extend([self.doctype,
959 self.head_prefix_template %
960 {'lang': self.settings.language_code}])
961 self.html_prolog.append(self.doctype)
962 self.head = self.meta[:] + self.head
963 if 'name="dcterms.' in ''.join(self.meta):
964 self.head.append('<link rel="schema.dcterms"'
965 ' href="http://purl.org/dc/terms/"/>')
966 if self.math_header:
967 if self.math_output == 'mathjax':
968 self.head.extend(self.math_header)
969 else:
970 self.stylesheet.extend(self.math_header)
971 if (self.settings.output_encoding # may be None
972 and self.settings.output_encoding.lower() != 'unicode'):
973 # skip content-type meta tag with interpolated charset value:
974 self.html_head.extend(self.head[1:])
975 else:
976 self.html_head.extend(self.head)
977 self.body_prefix.append(self.starttag(node, **self.documenttag_args))
978 self.body_suffix.insert(0, f'</{self.documenttag_args["tagname"]}>\n')
979 self.fragment.extend(self.body) # self.fragment is the "naked" body
980 self.html_body.extend(self.body_prefix[1:] + self.body_pre_docinfo
981 + self.docinfo + self.body
982 + self.body_suffix[:-1])
983 assert not self.context, f'len(context) = {len(self.context)}'
984
985 def visit_emphasis(self, node) -> None:
986 self.body.append(self.starttag(node, 'em', ''))
987
988 def depart_emphasis(self, node) -> None:
989 self.body.append('</em>')
990
991 def visit_entry(self, node) -> None:
992 atts = {'classes': []}
993 if isinstance(node.parent.parent, nodes.thead):
994 atts['classes'].append('head')
995 if node.parent.parent.parent.stubs[node.parent.column]:
996 # "stubs" list is an attribute of the tgroup element
997 atts['classes'].append('stub')
998 if atts['classes']:
999 tagname = 'th'
1000 else:
1001 tagname = 'td'
1002 node.parent.column += 1
1003 if 'morerows' in node:
1004 atts['rowspan'] = node['morerows'] + 1
1005 if 'morecols' in node:
1006 atts['colspan'] = node['morecols'] + 1
1007 node.parent.column += node['morecols']
1008 self.body.append(self.starttag(node, tagname, '', **atts))
1009 self.context.append('</%s>\n' % tagname.lower())
1010
1011 def depart_entry(self, node) -> None:
1012 self.body.append(self.context.pop())
1013
1014 def visit_enumerated_list(self, node) -> None:
1015 atts = {'classes': []}
1016 if 'start' in node:
1017 atts['start'] = node['start']
1018 if 'enumtype' in node:
1019 atts['classes'].append(node['enumtype'])
1020 if self.is_compactable(node):
1021 atts['classes'].append('simple')
1022 self.body.append(self.starttag(node, 'ol', **atts))
1023
1024 def depart_enumerated_list(self, node) -> None:
1025 self.body.append('</ol>\n')
1026
1027 def visit_field_list(self, node) -> None:
1028 atts = {}
1029 classes = node.setdefault('classes', [])
1030 for i, cls in enumerate(classes):
1031 if cls.startswith('field-indent-'):
1032 try:
1033 indent_length = length_or_percentage_or_unitless(
1034 cls.removeprefix('field-indent-'), 'px')
1035 except ValueError:
1036 break
1037 atts['style'] = '--field-indent: %s;' % indent_length
1038 classes.pop(i)
1039 break
1040 classes.append('field-list')
1041 if self.is_compactable(node):
1042 classes.append('simple')
1043 self.body.append(self.starttag(node, 'dl', **atts))
1044
1045 def depart_field_list(self, node) -> None:
1046 self.body.append('</dl>\n')
1047
1048 def visit_field(self, node) -> None:
1049 # Insert children (<field_name> and <field_body>) directly.
1050 # Transfer "id" attribute to the <field_name> child node.
1051 for child in node:
1052 if isinstance(child, nodes.field_name):
1053 child['ids'].extend(node['ids'])
1054
1055 def depart_field(self, node) -> None:
1056 pass
1057
1058 # as field is ignored, pass class arguments to field-name and field-body:
1059 def visit_field_name(self, node) -> None:
1060 self.body.append(self.starttag(node, 'dt', '',
1061 classes=node.parent['classes']))
1062
1063 def depart_field_name(self, node) -> None:
1064 self.body.append('<span class="colon">:</span></dt>\n')
1065
1066 def visit_field_body(self, node) -> None:
1067 self.body.append(self.starttag(node, 'dd', '',
1068 classes=node.parent['classes']))
1069 # prevent misalignment of following content if the field is empty:
1070 if not node.children:
1071 self.body.append('<p></p>')
1072
1073 def depart_field_body(self, node) -> None:
1074 self.body.append('</dd>\n')
1075
1076 def visit_figure(self, node) -> None:
1077 atts = {'class': 'figure'}
1078 if node.get('width'):
1079 atts['style'] = 'width: %s' % node['width']
1080 if node.get('align'):
1081 atts['class'] += " align-" + node['align']
1082 self.body.append(self.starttag(node, 'div', **atts))
1083
1084 def depart_figure(self, node) -> None:
1085 self.body.append('</div>\n')
1086
1087 def visit_footer(self, node) -> None:
1088 self.context.append(len(self.body))
1089
1090 def depart_footer(self, node) -> None:
1091 start = self.context.pop()
1092 footer = [self.starttag(node, 'div', CLASS='footer'),
1093 '<hr class="footer" />\n']
1094 footer.extend(self.body[start:])
1095 footer.append('\n</div>\n')
1096 self.footer.extend(footer)
1097 self.body_suffix[:0] = footer
1098 del self.body[start:]
1099
1100 def visit_footnote(self, node) -> None:
1101 # No native HTML element: use <aside> with ARIA role
1102 # (html4css1 uses tables).
1103 # Wrap groups of footnotes for easier styling.
1104 label_style = self.settings.footnote_references # brackets/superscript
1105 if not isinstance(node.previous_sibling(), type(node)):
1106 self.body.append(f'<aside class="footnote-list {label_style}">\n')
1107 self.body.append(self.starttag(node, 'aside',
1108 classes=[node.tagname, label_style],
1109 role="doc-footnote"))
1110
1111 def depart_footnote(self, node) -> None:
1112 self.body.append('</aside>\n')
1113 if not isinstance(node.next_node(descend=False, siblings=True),
1114 type(node)):
1115 self.body.append('</aside>\n')
1116
1117 def visit_footnote_reference(self, node) -> None:
1118 href = '#' + node['refid']
1119 classes = [self.settings.footnote_references]
1120 self.body.append(self.starttag(node, 'a', suffix='', classes=classes,
1121 role='doc-noteref', href=href))
1122 self.body.append('<span class="fn-bracket">[</span>')
1123
1124 def depart_footnote_reference(self, node) -> None:
1125 self.body.append('<span class="fn-bracket">]</span>')
1126 self.body.append('</a>')
1127
1128 # Docutils-generated text: put section numbers in a span for CSS styling:
1129 def visit_generated(self, node):
1130 if 'sectnum' in node['classes']:
1131 # get section number (strip trailing no-break-spaces)
1132 sectnum = node.astext().rstrip(' ')
1133 self.body.append('<span class="sectnum">%s </span>'
1134 % self.encode(sectnum))
1135 # Content already processed:
1136 raise nodes.SkipNode
1137
1138 def depart_generated(self, node) -> None:
1139 pass
1140
1141 def visit_header(self, node) -> None:
1142 self.context.append(len(self.body))
1143
1144 def depart_header(self, node) -> None:
1145 start = self.context.pop()
1146 header = [self.starttag(node, 'div', CLASS='header')]
1147 header.extend(self.body[start:])
1148 header.append('\n<hr class="header"/>\n</div>\n')
1149 self.body_prefix.extend(header)
1150 self.header.extend(header)
1151 del self.body[start:]
1152
1153 def visit_image(self, node) -> None:
1154 # reference/embed images (still images and videos)
1155 uri = node['uri']
1156 alt = node.get('alt', uri)
1157 mimetype = mimetypes.guess_type(uri)[0]
1158 element = '' # the HTML element (including potential children)
1159 # attributes for the HTML tag:
1160 atts = self.image_size(node)
1161 # alignment is handled by CSS rules
1162 if 'align' in node:
1163 atts['classes'] = [f"align-{node['align']}"]
1164 # ``:loading:`` option (embed, link, lazy), default from setting,
1165 # exception: only embed videos if told via directive option
1166 loading = 'link' if mimetype in self.videotypes else self.image_loading
1167 loading = node.get('loading', loading)
1168 if loading == 'lazy':
1169 atts['loading'] = 'lazy'
1170 elif loading == 'embed':
1171 try:
1172 imagepath = self.uri2path(uri)
1173 if mimetype == 'image/svg+xml':
1174 imagedata = Path(imagepath).read_text(encoding='utf-8')
1175 else:
1176 imagedata = Path(imagepath).read_bytes()
1177 except (ValueError, OSError, UnicodeError) as err:
1178 self.messages.append(self.document.reporter.error(
1179 f'Cannot embed image "{uri}":\n {err}', base_node=node))
1180 # TODO: get external files with urllib.request (cf. odtwriter)?
1181 else:
1182 self.settings.record_dependencies.add(imagepath)
1183 if mimetype == 'image/svg+xml':
1184 element = self.prepare_svg(imagedata, node, atts)
1185 else:
1186 data64 = base64.b64encode(imagedata).decode()
1187 uri = f'data:{mimetype};base64,{data64}'
1188
1189 # No newlines around inline images (but all images may be nested
1190 # in a `reference` node which is a `TextElement` instance):
1191 if (not isinstance(node.parent, nodes.TextElement)
1192 or isinstance(node.parent, nodes.reference)
1193 and not isinstance(node.parent.parent, nodes.TextElement)):
1194 suffix = '\n'
1195 else:
1196 suffix = ''
1197
1198 if mimetype in self.videotypes:
1199 atts['title'] = alt
1200 if 'controls' in node['classes']:
1201 node['classes'].remove('controls')
1202 atts['controls'] = 'controls'
1203 element = (self.starttag(node, "video", suffix, src=uri, **atts)
1204 + f'<a href="{node["uri"]}">{alt}</a>{suffix}'
1205 + f'</video>{suffix}')
1206 elif mimetype == 'application/x-shockwave-flash':
1207 atts['type'] = mimetype
1208 element = (self.starttag(node, 'object', '', data=uri, **atts)
1209 + f'{alt}</object>{suffix}')
1210 elif element: # embedded SVG, see above
1211 element += suffix
1212 else:
1213 atts['alt'] = alt
1214 element = self.emptytag(node, 'img', suffix, src=uri, **atts)
1215 self.body.append(element)
1216 if suffix: # block-element
1217 self.report_messages(node)
1218
1219 def depart_image(self, node) -> None:
1220 pass
1221
1222 def visit_inline(self, node) -> None:
1223 self.body.append(self.starttag(node, 'span', ''))
1224
1225 def depart_inline(self, node) -> None:
1226 self.body.append('</span>')
1227
1228 # footnote and citation labels:
1229 def visit_label(self, node) -> None:
1230 self.body.append('<span class="label">')
1231 self.body.append('<span class="fn-bracket">[</span>')
1232 # footnote/citation backrefs:
1233 if self.settings.footnote_backlinks:
1234 backrefs = node.parent.get('backrefs', [])
1235 if len(backrefs) == 1:
1236 self.body.append('<a role="doc-backlink"'
1237 ' href="#%s">' % backrefs[0])
1238
1239 def depart_label(self, node) -> None:
1240 backrefs = []
1241 if self.settings.footnote_backlinks:
1242 backrefs = node.parent.get('backrefs', backrefs)
1243 if len(backrefs) == 1:
1244 self.body.append('</a>')
1245 self.body.append('<span class="fn-bracket">]</span></span>\n')
1246 if len(backrefs) > 1:
1247 backlinks = ['<a role="doc-backlink" href="#%s">%s</a>' % (ref, i)
1248 for (i, ref) in enumerate(backrefs, 1)]
1249 self.body.append('<span class="backrefs">(%s)</span>\n'
1250 % ','.join(backlinks))
1251
1252 def visit_legend(self, node) -> None:
1253 self.body.append(self.starttag(node, 'div', CLASS='legend'))
1254
1255 def depart_legend(self, node) -> None:
1256 self.body.append('</div>\n')
1257
1258 def visit_line(self, node) -> None:
1259 self.body.append(self.starttag(node, 'div', suffix='', CLASS='line'))
1260 if not len(node):
1261 self.body.append('<br />')
1262
1263 def depart_line(self, node) -> None:
1264 self.body.append('</div>\n')
1265
1266 def visit_line_block(self, node) -> None:
1267 self.body.append(self.starttag(node, 'div', CLASS='line-block'))
1268
1269 def depart_line_block(self, node) -> None:
1270 self.body.append('</div>\n')
1271
1272 def visit_list_item(self, node) -> None:
1273 self.body.append(self.starttag(node, 'li', ''))
1274
1275 def depart_list_item(self, node) -> None:
1276 self.body.append('</li>\n')
1277
1278 # inline literal
1279 def visit_literal(self, node):
1280 # special case: "code" role
1281 classes = node['classes']
1282 if 'code' in classes:
1283 # filter 'code' from class arguments
1284 classes.pop(classes.index('code'))
1285 self.body.append(self.starttag(node, 'code', ''))
1286 return
1287 self.body.append(
1288 self.starttag(node, 'span', '', CLASS='docutils literal'))
1289 text = node.astext()
1290 if not isinstance(node.parent, nodes.literal_block):
1291 text = text.replace('\n', ' ')
1292 # Protect text like ``--an-option`` and the regular expression
1293 # ``[+]?(\d+(\.\d*)?|\.\d+)`` from bad line wrapping
1294 for token in self.words_and_spaces.findall(text):
1295 if token.strip() and self.in_word_wrap_point.search(token):
1296 self.body.append('<span class="pre">%s</span>'
1297 % self.encode(token))
1298 else:
1299 self.body.append(self.encode(token))
1300 self.body.append('</span>')
1301 raise nodes.SkipNode # content already processed
1302
1303 def depart_literal(self, node) -> None:
1304 # skipped unless literal element is from "code" role:
1305 self.body.append('</code>')
1306
1307 def visit_literal_block(self, node) -> None:
1308 self.body.append(self.starttag(node, 'pre', '', CLASS='literal-block'))
1309 if 'code' in node['classes']:
1310 self.body.append('<code>')
1311
1312 def depart_literal_block(self, node) -> None:
1313 if 'code' in node['classes']:
1314 self.body.append('</code>')
1315 self.body.append('</pre>\n')
1316
1317 # Mathematics:
1318 # As there is no native HTML math support, we provide alternatives
1319 # for the math-output: LaTeX and MathJax simply wrap the content,
1320 # HTML and MathML also convert the math_code.
1321 # HTML element:
1322 math_tags = { # format: (inline, block, [class arguments])
1323 'html': ('span', 'div', ['formula']),
1324 'latex': ('tt', 'pre', ['math']),
1325 'mathjax': ('span', 'div', ['math']),
1326 'mathml': ('', 'div', []),
1327 'problematic': ('span', 'pre', ['math', 'problematic']),
1328 }
1329
1330 def visit_math(self, node):
1331 # Also called from `visit_math_block()`:
1332 is_block = isinstance(node, nodes.math_block)
1333 format = self.math_output
1334 math_code = node.astext().translate(unichar2tex.uni2tex_table)
1335
1336 # preamble code and conversion
1337 if format == 'html':
1338 if self.math_options and not self.math_header:
1339 self.math_header = [
1340 self.stylesheet_call(utils.find_file_in_dirs(
1341 s, self.settings.stylesheet_dirs), adjust_path=True)
1342 for s in self.math_options.split(',')]
1343 math2html.DocumentParameters.displaymode = is_block
1344 # TODO: fix display mode in matrices and fractions
1345 math_code = wrap_math_code(math_code, is_block)
1346 math_code = math2html.math2html(math_code)
1347 elif format == 'latex':
1348 math_code = self.encode(math_code)
1349 elif format == 'mathjax':
1350 if not self.math_header:
1351 if self.math_options:
1352 self.mathjax_url = self.math_options
1353 else:
1354 self.document.reporter.warning(
1355 'No MathJax URL specified, using local fallback '
1356 '(see config.html).', base_node=node)
1357 # append MathJax configuration
1358 # (input LaTeX with AMS, output common HTML):
1359 if '?' not in self.mathjax_url:
1360 self.mathjax_url += '?config=TeX-AMS_CHTML'
1361 self.math_header = [self.mathjax_script % self.mathjax_url]
1362 if is_block:
1363 math_code = wrap_math_code(math_code, is_block)
1364 else:
1365 math_code = rf'\({math_code}\)'
1366 math_code = self.encode(math_code)
1367 elif format == 'mathml':
1368 if 'XHTML 1' in self.doctype:
1369 self.content_type = self.content_type_mathml
1370 if self.math_options:
1371 converter = getattr(tex2mathml_extern, self.math_options)
1372 else:
1373 converter = latex2mathml.tex2mathml
1374 try:
1375 math_code = converter(math_code, as_block=is_block)
1376 except (MathError, OSError) as err:
1377 details = getattr(err, 'details', [])
1378 self.messages.append(self.document.reporter.warning(
1379 err, *details, base_node=node))
1380 math_code = self.encode(node.astext())
1381 if self.settings.report_level <= 2:
1382 format = 'problematic'
1383 else:
1384 format = 'latex'
1385 if isinstance(err, OSError):
1386 # report missing converter only once
1387 self.math_output = format
1388
1389 # append to document body
1390 tag = self.math_tags[format][is_block]
1391 suffix = '\n' if is_block else ''
1392 if tag:
1393 self.body.append(self.starttag(node, tag, suffix=suffix,
1394 classes=self.math_tags[format][2]))
1395 self.body.extend([math_code, suffix])
1396 if tag:
1397 self.body.append(f'</{tag}>{suffix}')
1398 # Content already processed:
1399 raise nodes.SkipChildren
1400
1401 def depart_math(self, node) -> None:
1402 pass
1403
1404 def visit_math_block(self, node) -> None:
1405 self.visit_math(node)
1406
1407 def depart_math_block(self, node) -> None:
1408 self.report_messages(node)
1409
1410 # Meta tags: 'lang' attribute replaced by 'xml:lang' in XHTML 1.1
1411 # HTML5/polyglot recommends using both
1412 def visit_meta(self, node) -> None:
1413 self.meta.append(self.emptytag(node, 'meta',
1414 **node.non_default_attributes()))
1415
1416 def depart_meta(self, node) -> None:
1417 pass
1418
1419 def visit_option(self, node) -> None:
1420 self.body.append(self.starttag(node, 'span', '', CLASS='option'))
1421
1422 def depart_option(self, node) -> None:
1423 self.body.append('</span>')
1424 if isinstance(node.next_node(descend=False, siblings=True),
1425 nodes.option):
1426 self.body.append(', ')
1427
1428 def visit_option_argument(self, node) -> None:
1429 self.body.append(node.get('delimiter', ' '))
1430 self.body.append(self.starttag(node, 'var', ''))
1431
1432 def depart_option_argument(self, node) -> None:
1433 self.body.append('</var>')
1434
1435 def visit_option_group(self, node) -> None:
1436 self.body.append(self.starttag(node, 'dt', ''))
1437 self.body.append('<kbd>')
1438
1439 def depart_option_group(self, node) -> None:
1440 self.body.append('</kbd></dt>\n')
1441
1442 def visit_option_list(self, node) -> None:
1443 self.body.append(
1444 self.starttag(node, 'dl', CLASS='option-list'))
1445
1446 def depart_option_list(self, node) -> None:
1447 self.body.append('</dl>\n')
1448
1449 def visit_option_list_item(self, node) -> None:
1450 pass
1451
1452 def depart_option_list_item(self, node) -> None:
1453 pass
1454
1455 def visit_option_string(self, node) -> None:
1456 pass
1457
1458 def depart_option_string(self, node) -> None:
1459 pass
1460
1461 def visit_organization(self, node) -> None:
1462 self.visit_docinfo_item(node, 'organization')
1463
1464 def depart_organization(self, node) -> None:
1465 self.depart_docinfo_item()
1466
1467 # Do not omit <p> tags
1468 # --------------------
1469 #
1470 # The HTML4CSS1 writer does this to "produce
1471 # visually compact lists (less vertical whitespace)". This writer
1472 # relies on CSS rules for visual compactness.
1473 #
1474 # * In XHTML 1.1, e.g., a <blockquote> element may not contain
1475 # character data, so you cannot drop the <p> tags.
1476 # * Keeping simple paragraphs in the field_body enables a CSS
1477 # rule to start the field-body on a new line if the label is too long
1478 # * it makes the code simpler.
1479 #
1480 # TODO: omit paragraph tags in simple table cells?
1481
1482 def visit_paragraph(self, node) -> None:
1483 self.body.append(self.starttag(node, 'p', ''))
1484
1485 def depart_paragraph(self, node) -> None:
1486 self.body.append('</p>')
1487 if not (isinstance(node.parent, (nodes.list_item, nodes.entry))
1488 and (len(node.parent) == 1)):
1489 self.body.append('\n')
1490 self.report_messages(node)
1491
1492 def visit_problematic(self, node) -> None:
1493 if node.hasattr('refid'):
1494 self.body.append('<a href="#%s">' % node['refid'])
1495 self.context.append('</a>')
1496 else:
1497 self.context.append('')
1498 self.body.append(self.starttag(node, 'span', '', CLASS='problematic'))
1499
1500 def depart_problematic(self, node) -> None:
1501 self.body.append('</span>')
1502 self.body.append(self.context.pop())
1503
1504 def visit_raw(self, node):
1505 if 'html' in node.get('format', '').split():
1506 if isinstance(node.parent, nodes.TextElement):
1507 tagname = 'span'
1508 else:
1509 tagname = 'div'
1510 if node['classes']:
1511 self.body.append(self.starttag(node, tagname, suffix=''))
1512 self.body.append(node.astext())
1513 if node['classes']:
1514 self.body.append('</%s>' % tagname)
1515 # Keep non-HTML raw text out of output:
1516 raise nodes.SkipNode
1517
1518 def visit_reference(self, node) -> None:
1519 atts = {'classes': ['reference']}
1520 suffix = ''
1521 if 'refuri' in node:
1522 atts['href'] = node['refuri']
1523 if (self.settings.cloak_email_addresses
1524 and atts['href'].startswith('mailto:')):
1525 atts['href'] = self.cloak_mailto(atts['href'])
1526 self.in_mailto = True
1527 atts['classes'].append('external')
1528 else:
1529 assert 'refid' in node, \
1530 'References must have "refuri" or "refid" attribute.'
1531 atts['href'] = '#' + node['refid']
1532 atts['classes'].append('internal')
1533 if len(node) == 1 and isinstance(node[0], nodes.image):
1534 atts['classes'].append('image-reference')
1535 if not isinstance(node.parent, nodes.TextElement):
1536 suffix = '\n'
1537 self.body.append(self.starttag(node, 'a', suffix, **atts))
1538
1539 def depart_reference(self, node) -> None:
1540 self.body.append('</a>')
1541 if not isinstance(node.parent, nodes.TextElement):
1542 self.body.append('\n')
1543 self.in_mailto = False
1544
1545 def visit_revision(self, node) -> None:
1546 self.visit_docinfo_item(node, 'revision', meta=False)
1547
1548 def depart_revision(self, node) -> None:
1549 self.depart_docinfo_item()
1550
1551 def visit_row(self, node) -> None:
1552 self.body.append(self.starttag(node, 'tr', ''))
1553 node.column = 0
1554
1555 def depart_row(self, node) -> None:
1556 self.body.append('</tr>\n')
1557
1558 def visit_rubric(self, node) -> None:
1559 self.body.append(self.starttag(node, 'p', '', CLASS='rubric'))
1560
1561 def depart_rubric(self, node) -> None:
1562 self.body.append('</p>\n')
1563
1564 def visit_section(self, node) -> None:
1565 self.section_level += 1
1566 self.body.append(
1567 self.starttag(node, 'div', CLASS='section'))
1568
1569 def depart_section(self, node) -> None:
1570 self.section_level -= 1
1571 self.body.append('</div>\n')
1572
1573 # TODO: use the new HTML5 element <aside>
1574 def visit_sidebar(self, node) -> None:
1575 self.body.append(
1576 self.starttag(node, 'div', CLASS='sidebar'))
1577 self.in_sidebar = True
1578
1579 def depart_sidebar(self, node) -> None:
1580 self.body.append('</div>\n')
1581 self.in_sidebar = False
1582
1583 def visit_status(self, node) -> None:
1584 self.visit_docinfo_item(node, 'status', meta=False)
1585
1586 def depart_status(self, node) -> None:
1587 self.depart_docinfo_item()
1588
1589 def visit_strong(self, node) -> None:
1590 self.body.append(self.starttag(node, 'strong', ''))
1591
1592 def depart_strong(self, node) -> None:
1593 self.body.append('</strong>')
1594
1595 def visit_subscript(self, node) -> None:
1596 self.body.append(self.starttag(node, 'sub', ''))
1597
1598 def depart_subscript(self, node) -> None:
1599 self.body.append('</sub>')
1600
1601 def visit_substitution_definition(self, node):
1602 """Internal only."""
1603 raise nodes.SkipNode
1604
1605 def visit_substitution_reference(self, node) -> None:
1606 self.unimplemented_visit(node)
1607
1608 # h1–h6 elements must not be used to markup subheadings, subtitles,
1609 # alternative titles and taglines unless intended to be the heading for a
1610 # new section or subsection.
1611 # -- http://www.w3.org/TR/html51/sections.html#headings-and-sections
1612 def visit_subtitle(self, node) -> None:
1613 if isinstance(node.parent, nodes.sidebar):
1614 classes = ['sidebar-subtitle']
1615 elif isinstance(node.parent, nodes.document):
1616 classes = ['subtitle']
1617 self.in_document_title = len(self.body) + 1
1618 elif isinstance(node.parent, nodes.section):
1619 classes = ['section-subtitle']
1620 self.body.append(self.starttag(node, 'p', '', classes=classes))
1621
1622 def depart_subtitle(self, node) -> None:
1623 self.body.append('</p>\n')
1624 if isinstance(node.parent, nodes.document):
1625 self.subtitle = self.body[self.in_document_title:-1]
1626 self.in_document_title = 0
1627 self.body_pre_docinfo.extend(self.body)
1628 self.html_subtitle.extend(self.body)
1629 del self.body[:]
1630
1631 def visit_superscript(self, node) -> None:
1632 self.body.append(self.starttag(node, 'sup', ''))
1633
1634 def depart_superscript(self, node) -> None:
1635 self.body.append('</sup>')
1636
1637 def visit_system_message(self, node) -> None:
1638 self.body.append(self.starttag(node, 'aside', CLASS='system-message'))
1639 self.body.append('<p class="system-message-title">')
1640 backref_text = ''
1641 if len(node['backrefs']):
1642 backrefs = node['backrefs']
1643 if len(backrefs) == 1:
1644 backref_text = ('; <em><a href="#%s">backlink</a></em>'
1645 % backrefs[0])
1646 else:
1647 i = 1
1648 backlinks = []
1649 for backref in backrefs:
1650 backlinks.append('<a href="#%s">%s</a>' % (backref, i))
1651 i += 1
1652 backref_text = ('; <em>backlinks: %s</em>'
1653 % ', '.join(backlinks))
1654 if node.hasattr('line'):
1655 line = ', line %s' % node['line']
1656 else:
1657 line = ''
1658 self.body.append('System Message: %s/%s '
1659 '(<span class="docutils literal">%s</span>%s)%s</p>\n'
1660 % (node['type'], node['level'],
1661 self.encode(node['source']), line, backref_text))
1662
1663 def depart_system_message(self, node) -> None:
1664 self.body.append('</aside>\n')
1665
1666 def visit_table(self, node) -> None:
1667 atts = {'classes': self.settings.table_style.replace(',', ' ').split()}
1668 if 'align' in node:
1669 atts['classes'].append('align-%s' % node['align'])
1670 if 'width' in node:
1671 width = node['width']
1672 if width[-1:] in '0123456789.': # unitless value
1673 width += 'px' # add default length unit
1674 atts['style'] = f'width: {width};'
1675 tag = self.starttag(node, 'table', **atts)
1676 self.body.append(tag)
1677
1678 def depart_table(self, node) -> None:
1679 self.body.append('</table>\n')
1680 self.report_messages(node)
1681
1682 def visit_target(self, node) -> None:
1683 if ('refuri' not in node
1684 and 'refid' not in node
1685 and 'refname' not in node):
1686 self.body.append(self.starttag(node, 'span', '', CLASS='target'))
1687 self.context.append('</span>')
1688 else:
1689 self.context.append('')
1690
1691 def depart_target(self, node) -> None:
1692 self.body.append(self.context.pop())
1693
1694 # no hard-coded vertical alignment in table body
1695 def visit_tbody(self, node) -> None:
1696 self.body.append(self.starttag(node, 'tbody'))
1697
1698 def depart_tbody(self, node) -> None:
1699 self.body.append('</tbody>\n')
1700
1701 def visit_term(self, node) -> None:
1702 if 'details' in node.parent.parent['classes']:
1703 self.body.append(self.starttag(node, 'summary', suffix=''))
1704 else:
1705 # The parent node (definition_list_item) is omitted in HTML.
1706 self.body.append(self.starttag(node, 'dt', suffix='',
1707 classes=node.parent['classes'],
1708 ids=node.parent['ids']))
1709
1710 def depart_term(self, node) -> None:
1711 # Nest (optional) classifier(s) in the <dt> element
1712 if node.next_node(nodes.classifier, descend=False, siblings=True):
1713 return # skip (depart_classifier() calls this function again)
1714 if 'details' in node.parent.parent['classes']:
1715 self.body.append('</summary>\n')
1716 else:
1717 self.body.append('</dt>\n')
1718
1719 def visit_tgroup(self, node) -> None:
1720 self.colspecs = []
1721 node.stubs = []
1722
1723 def depart_tgroup(self, node) -> None:
1724 pass
1725
1726 def visit_thead(self, node) -> None:
1727 self.body.append(self.starttag(node, 'thead'))
1728
1729 def depart_thead(self, node) -> None:
1730 self.body.append('</thead>\n')
1731
1732 def section_title_tags(self, node):
1733 atts = {}
1734 h_level = self.section_level + self.initial_header_level - 1
1735 # Only 6 heading levels have dedicated HTML tags.
1736 tagname = 'h%i' % min(h_level, 6)
1737 if h_level > 6:
1738 atts['aria-level'] = h_level
1739 start_tag = self.starttag(node, tagname, '', **atts)
1740 if node.hasattr('refid'):
1741 atts = {}
1742 atts['class'] = 'toc-backref'
1743 atts['role'] = 'doc-backlink' # HTML5 only
1744 atts['href'] = '#' + node['refid']
1745 start_tag += self.starttag(nodes.reference(), 'a', '', **atts)
1746 close_tag = '</a></%s>\n' % tagname
1747 else:
1748 close_tag = '</%s>\n' % tagname
1749 return start_tag, close_tag
1750
1751 def visit_title(self, node) -> None:
1752 close_tag = '</p>\n'
1753 if isinstance(node.parent, nodes.topic):
1754 # TODO: use role="heading" or <h1>? (HTML5 only)
1755 self.body.append(
1756 self.starttag(node, 'p', '', CLASS='topic-title'))
1757 if (self.settings.toc_backlinks
1758 and 'contents' in node.parent['classes']):
1759 self.body.append('<a class="reference internal" href="#top">')
1760 close_tag = '</a></p>\n'
1761 elif isinstance(node.parent, nodes.sidebar):
1762 # TODO: use role="heading" or <h1>? (HTML5 only)
1763 self.body.append(
1764 self.starttag(node, 'p', '', CLASS='sidebar-title'))
1765 elif isinstance(node.parent, nodes.Admonition):
1766 self.body.append(
1767 self.starttag(node, 'p', '', CLASS='admonition-title'))
1768 elif isinstance(node.parent, nodes.table):
1769 self.body.append(self.starttag(node, 'caption', ''))
1770 close_tag = '</caption>\n'
1771 elif isinstance(node.parent, nodes.document):
1772 self.body.append(self.starttag(node, 'h1', '', CLASS='title'))
1773 close_tag = '</h1>\n'
1774 self.in_document_title = len(self.body)
1775 else:
1776 assert isinstance(node.parent, nodes.section)
1777 # Get correct heading and evt. backlink tags
1778 start_tag, close_tag = self.section_title_tags(node)
1779 self.body.append(start_tag)
1780 self.context.append(close_tag)
1781
1782 def depart_title(self, node) -> None:
1783 self.body.append(self.context.pop())
1784 if self.in_document_title:
1785 self.title = self.body[self.in_document_title:-1]
1786 self.in_document_title = 0
1787 self.body_pre_docinfo.extend(self.body)
1788 self.html_title.extend(self.body)
1789 del self.body[:]
1790
1791 def visit_title_reference(self, node) -> None:
1792 self.body.append(self.starttag(node, 'cite', ''))
1793
1794 def depart_title_reference(self, node) -> None:
1795 self.body.append('</cite>')
1796
1797 def visit_topic(self, node) -> None:
1798 self.body.append(self.starttag(node, 'div', CLASS='topic'))
1799
1800 def depart_topic(self, node) -> None:
1801 self.body.append('</div>\n')
1802
1803 def visit_transition(self, node) -> None:
1804 self.body.append(self.emptytag(node, 'hr', CLASS='docutils'))
1805
1806 def depart_transition(self, node) -> None:
1807 pass
1808
1809 def visit_version(self, node) -> None:
1810 self.visit_docinfo_item(node, 'version', meta=False)
1811
1812 def depart_version(self, node) -> None:
1813 self.depart_docinfo_item()
1814
1815 def unimplemented_visit(self, node):
1816 raise NotImplementedError('visiting unimplemented node type: %s'
1817 % node.__class__.__name__)
1818
1819
1820 class SimpleListChecker(nodes.GenericNodeVisitor):
1821
1822 """
1823 Raise `nodes.NodeFound` if non-simple list item is encountered.
1824
1825 Here "simple" means a list item containing nothing other than a single
1826 paragraph, a simple list, or a paragraph followed by a simple list.
1827
1828 This version also checks for simple field lists and docinfo.
1829 """
1830
1831 def default_visit(self, node):
1832 raise nodes.NodeFound
1833
1834 def default_departure(self, node):
1835 pass
1836
1837 def visit_list_item(self, node):
1838 children = [child for child in node.children
1839 if not isinstance(child, nodes.Invisible)]
1840 if (children and isinstance(children[0], nodes.paragraph)
1841 and (isinstance(children[-1], nodes.bullet_list)
1842 or isinstance(children[-1], nodes.enumerated_list)
1843 or isinstance(children[-1], nodes.field_list))):
1844 children.pop()
1845 if len(children) <= 1:
1846 return
1847 else:
1848 raise nodes.NodeFound
1849
1850 def pass_node(self, node) -> None:
1851 pass
1852
1853 def ignore_node(self, node):
1854 # ignore nodes that are never complex (can contain only inline nodes)
1855 raise nodes.SkipNode
1856
1857 # Paragraphs and text
1858 visit_Text = ignore_node
1859 visit_paragraph = ignore_node
1860
1861 # Lists
1862 visit_bullet_list = pass_node
1863 visit_enumerated_list = pass_node
1864 visit_docinfo = pass_node
1865
1866 # Docinfo nodes:
1867 visit_author = ignore_node
1868 visit_authors = visit_list_item
1869 visit_address = visit_list_item
1870 visit_contact = pass_node
1871 visit_copyright = ignore_node
1872 visit_date = ignore_node
1873 visit_organization = ignore_node
1874 visit_status = ignore_node
1875 visit_version = visit_list_item
1876
1877 # Definition list:
1878 visit_definition_list = pass_node
1879 visit_definition_list_item = pass_node
1880 visit_term = ignore_node
1881 visit_classifier = pass_node
1882 visit_definition = visit_list_item
1883
1884 # Field list:
1885 visit_field_list = pass_node
1886 visit_field = pass_node
1887 # the field body corresponds to a list item
1888 visit_field_body = visit_list_item
1889 visit_field_name = ignore_node
1890
1891 # Invisible nodes should be ignored.
1892 visit_comment = ignore_node
1893 visit_substitution_definition = ignore_node
1894 visit_target = ignore_node
1895 visit_pending = ignore_node