# $Id: __init__.py 10270 2025-12-03 11:38:54Z milde $
# Author: David Goodger
# Maintainer: docutils-develop@lists.sourceforge.net
# Copyright: This module has been placed in the public domain.
"""
Simple HyperText Markup Language document tree Writer.
The output conforms to the XHTML version 1.0 Transitional DTD
(*almost* strict). The output contains a minimum of formatting
information. The cascading style sheet "html4css1.css" is required
for proper viewing with a modern graphical browser.
"""
from __future__ import annotations
__docformat__ = 'reStructuredText'
import os.path
import re
from docutils import frontend, nodes, writers
from docutils.writers import _html_base
from docutils.writers._html_base import PIL
class Writer(writers._html_base.Writer):
supported = ('html', 'html4', 'html4css1', 'xhtml', 'xhtml10')
"""Formats this writer supports."""
default_stylesheets = ['html4css1.css']
default_stylesheet_dirs = ['.',
os.path.abspath(os.path.dirname(__file__)),
os.path.abspath(os.path.join(
os.path.dirname(os.path.dirname(__file__)),
'html5_polyglot')) # for math.css
]
default_template = os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'template.txt')
# use a copy of the parent spec with some modifications
settings_spec = frontend.filter_settings_spec(
writers._html_base.Writer.settings_spec,
template=(
'Template file. (UTF-8 encoded, default: "%s")' % default_template,
['--template'],
{'default': default_template, 'metavar': ''}),
stylesheet_path=(
'Comma separated list of stylesheet paths. '
'Relative paths are expanded if a matching file is found in '
'the --stylesheet-dirs. With --link-stylesheet, '
'the path is rewritten relative to the output HTML file. '
'(default: "%s")' % ','.join(default_stylesheets),
['--stylesheet-path'],
{'metavar': '', 'overrides': 'stylesheet',
'validator': frontend.validate_comma_separated_list,
'default': default_stylesheets}),
stylesheet_dirs=(
'Comma-separated list of directories where stylesheets are found. '
'Used by --stylesheet-path when expanding relative path '
'arguments. (default: "%s")' % ','.join(default_stylesheet_dirs),
['--stylesheet-dirs'],
{'metavar': '',
'validator': frontend.validate_comma_separated_list,
'default': default_stylesheet_dirs}),
initial_header_level=(
'Specify the initial header level. Does not affect document '
'title & subtitle (see --no-doc-title). (default: 1 for "")',
['--initial-header-level'],
{'choices': '1 2 3 4 5 6 auto'.split(), 'default': '1',
'metavar': ''}),
math_output=(
'Math output format (one of "MathML", "HTML", "MathJax", or '
'"LaTeX") and option(s). (default: "HTML math.css")',
['--math-output'],
{'metavar': '', 'default': 'HTML math.css',
'validator': frontend.validate_math_output}),
xml_declaration=(
'Prepend an XML declaration (default). ',
['--xml-declaration'],
{'default': True, 'action': 'store_true',
'validator': frontend.validate_boolean}),
)
settings_spec = settings_spec + (
'HTML4 Writer Options',
'',
(('Specify the maximum width (in characters) for one-column field '
'names. Longer field names will span an entire row of the table '
'used to render the field list. Default is 14 characters. '
'Use 0 for "no limit".',
['--field-name-limit'],
{'default': 14, 'metavar': '',
'validator': frontend.validate_nonnegative_int}),
('Specify the maximum width (in characters) for options in option '
'lists. Longer options will span an entire row of the table used '
'to render the option list. Default is 14 characters. '
'Use 0 for "no limit".',
['--option-limit'],
{'default': 14, 'metavar': '',
'validator': frontend.validate_nonnegative_int}),
)
)
config_section = 'html4css1 writer'
def __init__(self) -> None:
self.parts = {}
self.translator_class = HTMLTranslator
class HTMLTranslator(writers._html_base.HTMLTranslator):
"""
The html4css1 writer has been optimized to produce visually compact
lists (less vertical whitespace). HTML's mixed content models
allow list items to contain "body elements
" or
"just text " or even "textand body
elements
combined ", each with different effects. It would
be best to stick with strict body elements in list items, but they
affect vertical spacing in older browsers (although they really
shouldn't).
The html5_polyglot writer solves this using CSS2.
Here is an outline of the optimization:
- Check for and omit tags in "simple" lists: list items
contain either a single paragraph, a nested simple list, or a
paragraph followed by a nested simple list. This means that
this list can be compact:
- Item 1.
- Item 2.
But this list cannot be compact:
- Item 1.
This second paragraph forces space between list items.
- Item 2.
- In non-list contexts, omit
tags on a paragraph if that
paragraph is the only child of its parent (footnotes & citations
are allowed a label first).
- Regardless of the above, in definitions, table cells, field bodies,
option descriptions, and list items, mark the first child with
'class="first"' and the last child with 'class="last"'. The stylesheet
sets the margins (top & bottom respectively) to 0 for these elements.
The ``no_compact_lists`` setting (``--no-compact-lists`` command-line
option) disables list whitespace optimization.
"""
# The following definitions are required for display in browsers limited
# to CSS1 or backwards compatible behaviour of the writer:
doctype = (
'\n')
content_type = ('\n')
content_type_mathml = ('\n')
# encode also non-breaking space
special_characters = _html_base.HTMLTranslator.special_characters.copy()
special_characters[0xa0] = ' '
# use character reference for dash (not valid in HTML5)
attribution_formats = {'dash': ('—', ''),
'parentheses': ('(', ')'),
'parens': ('(', ')'),
'none': ('', '')}
# ersatz for first/last pseudo-classes missing in CSS1
def set_first_last(self, node) -> None:
self.set_class_on_child(node, 'first', 0)
self.set_class_on_child(node, 'last', -1)
# add newline after opening tag
def visit_address(self, node) -> None:
self.visit_docinfo_item(node, 'address', meta=False)
self.body.append(self.starttag(node, 'pre', CLASS='address'))
def depart_address(self, node) -> None:
self.body.append('\n
\n')
self.depart_docinfo_item()
# ersatz for first/last pseudo-classes
def visit_admonition(self, node) -> None:
node['classes'].insert(0, 'admonition')
self.body.append(self.starttag(node, 'div'))
self.set_first_last(node)
def depart_admonition(self, node=None) -> None:
self.body.append('\n')
# author, authors: use