| 1 |
# $Id: __init__.py 10270 2025-12-03 11:38:54Z milde $ |
| 2 |
# Author: David Goodger |
| 3 |
# Maintainer: [email protected] |
| 4 |
# Copyright: This module has been placed in the public domain. |
| 5 |
|
| 6 |
""" |
| 7 |
Simple HyperText Markup Language document tree Writer. |
| 8 |
|
| 9 |
The output conforms to the XHTML version 1.0 Transitional DTD |
| 10 |
(*almost* strict). The output contains a minimum of formatting |
| 11 |
information. The cascading style sheet "html4css1.css" is required |
| 12 |
for proper viewing with a modern graphical browser. |
| 13 |
""" |
| 14 |
|
| 15 |
from __future__ import annotations |
| 16 |
|
| 17 |
__docformat__ = 'reStructuredText' |
| 18 |
|
| 19 |
import os.path |
| 20 |
import re |
| 21 |
|
| 22 |
from docutils import frontend, nodes, writers |
| 23 |
from docutils.writers import _html_base |
| 24 |
from docutils.writers._html_base import PIL |
| 25 |
|
| 26 |
|
| 27 |
class Writer(writers._html_base.Writer): |
| 28 |
|
| 29 |
supported = ('html', 'html4', 'html4css1', 'xhtml', 'xhtml10') |
| 30 |
"""Formats this writer supports.""" |
| 31 |
|
| 32 |
default_stylesheets = ['html4css1.css'] |
| 33 |
default_stylesheet_dirs = ['.', |
| 34 |
os.path.abspath(os.path.dirname(__file__)), |
| 35 |
os.path.abspath(os.path.join( |
| 36 |
os.path.dirname(os.path.dirname(__file__)), |
| 37 |
'html5_polyglot')) # for math.css |
| 38 |
] |
| 39 |
default_template = os.path.join( |
| 40 |
os.path.dirname(os.path.abspath(__file__)), 'template.txt') |
| 41 |
|
| 42 |
# use a copy of the parent spec with some modifications |
| 43 |
settings_spec = frontend.filter_settings_spec( |
| 44 |
writers._html_base.Writer.settings_spec, |
| 45 |
template=( |
| 46 |
'Template file. (UTF-8 encoded, default: "%s")' % default_template, |
| 47 |
['--template'], |
| 48 |
{'default': default_template, 'metavar': '<file>'}), |
| 49 |
stylesheet_path=( |
| 50 |
'Comma separated list of stylesheet paths. ' |
| 51 |
'Relative paths are expanded if a matching file is found in ' |
| 52 |
'the --stylesheet-dirs. With --link-stylesheet, ' |
| 53 |
'the path is rewritten relative to the output HTML file. ' |
| 54 |
'(default: "%s")' % ','.join(default_stylesheets), |
| 55 |
['--stylesheet-path'], |
| 56 |
{'metavar': '<file[,file,...]>', 'overrides': 'stylesheet', |
| 57 |
'validator': frontend.validate_comma_separated_list, |
| 58 |
'default': default_stylesheets}), |
| 59 |
stylesheet_dirs=( |
| 60 |
'Comma-separated list of directories where stylesheets are found. ' |
| 61 |
'Used by --stylesheet-path when expanding relative path ' |
| 62 |
'arguments. (default: "%s")' % ','.join(default_stylesheet_dirs), |
| 63 |
['--stylesheet-dirs'], |
| 64 |
{'metavar': '<dir[,dir,...]>', |
| 65 |
'validator': frontend.validate_comma_separated_list, |
| 66 |
'default': default_stylesheet_dirs}), |
| 67 |
initial_header_level=( |
| 68 |
'Specify the initial header level. Does not affect document ' |
| 69 |
'title & subtitle (see --no-doc-title). (default: 1 for "<h1>")', |
| 70 |
['--initial-header-level'], |
| 71 |
{'choices': '1 2 3 4 5 6 auto'.split(), 'default': '1', |
| 72 |
'metavar': '<level>'}), |
| 73 |
math_output=( |
| 74 |
'Math output format (one of "MathML", "HTML", "MathJax", or ' |
| 75 |
'"LaTeX") and option(s). (default: "HTML math.css")', |
| 76 |
['--math-output'], |
| 77 |
{'metavar': '<format [option(s)]>', 'default': 'HTML math.css', |
| 78 |
'validator': frontend.validate_math_output}), |
| 79 |
xml_declaration=( |
| 80 |
'Prepend an XML declaration (default). ', |
| 81 |
['--xml-declaration'], |
| 82 |
{'default': True, 'action': 'store_true', |
| 83 |
'validator': frontend.validate_boolean}), |
| 84 |
) |
| 85 |
settings_spec = settings_spec + ( |
| 86 |
'HTML4 Writer Options', |
| 87 |
'', |
| 88 |
(('Specify the maximum width (in characters) for one-column field ' |
| 89 |
'names. Longer field names will span an entire row of the table ' |
| 90 |
'used to render the field list. Default is 14 characters. ' |
| 91 |
'Use 0 for "no limit".', |
| 92 |
['--field-name-limit'], |
| 93 |
{'default': 14, 'metavar': '<level>', |
| 94 |
'validator': frontend.validate_nonnegative_int}), |
| 95 |
('Specify the maximum width (in characters) for options in option ' |
| 96 |
'lists. Longer options will span an entire row of the table used ' |
| 97 |
'to render the option list. Default is 14 characters. ' |
| 98 |
'Use 0 for "no limit".', |
| 99 |
['--option-limit'], |
| 100 |
{'default': 14, 'metavar': '<level>', |
| 101 |
'validator': frontend.validate_nonnegative_int}), |
| 102 |
) |
| 103 |
) |
| 104 |
|
| 105 |
config_section = 'html4css1 writer' |
| 106 |
|
| 107 |
def __init__(self) -> None: |
| 108 |
self.parts = {} |
| 109 |
self.translator_class = HTMLTranslator |
| 110 |
|
| 111 |
|
| 112 |
class HTMLTranslator(writers._html_base.HTMLTranslator): |
| 113 |
""" |
| 114 |
The html4css1 writer has been optimized to produce visually compact |
| 115 |
lists (less vertical whitespace). HTML's mixed content models |
| 116 |
allow list items to contain "<li><p>body elements</p></li>" or |
| 117 |
"<li>just text</li>" or even "<li>text<p>and body |
| 118 |
elements</p>combined</li>", each with different effects. It would |
| 119 |
be best to stick with strict body elements in list items, but they |
| 120 |
affect vertical spacing in older browsers (although they really |
| 121 |
shouldn't). |
| 122 |
The html5_polyglot writer solves this using CSS2. |
| 123 |
|
| 124 |
Here is an outline of the optimization: |
| 125 |
|
| 126 |
- Check for and omit <p> tags in "simple" lists: list items |
| 127 |
contain either a single paragraph, a nested simple list, or a |
| 128 |
paragraph followed by a nested simple list. This means that |
| 129 |
this list can be compact: |
| 130 |
|
| 131 |
- Item 1. |
| 132 |
- Item 2. |
| 133 |
|
| 134 |
But this list cannot be compact: |
| 135 |
|
| 136 |
- Item 1. |
| 137 |
|
| 138 |
This second paragraph forces space between list items. |
| 139 |
|
| 140 |
- Item 2. |
| 141 |
|
| 142 |
- In non-list contexts, omit <p> tags on a paragraph if that |
| 143 |
paragraph is the only child of its parent (footnotes & citations |
| 144 |
are allowed a label first). |
| 145 |
|
| 146 |
- Regardless of the above, in definitions, table cells, field bodies, |
| 147 |
option descriptions, and list items, mark the first child with |
| 148 |
'class="first"' and the last child with 'class="last"'. The stylesheet |
| 149 |
sets the margins (top & bottom respectively) to 0 for these elements. |
| 150 |
|
| 151 |
The ``no_compact_lists`` setting (``--no-compact-lists`` command-line |
| 152 |
option) disables list whitespace optimization. |
| 153 |
""" |
| 154 |
|
| 155 |
# The following definitions are required for display in browsers limited |
| 156 |
# to CSS1 or backwards compatible behaviour of the writer: |
| 157 |
|
| 158 |
doctype = ( |
| 159 |
'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"' |
| 160 |
' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n') |
| 161 |
|
| 162 |
content_type = ('<meta http-equiv="Content-Type"' |
| 163 |
' content="text/html; charset=%s" />\n') |
| 164 |
content_type_mathml = ('<meta http-equiv="Content-Type"' |
| 165 |
' content="application/xhtml+xml; charset=%s" />\n') |
| 166 |
|
| 167 |
# encode also non-breaking space |
| 168 |
special_characters = _html_base.HTMLTranslator.special_characters.copy() |
| 169 |
special_characters[0xa0] = ' ' |
| 170 |
|
| 171 |
# use character reference for dash (not valid in HTML5) |
| 172 |
attribution_formats = {'dash': ('—', ''), |
| 173 |
'parentheses': ('(', ')'), |
| 174 |
'parens': ('(', ')'), |
| 175 |
'none': ('', '')} |
| 176 |
|
| 177 |
# ersatz for first/last pseudo-classes missing in CSS1 |
| 178 |
def set_first_last(self, node) -> None: |
| 179 |
self.set_class_on_child(node, 'first', 0) |
| 180 |
self.set_class_on_child(node, 'last', -1) |
| 181 |
|
| 182 |
# add newline after opening tag |
| 183 |
def visit_address(self, node) -> None: |
| 184 |
self.visit_docinfo_item(node, 'address', meta=False) |
| 185 |
self.body.append(self.starttag(node, 'pre', CLASS='address')) |
| 186 |
|
| 187 |
def depart_address(self, node) -> None: |
| 188 |
self.body.append('\n</pre>\n') |
| 189 |
self.depart_docinfo_item() |
| 190 |
|
| 191 |
# ersatz for first/last pseudo-classes |
| 192 |
def visit_admonition(self, node) -> None: |
| 193 |
node['classes'].insert(0, 'admonition') |
| 194 |
self.body.append(self.starttag(node, 'div')) |
| 195 |
self.set_first_last(node) |
| 196 |
|
| 197 |
def depart_admonition(self, node=None) -> None: |
| 198 |
self.body.append('</div>\n') |
| 199 |
|
| 200 |
# author, authors: use <br> instead of paragraphs |
| 201 |
def visit_author(self, node) -> None: |
| 202 |
if isinstance(node.parent, nodes.authors): |
| 203 |
if self.author_in_authors: |
| 204 |
self.body.append('\n<br />') |
| 205 |
else: |
| 206 |
self.visit_docinfo_item(node, 'author') |
| 207 |
|
| 208 |
def depart_author(self, node) -> None: |
| 209 |
if isinstance(node.parent, nodes.authors): |
| 210 |
self.author_in_authors = True |
| 211 |
else: |
| 212 |
self.depart_docinfo_item() |
| 213 |
|
| 214 |
def visit_authors(self, node) -> None: |
| 215 |
self.visit_docinfo_item(node, 'authors') |
| 216 |
self.author_in_authors = False # initialize |
| 217 |
|
| 218 |
def depart_authors(self, node) -> None: |
| 219 |
self.depart_docinfo_item() |
| 220 |
|
| 221 |
# use "width" argument instead of "style: 'width'": |
| 222 |
def visit_colspec(self, node) -> None: |
| 223 |
self.colspecs.append(node) |
| 224 |
# "stubs" list is an attribute of the tgroup element: |
| 225 |
node.parent.stubs.append(node.attributes.get('stub')) |
| 226 |
|
| 227 |
def depart_colspec(self, node) -> None: |
| 228 |
# write out <colgroup> when all colspecs are processed |
| 229 |
if isinstance(node.next_node(descend=False, siblings=True), |
| 230 |
nodes.colspec): |
| 231 |
return |
| 232 |
if ('colwidths-auto' in node.parent.parent['classes'] |
| 233 |
or ('colwidths-auto' in self.settings.table_style |
| 234 |
and 'colwidths-given' not in node.parent.parent['classes'])): |
| 235 |
return |
| 236 |
total_width = sum(node.propwidth() for node in self.colspecs) |
| 237 |
self.body.append(self.starttag(node, 'colgroup')) |
| 238 |
for node in self.colspecs: |
| 239 |
colwidth = node.propwidth() * 100.0 / total_width + 0.5 |
| 240 |
self.body.append(self.emptytag(node, 'col', |
| 241 |
width='%i%%' % colwidth)) |
| 242 |
self.body.append('</colgroup>\n') |
| 243 |
|
| 244 |
# Compact lists: |
| 245 |
# exclude definition lists and field lists (non-compact by default) |
| 246 |
|
| 247 |
def is_compactable(self, node): |
| 248 |
return ('compact' in node['classes'] |
| 249 |
or (self.settings.compact_lists |
| 250 |
and 'open' not in node['classes'] |
| 251 |
and (self.compact_simple |
| 252 |
or 'contents' in node.parent['classes'] |
| 253 |
# TODO: self.in_contents |
| 254 |
or self.check_simple_list(node)))) |
| 255 |
|
| 256 |
# citations: Use table for bibliographic references. |
| 257 |
def visit_citation(self, node) -> None: |
| 258 |
self.body.append(self.starttag(node, 'table', |
| 259 |
CLASS='docutils citation', |
| 260 |
frame="void", rules="none")) |
| 261 |
self.body.append('<colgroup><col class="label" /><col /></colgroup>\n' |
| 262 |
'<tbody valign="top">\n' |
| 263 |
'<tr>') |
| 264 |
self.footnote_backrefs(node) |
| 265 |
|
| 266 |
def depart_citation(self, node) -> None: |
| 267 |
self.body.append('</td></tr>\n' |
| 268 |
'</tbody>\n</table>\n') |
| 269 |
|
| 270 |
def visit_citation_reference(self, node) -> None: |
| 271 |
href = '#' |
| 272 |
if 'refid' in node: |
| 273 |
href += node['refid'] |
| 274 |
elif 'refname' in node: |
| 275 |
href += self.document.nameids[node['refname']] |
| 276 |
self.body.append(self.starttag(node, 'a', suffix='[', href=href, |
| 277 |
classes=['citation-reference'])) |
| 278 |
|
| 279 |
def depart_citation_reference(self, node) -> None: |
| 280 |
self.body.append(']</a>') |
| 281 |
|
| 282 |
# insert classifier-delimiter (not required with CSS2) |
| 283 |
def visit_classifier(self, node) -> None: |
| 284 |
self.body.append(' <span class="classifier-delimiter">:</span> ') |
| 285 |
self.body.append(self.starttag(node, 'span', '', CLASS='classifier')) |
| 286 |
|
| 287 |
def depart_classifier(self, node) -> None: |
| 288 |
self.body.append('</span>') |
| 289 |
self.depart_term(node) # close the <dt> after last classifier |
| 290 |
|
| 291 |
# ersatz for first/last pseudo-classes |
| 292 |
def visit_compound(self, node) -> None: |
| 293 |
self.body.append(self.starttag(node, 'div', CLASS='compound')) |
| 294 |
if len(node) > 1: |
| 295 |
node[0]['classes'].append('compound-first') |
| 296 |
node[-1]['classes'].append('compound-last') |
| 297 |
for child in node[1:-1]: |
| 298 |
child['classes'].append('compound-middle') |
| 299 |
|
| 300 |
def depart_compound(self, node) -> None: |
| 301 |
self.body.append('</div>\n') |
| 302 |
|
| 303 |
# ersatz for first/last pseudo-classes, no special handling of "details" |
| 304 |
def visit_definition(self, node) -> None: |
| 305 |
self.body.append(self.starttag(node, 'dd', '')) |
| 306 |
self.set_first_last(node) |
| 307 |
|
| 308 |
def depart_definition(self, node) -> None: |
| 309 |
self.body.append('</dd>\n') |
| 310 |
|
| 311 |
# don't add "simple" class value, no special handling of "details" |
| 312 |
def visit_definition_list(self, node) -> None: |
| 313 |
self.body.append(self.starttag(node, 'dl', CLASS='docutils')) |
| 314 |
|
| 315 |
def depart_definition_list(self, node) -> None: |
| 316 |
self.body.append('</dl>\n') |
| 317 |
|
| 318 |
# no special handling of "details" |
| 319 |
def visit_definition_list_item(self, node) -> None: |
| 320 |
pass |
| 321 |
|
| 322 |
def depart_definition_list_item(self, node) -> None: |
| 323 |
pass |
| 324 |
|
| 325 |
# use a table for description lists |
| 326 |
def visit_description(self, node) -> None: |
| 327 |
self.body.append(self.starttag(node, 'td', '')) |
| 328 |
self.set_first_last(node) |
| 329 |
|
| 330 |
def depart_description(self, node) -> None: |
| 331 |
self.body.append('</td>') |
| 332 |
|
| 333 |
# use table for docinfo |
| 334 |
def visit_docinfo(self, node) -> None: |
| 335 |
self.context.append(len(self.body)) |
| 336 |
self.body.append(self.starttag(node, 'table', |
| 337 |
CLASS='docinfo', |
| 338 |
frame="void", rules="none")) |
| 339 |
self.body.append('<col class="docinfo-name" />\n' |
| 340 |
'<col class="docinfo-content" />\n' |
| 341 |
'<tbody valign="top">\n') |
| 342 |
self.in_docinfo = True |
| 343 |
|
| 344 |
def depart_docinfo(self, node) -> None: |
| 345 |
self.body.append('</tbody>\n</table>\n') |
| 346 |
self.in_docinfo = False |
| 347 |
start = self.context.pop() |
| 348 |
self.docinfo = self.body[start:] |
| 349 |
self.body = [] |
| 350 |
|
| 351 |
def visit_docinfo_item(self, node, name, meta=True) -> None: |
| 352 |
if meta: |
| 353 |
meta_tag = '<meta name="%s" content="%s" />\n' \ |
| 354 |
% (name, self.attval(node.astext())) |
| 355 |
self.meta.append(meta_tag) |
| 356 |
self.body.append(self.starttag(node, 'tr', '')) |
| 357 |
self.body.append('<th class="docinfo-name">%s:</th>\n<td>' |
| 358 |
% self.language.labels[name]) |
| 359 |
if len(node): |
| 360 |
if isinstance(node[0], nodes.Element): |
| 361 |
node[0]['classes'].append('first') |
| 362 |
if isinstance(node[-1], nodes.Element): |
| 363 |
node[-1]['classes'].append('last') |
| 364 |
|
| 365 |
def depart_docinfo_item(self) -> None: |
| 366 |
self.body.append('</td></tr>\n') |
| 367 |
|
| 368 |
# add newline after opening tag |
| 369 |
def visit_doctest_block(self, node) -> None: |
| 370 |
self.body.append(self.starttag(node, 'pre', CLASS='doctest-block')) |
| 371 |
|
| 372 |
def depart_doctest_block(self, node) -> None: |
| 373 |
self.body.append('\n</pre>\n') |
| 374 |
|
| 375 |
# insert an NBSP into empty cells, ersatz for first/last |
| 376 |
def visit_entry(self, node) -> None: |
| 377 |
writers._html_base.HTMLTranslator.visit_entry(self, node) |
| 378 |
if len(node) == 0: # empty cell |
| 379 |
self.body.append(' ') |
| 380 |
self.set_first_last(node) |
| 381 |
|
| 382 |
def depart_entry(self, node) -> None: |
| 383 |
self.body.append(self.context.pop()) |
| 384 |
|
| 385 |
# ersatz for first/last pseudo-classes |
| 386 |
def visit_enumerated_list(self, node) -> None: |
| 387 |
""" |
| 388 |
The 'start' attribute does not conform to HTML 4.01's strict.dtd, but |
| 389 |
cannot be emulated in CSS1 (HTML 5 reincludes it). |
| 390 |
""" |
| 391 |
atts = {} |
| 392 |
if 'start' in node: |
| 393 |
atts['start'] = node['start'] |
| 394 |
if 'enumtype' in node: |
| 395 |
atts['class'] = node['enumtype'] |
| 396 |
# @@@ To do: prefix, suffix. How? Change prefix/suffix to a |
| 397 |
# single "format" attribute? Use CSS2? |
| 398 |
old_compact_simple = self.compact_simple |
| 399 |
self.context.append((self.compact_simple, self.compact_p)) |
| 400 |
self.compact_p = None |
| 401 |
self.compact_simple = self.is_compactable(node) |
| 402 |
if self.compact_simple and not old_compact_simple: |
| 403 |
atts['class'] = (atts.get('class', '') + ' simple').strip() |
| 404 |
self.body.append(self.starttag(node, 'ol', **atts)) |
| 405 |
|
| 406 |
def depart_enumerated_list(self, node) -> None: |
| 407 |
self.compact_simple, self.compact_p = self.context.pop() |
| 408 |
self.body.append('</ol>\n') |
| 409 |
|
| 410 |
# use table for field-list: |
| 411 |
def visit_field(self, node) -> None: |
| 412 |
self.body.append(self.starttag(node, 'tr', '', CLASS='field')) |
| 413 |
|
| 414 |
def depart_field(self, node) -> None: |
| 415 |
self.body.append('</tr>\n') |
| 416 |
|
| 417 |
def visit_field_body(self, node) -> None: |
| 418 |
self.body.append(self.starttag(node, 'td', '', CLASS='field-body')) |
| 419 |
self.set_class_on_child(node, 'first', 0) |
| 420 |
field = node.parent |
| 421 |
if (self.compact_field_list |
| 422 |
or isinstance(field.parent, nodes.docinfo) |
| 423 |
or field.parent.index(field) == len(field.parent) - 1): |
| 424 |
# If we are in a compact list, the docinfo, or if this is |
| 425 |
# the last field of the field list, do not add vertical |
| 426 |
# space after last element. |
| 427 |
self.set_class_on_child(node, 'last', -1) |
| 428 |
|
| 429 |
def depart_field_body(self, node) -> None: |
| 430 |
self.body.append('</td>\n') |
| 431 |
|
| 432 |
def visit_field_list(self, node) -> None: |
| 433 |
self.context.append((self.compact_field_list, self.compact_p)) |
| 434 |
self.compact_p = None |
| 435 |
if 'compact' in node['classes']: |
| 436 |
self.compact_field_list = True |
| 437 |
elif (self.settings.compact_field_lists |
| 438 |
and 'open' not in node['classes']): |
| 439 |
self.compact_field_list = True |
| 440 |
if self.compact_field_list: |
| 441 |
for field in node: |
| 442 |
field_body = field[-1] |
| 443 |
assert isinstance(field_body, nodes.field_body) |
| 444 |
children = [n for n in field_body |
| 445 |
if not isinstance(n, nodes.Invisible)] |
| 446 |
if not (len(children) == 0 |
| 447 |
or len(children) == 1 |
| 448 |
and isinstance(children[0], |
| 449 |
(nodes.paragraph, nodes.line_block))): |
| 450 |
self.compact_field_list = False |
| 451 |
break |
| 452 |
self.body.append(self.starttag(node, 'table', frame='void', |
| 453 |
rules='none', |
| 454 |
CLASS='docutils field-list')) |
| 455 |
self.body.append('<col class="field-name" />\n' |
| 456 |
'<col class="field-body" />\n' |
| 457 |
'<tbody valign="top">\n') |
| 458 |
|
| 459 |
def depart_field_list(self, node) -> None: |
| 460 |
self.body.append('</tbody>\n</table>\n') |
| 461 |
self.compact_field_list, self.compact_p = self.context.pop() |
| 462 |
|
| 463 |
def visit_field_name(self, node) -> None: |
| 464 |
atts = {} |
| 465 |
if self.in_docinfo: |
| 466 |
atts['class'] = 'docinfo-name' |
| 467 |
else: |
| 468 |
atts['class'] = 'field-name' |
| 469 |
if (self.settings.field_name_limit |
| 470 |
and len(node.astext()) > self.settings.field_name_limit): |
| 471 |
atts['colspan'] = 2 |
| 472 |
self.context.append('</tr>\n' |
| 473 |
+ self.starttag(node.parent, 'tr', '', |
| 474 |
CLASS='field') |
| 475 |
+ '<td> </td>') |
| 476 |
else: |
| 477 |
self.context.append('') |
| 478 |
self.body.append(self.starttag(node, 'th', '', **atts)) |
| 479 |
|
| 480 |
def depart_field_name(self, node) -> None: |
| 481 |
self.body.append(':</th>') |
| 482 |
self.body.append(self.context.pop()) |
| 483 |
|
| 484 |
# use table for footnote text |
| 485 |
def visit_footnote(self, node) -> None: |
| 486 |
self.body.append(self.starttag(node, 'table', |
| 487 |
CLASS='docutils footnote', |
| 488 |
frame="void", rules="none")) |
| 489 |
self.body.append('<colgroup><col class="label" /><col /></colgroup>\n' |
| 490 |
'<tbody valign="top">\n' |
| 491 |
'<tr>') |
| 492 |
self.footnote_backrefs(node) |
| 493 |
|
| 494 |
def footnote_backrefs(self, node) -> None: |
| 495 |
backlinks = [] |
| 496 |
backrefs = node['backrefs'] |
| 497 |
if self.settings.footnote_backlinks and backrefs: |
| 498 |
if len(backrefs) == 1: |
| 499 |
self.context.append('') |
| 500 |
self.context.append('</a>') |
| 501 |
self.context.append('<a class="fn-backref" href="#%s">' |
| 502 |
% backrefs[0]) |
| 503 |
else: |
| 504 |
for (i, backref) in enumerate(backrefs, 1): |
| 505 |
backlinks.append('<a class="fn-backref" href="#%s">%s</a>' |
| 506 |
% (backref, i)) |
| 507 |
self.context.append('<em>(%s)</em> ' % ', '.join(backlinks)) |
| 508 |
self.context += ['', ''] |
| 509 |
else: |
| 510 |
self.context.append('') |
| 511 |
self.context += ['', ''] |
| 512 |
# If the node does not only consist of a label. |
| 513 |
if len(node) > 1: |
| 514 |
# If there are preceding backlinks, we do not set class |
| 515 |
# 'first', because we need to retain the top-margin. |
| 516 |
if not backlinks: |
| 517 |
node[1]['classes'].append('first') |
| 518 |
node[-1]['classes'].append('last') |
| 519 |
|
| 520 |
def depart_footnote(self, node) -> None: |
| 521 |
self.body.append('</td></tr>\n' |
| 522 |
'</tbody>\n</table>\n') |
| 523 |
|
| 524 |
# insert markers in text (pseudo-classes are not supported in CSS1): |
| 525 |
def visit_footnote_reference(self, node) -> None: |
| 526 |
href = '#' + node['refid'] |
| 527 |
format = self.settings.footnote_references |
| 528 |
if format == 'brackets': |
| 529 |
suffix = '[' |
| 530 |
self.context.append(']') |
| 531 |
else: |
| 532 |
assert format == 'superscript' |
| 533 |
suffix = '<sup>' |
| 534 |
self.context.append('</sup>') |
| 535 |
self.body.append(self.starttag(node, 'a', suffix, |
| 536 |
CLASS='footnote-reference', href=href)) |
| 537 |
|
| 538 |
def depart_footnote_reference(self, node) -> None: |
| 539 |
self.body.append(self.context.pop() + '</a>') |
| 540 |
|
| 541 |
# just pass on generated text |
| 542 |
def visit_generated(self, node) -> None: |
| 543 |
pass |
| 544 |
|
| 545 |
# Backwards-compatibility implementation: |
| 546 |
# * Do not use <video>, |
| 547 |
# * don't embed images, |
| 548 |
# * use <object> instead of <img> for SVG. |
| 549 |
# (SVG not supported by IE up to version 8, |
| 550 |
# html4css1 strives for IE6 compatibility.) |
| 551 |
object_image_types = {'.svg': 'image/svg+xml', |
| 552 |
'.swf': 'application/x-shockwave-flash', |
| 553 |
'.mp4': 'video/mp4', |
| 554 |
'.webm': 'video/webm', |
| 555 |
'.ogg': 'video/ogg', |
| 556 |
} |
| 557 |
|
| 558 |
def visit_image(self, node) -> None: |
| 559 |
atts = {} |
| 560 |
uri = node['uri'] |
| 561 |
ext = os.path.splitext(uri)[1].lower() |
| 562 |
if ext in self.object_image_types: |
| 563 |
atts['data'] = uri |
| 564 |
atts['type'] = self.object_image_types[ext] |
| 565 |
else: |
| 566 |
atts['src'] = uri |
| 567 |
atts['alt'] = node.get('alt', uri) |
| 568 |
# image size |
| 569 |
if 'width' in node: |
| 570 |
atts['width'] = node['width'] |
| 571 |
if 'height' in node: |
| 572 |
atts['height'] = node['height'] |
| 573 |
if 'scale' in node: |
| 574 |
if (PIL and ('width' not in node or 'height' not in node) |
| 575 |
and self.settings.file_insertion_enabled): |
| 576 |
try: |
| 577 |
imagepath = self.uri2path(uri) |
| 578 |
with PIL.Image.open(imagepath) as img: |
| 579 |
img_size = img.size |
| 580 |
except (ValueError, OSError, UnicodeEncodeError) as e: |
| 581 |
self.document.reporter.warning( |
| 582 |
f'Problem reading image file: {e}') |
| 583 |
else: |
| 584 |
self.settings.record_dependencies.add(imagepath.as_posix()) |
| 585 |
if 'width' not in atts: |
| 586 |
atts['width'] = '%dpx' % img_size[0] |
| 587 |
if 'height' not in atts: |
| 588 |
atts['height'] = '%dpx' % img_size[1] |
| 589 |
for att_name in 'width', 'height': |
| 590 |
if att_name in atts: |
| 591 |
match = re.match(r'([0-9.]+)(\S*)$', atts[att_name]) |
| 592 |
assert match |
| 593 |
atts[att_name] = '%s%s' % ( |
| 594 |
float(match.group(1)) * (float(node['scale']) / 100), |
| 595 |
match.group(2)) |
| 596 |
style = [] |
| 597 |
for att_name in 'width', 'height': |
| 598 |
if att_name in atts: |
| 599 |
if re.match(r'^[0-9.]+$', atts[att_name]): |
| 600 |
# Interpret unitless values as pixels. |
| 601 |
atts[att_name] += 'px' |
| 602 |
style.append('%s: %s;' % (att_name, atts[att_name])) |
| 603 |
del atts[att_name] |
| 604 |
if style: |
| 605 |
atts['style'] = ' '.join(style) |
| 606 |
# No newlines around inline images. |
| 607 |
if (not isinstance(node.parent, nodes.TextElement) |
| 608 |
or isinstance(node.parent, nodes.reference) |
| 609 |
and not isinstance(node.parent.parent, nodes.TextElement)): |
| 610 |
suffix = '\n' |
| 611 |
else: |
| 612 |
suffix = '' |
| 613 |
if 'align' in node: |
| 614 |
atts['class'] = 'align-%s' % node['align'] |
| 615 |
if ext in self.object_image_types: |
| 616 |
# do NOT use an empty tag: incorrect rendering in browsers |
| 617 |
self.body.append(self.starttag(node, 'object', '', **atts) |
| 618 |
+ node.get('alt', uri) + '</object>' + suffix) |
| 619 |
else: |
| 620 |
self.body.append(self.emptytag(node, 'img', suffix, **atts)) |
| 621 |
|
| 622 |
def depart_image(self, node) -> None: |
| 623 |
pass |
| 624 |
|
| 625 |
# use table for footnote text, |
| 626 |
# context added in footnote_backrefs. |
| 627 |
def visit_label(self, node) -> None: |
| 628 |
self.body.append(self.starttag(node, 'td', '%s[' % self.context.pop(), |
| 629 |
CLASS='label')) |
| 630 |
|
| 631 |
def depart_label(self, node) -> None: |
| 632 |
self.body.append(f']{self.context.pop()}</td><td>{self.context.pop()}') |
| 633 |
|
| 634 |
# ersatz for first/last pseudo-classes |
| 635 |
def visit_list_item(self, node) -> None: |
| 636 |
self.body.append(self.starttag(node, 'li', '')) |
| 637 |
if len(node): |
| 638 |
node[0]['classes'].append('first') |
| 639 |
|
| 640 |
def depart_list_item(self, node) -> None: |
| 641 |
self.body.append('</li>\n') |
| 642 |
|
| 643 |
# use <tt> (not supported by HTML5), |
| 644 |
# cater for limited styling options in CSS1 using hard-coded NBSPs |
| 645 |
def visit_literal(self, node): |
| 646 |
# special case: "code" role |
| 647 |
classes = node['classes'] |
| 648 |
if 'code' in classes: |
| 649 |
# filter 'code' from class arguments |
| 650 |
node['classes'] = [cls for cls in classes if cls != 'code'] |
| 651 |
self.body.append(self.starttag(node, 'code', '')) |
| 652 |
return |
| 653 |
self.body.append( |
| 654 |
self.starttag(node, 'tt', '', CLASS='docutils literal')) |
| 655 |
text = node.astext() |
| 656 |
for token in self.words_and_spaces.findall(text): |
| 657 |
if token.strip(): |
| 658 |
# Protect text like "--an-option" and the regular expression |
| 659 |
# ``[+]?(\d+(\.\d*)?|\.\d+)`` from bad line wrapping |
| 660 |
if self.in_word_wrap_point.search(token): |
| 661 |
self.body.append('<span class="pre">%s</span>' |
| 662 |
% self.encode(token)) |
| 663 |
else: |
| 664 |
self.body.append(self.encode(token)) |
| 665 |
elif token in ('\n', ' '): |
| 666 |
# Allow breaks at whitespace: |
| 667 |
self.body.append(token) |
| 668 |
else: |
| 669 |
# Protect runs of multiple spaces; the last space can wrap: |
| 670 |
self.body.append(' ' * (len(token) - 1) + ' ') |
| 671 |
self.body.append('</tt>') |
| 672 |
# Content already processed: |
| 673 |
raise nodes.SkipNode |
| 674 |
|
| 675 |
def depart_literal(self, node) -> None: |
| 676 |
# skipped unless literal element is from "code" role: |
| 677 |
self.body.append('</code>') |
| 678 |
|
| 679 |
# add newline after wrapper tags, don't use <code> for code |
| 680 |
def visit_literal_block(self, node) -> None: |
| 681 |
self.body.append(self.starttag(node, 'pre', CLASS='literal-block')) |
| 682 |
|
| 683 |
def depart_literal_block(self, node) -> None: |
| 684 |
self.body.append('\n</pre>\n') |
| 685 |
|
| 686 |
# use table for option list |
| 687 |
def visit_option_group(self, node) -> None: |
| 688 |
atts = {} |
| 689 |
if (self.settings.option_limit |
| 690 |
and len(node.astext()) > self.settings.option_limit): |
| 691 |
atts['colspan'] = 2 |
| 692 |
self.context.append('</tr>\n<tr><td> </td>') |
| 693 |
else: |
| 694 |
self.context.append('') |
| 695 |
self.body.append( |
| 696 |
self.starttag(node, 'td', CLASS='option-group', **atts)) |
| 697 |
self.body.append('<kbd>') |
| 698 |
self.context.append(0) # count number of options |
| 699 |
|
| 700 |
def depart_option_group(self, node) -> None: |
| 701 |
self.context.pop() |
| 702 |
self.body.append('</kbd></td>\n') |
| 703 |
self.body.append(self.context.pop()) |
| 704 |
|
| 705 |
def visit_option_list(self, node) -> None: |
| 706 |
self.body.append( |
| 707 |
self.starttag(node, 'table', CLASS='docutils option-list', |
| 708 |
frame="void", rules="none")) |
| 709 |
self.body.append('<col class="option" />\n' |
| 710 |
'<col class="description" />\n' |
| 711 |
'<tbody valign="top">\n') |
| 712 |
|
| 713 |
def depart_option_list(self, node) -> None: |
| 714 |
self.body.append('</tbody>\n</table>\n') |
| 715 |
|
| 716 |
def visit_option_list_item(self, node) -> None: |
| 717 |
self.body.append(self.starttag(node, 'tr', '')) |
| 718 |
|
| 719 |
def depart_option_list_item(self, node) -> None: |
| 720 |
self.body.append('</tr>\n') |
| 721 |
|
| 722 |
# Omit <p> tags to produce visually compact lists (less vertical |
| 723 |
# whitespace) as CSS styling requires CSS2. |
| 724 |
def should_be_compact_paragraph(self, node) -> bool: |
| 725 |
""" |
| 726 |
Determine if the <p> tags around paragraph ``node`` can be omitted. |
| 727 |
""" |
| 728 |
if (isinstance(node.parent, nodes.document) |
| 729 |
or isinstance(node.parent, nodes.compound)): |
| 730 |
# Never compact paragraphs in document or compound. |
| 731 |
return False |
| 732 |
for key, value in node.attlist(): |
| 733 |
if (node.is_not_default(key) |
| 734 |
and not (key == 'classes' |
| 735 |
and value in ([], ['first'], |
| 736 |
['last'], ['first', 'last']))): |
| 737 |
# Attribute which needs to survive. |
| 738 |
return False |
| 739 |
first = isinstance(node.parent[0], nodes.label) # skip label |
| 740 |
for child in node.parent.children[first:]: |
| 741 |
# only first paragraph can be compact |
| 742 |
if isinstance(child, nodes.Invisible): |
| 743 |
continue |
| 744 |
if child is node: |
| 745 |
break |
| 746 |
return False |
| 747 |
parent_length = len([n for n in node.parent if not isinstance( |
| 748 |
n, (nodes.Invisible, nodes.label))]) |
| 749 |
if (self.compact_simple |
| 750 |
or self.compact_field_list |
| 751 |
or self.compact_p and parent_length == 1): |
| 752 |
return True |
| 753 |
return False |
| 754 |
|
| 755 |
def visit_paragraph(self, node) -> None: |
| 756 |
if self.should_be_compact_paragraph(node): |
| 757 |
self.context.append('') |
| 758 |
else: |
| 759 |
self.body.append(self.starttag(node, 'p', '')) |
| 760 |
self.context.append('</p>\n') |
| 761 |
|
| 762 |
def depart_paragraph(self, node) -> None: |
| 763 |
self.body.append(self.context.pop()) |
| 764 |
self.report_messages(node) |
| 765 |
|
| 766 |
# ersatz for first/last pseudo-classes |
| 767 |
def visit_sidebar(self, node) -> None: |
| 768 |
self.body.append( |
| 769 |
self.starttag(node, 'div', CLASS='sidebar')) |
| 770 |
self.set_first_last(node) |
| 771 |
self.in_sidebar = True |
| 772 |
|
| 773 |
def depart_sidebar(self, node) -> None: |
| 774 |
self.body.append('</div>\n') |
| 775 |
self.in_sidebar = False |
| 776 |
|
| 777 |
# <sub> not allowed in <pre> |
| 778 |
def visit_subscript(self, node) -> None: |
| 779 |
if isinstance(node.parent, nodes.literal_block): |
| 780 |
self.body.append(self.starttag(node, 'span', '', |
| 781 |
CLASS='subscript')) |
| 782 |
else: |
| 783 |
self.body.append(self.starttag(node, 'sub', '')) |
| 784 |
|
| 785 |
def depart_subscript(self, node) -> None: |
| 786 |
if isinstance(node.parent, nodes.literal_block): |
| 787 |
self.body.append('</span>') |
| 788 |
else: |
| 789 |
self.body.append('</sub>') |
| 790 |
|
| 791 |
# Use <h*> for subtitles (deprecated in HTML 5) |
| 792 |
def visit_subtitle(self, node) -> None: |
| 793 |
if isinstance(node.parent, nodes.sidebar): |
| 794 |
self.body.append(self.starttag(node, 'p', '', |
| 795 |
CLASS='sidebar-subtitle')) |
| 796 |
self.context.append('</p>\n') |
| 797 |
elif isinstance(node.parent, nodes.document): |
| 798 |
self.body.append(self.starttag(node, 'h2', '', CLASS='subtitle')) |
| 799 |
self.context.append('</h2>\n') |
| 800 |
self.in_document_title = len(self.body) |
| 801 |
elif isinstance(node.parent, nodes.section): |
| 802 |
tag = 'h%s' % (self.section_level + self.initial_header_level - 1) |
| 803 |
self.body.append( |
| 804 |
self.starttag(node, tag, '', CLASS='section-subtitle') |
| 805 |
+ self.starttag({}, 'span', '', CLASS='section-subtitle')) |
| 806 |
self.context.append('</span></%s>\n' % tag) |
| 807 |
|
| 808 |
def depart_subtitle(self, node) -> None: |
| 809 |
self.body.append(self.context.pop()) |
| 810 |
if self.in_document_title: |
| 811 |
self.subtitle = self.body[self.in_document_title:-1] |
| 812 |
self.in_document_title = 0 |
| 813 |
self.body_pre_docinfo.extend(self.body) |
| 814 |
self.html_subtitle.extend(self.body) |
| 815 |
del self.body[:] |
| 816 |
|
| 817 |
# <sup> not allowed in <pre> in HTML 4 |
| 818 |
def visit_superscript(self, node) -> None: |
| 819 |
if isinstance(node.parent, nodes.literal_block): |
| 820 |
self.body.append(self.starttag(node, 'span', '', |
| 821 |
CLASS='superscript')) |
| 822 |
else: |
| 823 |
self.body.append(self.starttag(node, 'sup', '')) |
| 824 |
|
| 825 |
def depart_superscript(self, node) -> None: |
| 826 |
if isinstance(node.parent, nodes.literal_block): |
| 827 |
self.body.append('</span>') |
| 828 |
else: |
| 829 |
self.body.append('</sup>') |
| 830 |
|
| 831 |
# <tt> element deprecated in HTML 5 |
| 832 |
def visit_system_message(self, node) -> None: |
| 833 |
self.body.append(self.starttag(node, 'div', CLASS='system-message')) |
| 834 |
self.body.append('<p class="system-message-title">') |
| 835 |
backref_text = '' |
| 836 |
if len(node['backrefs']): |
| 837 |
backrefs = node['backrefs'] |
| 838 |
if len(backrefs) == 1: |
| 839 |
backref_text = ('; <em><a href="#%s">backlink</a></em>' |
| 840 |
% backrefs[0]) |
| 841 |
else: |
| 842 |
i = 1 |
| 843 |
backlinks = [] |
| 844 |
for backref in backrefs: |
| 845 |
backlinks.append('<a href="#%s">%s</a>' % (backref, i)) |
| 846 |
i += 1 |
| 847 |
backref_text = ('; <em>backlinks: %s</em>' |
| 848 |
% ', '.join(backlinks)) |
| 849 |
if node.hasattr('line'): |
| 850 |
line = ', line %s' % node['line'] |
| 851 |
else: |
| 852 |
line = '' |
| 853 |
self.body.append('System Message: %s/%s ' |
| 854 |
'(<tt class="docutils">%s</tt>%s)%s</p>\n' |
| 855 |
% (node['type'], node['level'], |
| 856 |
self.encode(node['source']), line, backref_text)) |
| 857 |
|
| 858 |
def depart_system_message(self, node) -> None: |
| 859 |
self.body.append('</div>\n') |
| 860 |
|
| 861 |
# "hard coded" border setting |
| 862 |
def visit_table(self, node) -> None: |
| 863 |
self.context.append(self.compact_p) |
| 864 |
self.compact_p = True |
| 865 |
atts = {'border': 1} |
| 866 |
classes = ['docutils', self.settings.table_style] |
| 867 |
if 'align' in node: |
| 868 |
classes.append('align-%s' % node['align']) |
| 869 |
if 'width' in node: |
| 870 |
width = node['width'] |
| 871 |
if width[-1:] in '0123456789.': # unitless value |
| 872 |
width += 'px' # add default length unit |
| 873 |
atts['style'] = f'width: {width}' |
| 874 |
self.body.append( |
| 875 |
self.starttag(node, 'table', CLASS=' '.join(classes), **atts)) |
| 876 |
|
| 877 |
def depart_table(self, node) -> None: |
| 878 |
self.compact_p = self.context.pop() |
| 879 |
self.body.append('</table>\n') |
| 880 |
|
| 881 |
# hard-coded vertical alignment |
| 882 |
def visit_tbody(self, node) -> None: |
| 883 |
self.body.append(self.starttag(node, 'tbody', valign='top')) |
| 884 |
|
| 885 |
def depart_tbody(self, node) -> None: |
| 886 |
self.body.append('</tbody>\n') |
| 887 |
|
| 888 |
# no special handling of "details" in definition list |
| 889 |
def visit_term(self, node) -> None: |
| 890 |
self.body.append(self.starttag(node, 'dt', '', |
| 891 |
classes=node.parent['classes'], |
| 892 |
ids=node.parent['ids'])) |
| 893 |
|
| 894 |
def depart_term(self, node) -> None: |
| 895 |
# Nest (optional) classifier(s) in the <dt> element |
| 896 |
if node.next_node(nodes.classifier, descend=False, siblings=True): |
| 897 |
return # skip (depart_classifier() calls this function again) |
| 898 |
self.body.append('</dt>\n') |
| 899 |
|
| 900 |
# hard-coded vertical alignment |
| 901 |
def visit_thead(self, node) -> None: |
| 902 |
self.body.append(self.starttag(node, 'thead', valign='bottom')) |
| 903 |
|
| 904 |
def depart_thead(self, node) -> None: |
| 905 |
self.body.append('</thead>\n') |
| 906 |
|
| 907 |
# auxiliary method, called by visit_title() |
| 908 |
# "with-subtitle" class, no ARIA roles |
| 909 |
def section_title_tags(self, node): |
| 910 |
classes = [] |
| 911 |
h_level = self.section_level + self.initial_header_level - 1 |
| 912 |
if (len(node.parent) >= 2 |
| 913 |
and isinstance(node.parent[1], nodes.subtitle)): |
| 914 |
classes.append('with-subtitle') |
| 915 |
if h_level > 6: |
| 916 |
classes.append('h%i' % h_level) |
| 917 |
tagname = 'h%i' % min(h_level, 6) |
| 918 |
start_tag = self.starttag(node, tagname, '', classes=classes) |
| 919 |
if node.hasattr('refid'): |
| 920 |
atts = {} |
| 921 |
atts['class'] = 'toc-backref' |
| 922 |
atts['href'] = '#' + node['refid'] |
| 923 |
start_tag += self.starttag({}, 'a', '', **atts) |
| 924 |
close_tag = '</a></%s>\n' % tagname |
| 925 |
else: |
| 926 |
close_tag = '</%s>\n' % tagname |
| 927 |
return start_tag, close_tag |
| 928 |
|
| 929 |
|
| 930 |
class SimpleListChecker(writers._html_base.SimpleListChecker): |
| 931 |
|
| 932 |
""" |
| 933 |
Raise `nodes.NodeFound` if non-simple list item is encountered. |
| 934 |
|
| 935 |
Here "simple" means a list item containing nothing other than a single |
| 936 |
paragraph, a simple list, or a paragraph followed by a simple list. |
| 937 |
""" |
| 938 |
|
| 939 |
def visit_list_item(self, node): |
| 940 |
children = [child for child in node.children |
| 941 |
if not isinstance(child, nodes.Invisible)] |
| 942 |
if (children and isinstance(children[0], nodes.paragraph) |
| 943 |
and (isinstance(children[-1], nodes.bullet_list) |
| 944 |
or isinstance(children[-1], nodes.enumerated_list))): |
| 945 |
children.pop() |
| 946 |
if len(children) <= 1: |
| 947 |
return |
| 948 |
else: |
| 949 |
raise nodes.NodeFound |
| 950 |
|
| 951 |
# def visit_bullet_list(self, node): |
| 952 |
# pass |
| 953 |
|
| 954 |
# def visit_enumerated_list(self, node): |
| 955 |
# pass |
| 956 |
|
| 957 |
def visit_paragraph(self, node): |
| 958 |
raise nodes.SkipNode |
| 959 |
|
| 960 |
def visit_definition_list(self, node): |
| 961 |
raise nodes.NodeFound |
| 962 |
|
| 963 |
def visit_docinfo(self, node): |
| 964 |
raise nodes.NodeFound |