fix: align contextual CSS rendering and Word styles

This commit is contained in:
2026-10-30 13:12:05 +08:00
parent cc4f91899e
commit f9bf62b71c
17 changed files with 313 additions and 53 deletions
+1 -1
View File
@@ -65,7 +65,7 @@ def normalize_rule(value: object) -> dict[str, Any]:
if key in rule and not isinstance(rule[key], bool):
rule.pop(key)
for key in ('font_color', 'background_color', 'border_color'):
if key in rule and not re.fullmatch(r"auto|transparent|#[0-9a-fA-F]{6}", str(rule[key])):
if key in rule and not re.fullmatch(r"auto|transparent|inherit|#[0-9a-fA-F]{6}", str(rule[key])):
rule.pop(key)
for key, allowed in {"alignment": {"left", "center", "right", "justify"},
"indent_mode": {"none", "first", "hanging"},
+11 -3
View File
@@ -15,7 +15,7 @@ from markdown_it import MarkdownIt
from markdown_it.token import Token
from .markdown_compat import cjk_strong_plugin
from .docx_inline import source_style_name
from .docx_inline import source_style_name, LIST_PARAGRAPH_STYLE
WP_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
@@ -118,6 +118,7 @@ def export_markdown_to_docx_builtin(source: str, output_path: Path) -> Path:
package.writestr("_rels/.rels", PACKAGE_RELS_XML)
package.writestr("word/document.xml", document_xml)
markers = ''.join(f'<w:style w:type="character" w:styleId="{name}"><w:name w:val="{name}"/></w:style>' for name in sorted(source_styles))
markers += f'<w:style w:type="paragraph" w:styleId="{LIST_PARAGRAPH_STYLE}"><w:name w:val="{LIST_PARAGRAPH_STYLE}"/><w:basedOn w:val="ListParagraph"/></w:style>'
package.writestr("word/styles.xml", STYLES_XML.replace('</w:styles>', markers + '</w:styles>'))
package.writestr("word/settings.xml", SETTINGS_XML)
relations = ''.join(f'<Relationship Id="{identifier}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target={quoteattr(href)} TargetMode="External"/>' for href, identifier in links.items())
@@ -245,6 +246,12 @@ def _add_python_docx_paragraph(document: object, block: ParagraphBlock) -> None:
elif block.quote_depth:
style = "Quote"
if block.list_kind and block.loose:
from docx.enum.style import WD_STYLE_TYPE
if LIST_PARAGRAPH_STYLE not in document.styles:
marker = document.styles.add_style(LIST_PARAGRAPH_STYLE, WD_STYLE_TYPE.PARAGRAPH)
marker.base_style = document.styles[style]
style = LIST_PARAGRAPH_STYLE
paragraph = document.add_paragraph(style=style)
if block.list_kind:
from docx.oxml import parse_xml
@@ -319,6 +326,7 @@ class ParagraphBlock:
list_level: int = 0
list_id: int = 0
list_start: int = 1
loose: bool = False
@dataclass
@@ -377,7 +385,7 @@ class _DocxBuilder:
runs = _inline_runs(inline.children if inline is not None else None)
self.blocks.append(ParagraphBlock(runs, style=style, list_kind=list_kind, quote_depth=self.quote_depth,
list_level=min(8, max(0, len(self.list_stack) - 1)), list_id=self.list_ids[-1] if self.list_ids else 0,
list_start=self.list_starts[-1] if self.list_starts else 1))
list_start=self.list_starts[-1] if self.list_starts else 1, loose=not self.tokens[self.index].hidden))
self.index += 3
def _collect_table(self) -> TableBlock:
@@ -471,7 +479,7 @@ def _block_xml(block: ParagraphBlock | TableBlock) -> str:
def _paragraph_xml(block: ParagraphBlock) -> str:
props = [f'<w:pStyle w:val="{block.style}"/>'] if block.style != "Normal" else []
if block.list_kind:
props = ['<w:pStyle w:val="ListParagraph"/>']
props = [f'<w:pStyle w:val="{LIST_PARAGRAPH_STYLE if block.loose else "ListParagraph"}"/>']
props.append(f'<w:numPr><w:ilvl w:val="{block.list_level}"/><w:numId w:val="{block.list_id}"/></w:numPr>')
if block.quote_depth:
props.append('<w:ind w:left="720"/>')
+1
View File
@@ -1,5 +1,6 @@
"""Private, temporary style markers shared by the three DOCX converters."""
PREFIX = 'MDHelperSource_'
LIST_PARAGRAPH_STYLE = 'MDHelperSourceListParagraph'
CODES = {'strong': 'B', 'emphasis': 'I', 'strike': 'S', 'link': 'L', 'inline_code': 'C'}
+38 -8
View File
@@ -13,7 +13,7 @@ from lxml import etree as ET
from .document_style import resolved_rules, normalize_rule, font_points, length_points, number
from .style_catalog import CATALOG, CHARACTER_DEFAULTS, explicit_rules, parent_style, style_name
from .docx_style import W, NS, child, val, properties, _run_properties, _paragraph_properties, _order_properties
from .docx_inline import source_style_order, ordered_styles
from .docx_inline import source_style_order, ordered_styles, LIST_PARAGRAPH_STYLE
RUN_FIELDS = 'rFonts sz szCs b bCs i iCs color spacing u strike shd'.split()
PARAGRAPH_FIELDS = 'jc spacing ind shd snapToGrid contextualSpacing keepNext keepLines pageBreakBefore widowControl rPr outlineLvl'.split()
@@ -121,7 +121,8 @@ class WordStyles:
remove_fields(child(table_text, 'rPr'), ('shd',))
base = 'table'
style = self.new(identifier, 'paragraph', 'MDHelper ' + style_name(key, self.rules), base_id)
rule = self.effective[key]
rule = dict(self.effective[key])
if rule.get('font_color') == 'inherit': rule['font_color'] = 'auto'
_paragraph_properties(child(style, 'pPr'), rule)
_run_properties(child(style, 'rPr'), rule)
remove_fields(child(style, 'rPr'), ('shd',))
@@ -149,10 +150,14 @@ class WordStyles:
if identifier in self.created: return identifier
base = parent_style(key, self.rules)
base_id = self.character(base) if base else ''
style = self.new(identifier, 'character', 'MDHelper ' + style_name(key, self.rules), base_id)
rule = self.character_rule(key)
# Word cannot clear one inherited character-style property. Preserve
# the resolved remaining properties and inherit color from the text.
if rule.get('font_color') == 'inherit' and base and self.character_rule(base).get('font_color') not in (None, 'inherit'):
base_id = ''
style = self.new(identifier, 'character', 'MDHelper ' + style_name(key, self.rules), base_id)
_run_properties(child(style, 'rPr'), rule)
if base:
if base_id:
old = ET.Element(W + 'rPr')
_run_properties(old, self.character_rule(base))
_delta(child(style, 'rPr'), old, normalize_rule(self.rules.get(key)))
@@ -161,8 +166,9 @@ class WordStyles:
def combined_character(self, keys, paragraph_target):
keys = ordered_styles(keys)
if not keys: return ''
merged = dict(self.character_rule(keys[0]))
for key in keys[1:]: merged.update(self.character_rule(key))
merged = {}
for key in keys:
merged.update({field: value for field, value in self.character_rule(key).items() if not (field == 'font_color' and value == 'inherit')})
identifier = self.character(keys[0]) if len(keys) == 1 else 'MDHelperMix' + ''.join(style_id(key)[8:] for key in keys)
if identifier not in self.created:
base = 'link' if 'link' in keys else keys[0]
@@ -248,6 +254,22 @@ class WordStyles:
child(style, 'pPr').append(ind)
return identifier
def list_paragraph(self, target, base_id):
"""A loose Markdown list contains a real p element; a tight one does not."""
own = normalize_rule(self.rules.get('_list_paragraph'))
if not own: return base_id
identifier = base_id + 'Paragraph'
if identifier not in self.created:
style = self.new(identifier, 'paragraph', 'MDHelper ' + style_name(target, self.rules) + '(段落)' + base_id.removeprefix(style_id(target)), base_id)
base = self.effective[target]
rule = {**base, **own}
for tag, writer in (('pPr', _paragraph_properties), ('rPr', _run_properties)):
props, old = child(style, tag), ET.Element(W + tag)
writer(props, rule); writer(old, base)
if tag == 'rPr': remove_fields(props, ('shd',)); remove_fields(old, ('shd',))
_delta(props, old, own)
return identifier
def apply_list_marker(self, numpr, target, marker):
level, original_level = self.list_level(numpr)
if original_level is None: return
@@ -331,7 +353,9 @@ class WordStyles:
def apply(self, document):
for paragraph in document.iter(W + 'p'):
ppr = properties(paragraph, 'pPr')
target = self.classify(paragraph, reference(ppr, 'pStyle') or 'Normal')
original_id = reference(ppr, 'pStyle') or 'Normal'
loose = any(reference(style, 'name') == LIST_PARAGRAPH_STYLE for style in self.chain(original_id))
target = self.classify(paragraph, original_id)
identifier = self.paragraph(target)
if target.startswith('list_'):
numpr = ppr.find(W + 'numPr')
@@ -339,6 +363,7 @@ class WordStyles:
if level: identifier = self.nested_list(target, level)
marker = self.effective[target].get('list_marker')
if marker: self.apply_list_marker(numpr, target, marker)
if loose: identifier = self.list_paragraph(target, identifier)
remove_fields(ppr, PARAGRAPH_FIELDS)
val(ppr, 'pStyle', identifier)
for run in paragraph.iter(W + 'r'): self.apply_run(run, target)
@@ -362,12 +387,17 @@ def apply_semantic_styles(path, rules, **defaults):
adapter.apply(parts['word/document.xml'])
for name in ('word/footnotes.xml', 'word/endnotes.xml'):
if name in parts:
for paragraph in parts[name].iter(W + 'p'):
identifier = reference(paragraph.find(W + 'pPr'), 'pStyle')
if any(reference(s, 'name') == LIST_PARAGRAPH_STYLE for s in adapter.chain(identifier)):
adapter.apply(paragraph)
for run in parts[name].iter(W + 'r'):
identifier = reference(run.find(W + 'rPr'), 'rStyle')
if any(source_style_order(reference(s, 'name')) for s in adapter.chain(identifier)):
adapter.apply_run(run, 'paragraph')
for style in list(parts['word/styles.xml']):
if source_style_order(reference(style, 'name')): parts['word/styles.xml'].remove(style)
if source_style_order(reference(style, 'name')) or reference(style, 'name') == LIST_PARAGRAPH_STYLE:
parts['word/styles.xml'].remove(style)
for filename, root in parts.items():
_order_properties(root)
payloads[filename] = ET.tostring(root, encoding='UTF-8', xml_declaration=True, standalone=True)
+1 -1
View File
@@ -65,7 +65,7 @@ def _run_properties(rpr, rule):
if key in rule:
val(rpr, xml, int(rule[key]))
if key != 'strike': val(rpr, xml + 'Cs', int(rule[key]))
if 'font_color' in rule:
if 'font_color' in rule and rule['font_color'] != 'inherit':
color = child(rpr, "color")
color.attrib.clear()
color.set(W + "val", str(rule["font_color"]).lstrip("#"))
+6
View File
@@ -69,6 +69,12 @@ class MarkdownRenderer:
self.markdown.core.ruler.push("mdhelper_task_lists", self._convert_task_lists)
self.markdown.core.ruler.push("mdhelper_semantic_styles", self._mark_semantic_styles)
self.markdown.core.ruler.push("mdhelper_source_lines", self._add_source_lines)
# Table-cell margins have no layout effect. A content block gives the
# semantic paragraph spacing a real box without changing table padding.
for name in ('th_open', 'td_open'):
self.markdown.renderer.rules[name] = lambda tokens, idx, options, env: self.markdown.renderer.renderToken(tokens, idx, options, env) + '<div class="mdhelper-cell-paragraph">'
for name in ('th_close', 'td_close'):
self.markdown.renderer.rules[name] = lambda tokens, idx, options, env: '</div>' + self.markdown.renderer.renderToken(tokens, idx, options, env)
for name in ("fence", "code_block", "math_block"):
original = self.markdown.renderer.rules[name]
def mapped(tokens, idx, options, env, render=original):
+12 -1
View File
@@ -46,4 +46,15 @@ local function mark(items, stack)
end
return output
end
return {{Inlines=function(items) return mark(items, {}) end}}
local function list_paragraphs(list)
for _, item in ipairs(list.content) do
for index, block in ipairs(item) do
if block.t == 'Para' then
item[index] = pandoc.Div({block}, pandoc.Attr('', {}, {['custom-style']='MDHelperSourceListParagraph'}))
end
end
end
return list
end
return {{Inlines=function(items) return mark(items, {}) end},
{BulletList=list_paragraphs, OrderedList=list_paragraphs}}
+3 -3
View File
@@ -229,7 +229,7 @@ class DocumentStyleEditorDialog(QDialog):
form.addRow('每级列表缩进', self.level_indent_spin)
for edit in (self.background_edit, self.border_color_edit):
edit.editingFinished.connect(self._store_and_refresh)
self.color_combo = self._combo([("继承", None), ("自动(随主题)", "auto"), ("自定义…", "custom")])
self.color_combo = self._combo([("继承", None), ("随所在文字颜色", "inherit"), ("自动(随主题)", "auto"), ("自定义…", "custom")])
self.color_button = QPushButton("#23272f")
self.color_button.clicked.connect(self._choose_color)
form.addRow("字体颜色", self._row(self.color_combo, self.color_button))
@@ -421,7 +421,7 @@ class DocumentStyleEditorDialog(QDialog):
color = QColorDialog.getColor(QColor(self.color_button.text()), self, "字体颜色")
if color.isValid():
self.color_button.setText(color.name())
self.color_combo.setCurrentIndex(2)
self._select(self.color_combo, 'custom')
self._store_and_refresh()
def _apply_size_preset(self, *_: object) -> None:
@@ -624,7 +624,7 @@ class DocumentStyleEditorDialog(QDialog):
char.setFontUnderline(rule.get('underline', False))
char.setFontStrikeOut(rule.get('strike', False))
if str(rule.get('background_color', '')).startswith('#'): char.setBackground(QColor(rule['background_color']))
char.setForeground(QColor("#23272f" if rule["font_color"] == "auto" else rule["font_color"]))
char.setForeground(QColor("#23272f" if rule["font_color"] in ('auto', 'inherit') else rule["font_color"]))
char.setFontLetterSpacingType(QFont.SpacingType.AbsoluteSpacing)
char.setFontLetterSpacing(number(rule["letter_spacing"]) * scale)
cursor.insertText(part, char)
+63 -9
View File
@@ -63,6 +63,7 @@ ALIASES[_normalize_selector_text(SELECTORS["paragraph"])] = "paragraph"
FONT_VARIABLES = {"chinese_font_family": "--mdhelper-font-chinese", "english_font_family": "--mdhelper-font-english"}
FONT_EXPRESSION = "var(--mdhelper-font-english, var(--mdhelper-font-chinese, var(--reader-font-family))), var(--mdhelper-font-chinese, sans-serif)"
DECORATION_EXPRESSION = 'var(--mdhelper-text-decoration, none)'
LIST_PARAGRAPH = '_list_paragraph'
@dataclass
@@ -211,9 +212,40 @@ def _font_names(value):
return names
def _invalid_core_value(prop, tokens):
"""Reject definite invalid values; retain valid unsupported expressions."""
tokens = [t for t in tokens if t.type not in ('whitespace', 'comment')]
if not tokens or any(t.type == 'error' for t in tokens): return True
if len(tokens) != 1: return False
token = tokens[0]
wide = {'inherit', 'initial', 'unset', 'revert', 'revert-layer'}
if token.type == 'ident' and token.lower_value in wide: return False
lengths = {'font-size', 'line-height', 'letter-spacing', 'text-indent', 'padding', 'border-width',
'margin-top', 'margin-bottom', 'margin-left', 'margin-right'}
keywords = {
'font-size': {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large', 'xxx-large', 'larger', 'smaller', 'math'},
'line-height': {'normal'}, 'letter-spacing': {'normal'}, 'border-width': {'thin', 'medium', 'thick'},
'font-weight': {'normal', 'bold', 'bolder', 'lighter'}, 'font-style': {'normal', 'italic', 'oblique'},
**{f'margin-{side}': {'auto'} for side in ('top', 'bottom', 'left', 'right')},
}
if token.type == 'ident':
if prop in ('color', 'background-color', 'border-color'): return parse_color(token) is None
if prop in lengths or prop in keywords: return token.lower_value not in keywords.get(prop, set())
if prop in lengths and token.type in ('dimension', 'number', 'percentage'):
if token.value < 0 and prop not in ('letter-spacing', 'text-indent') and not prop.startswith('margin-'): return True
if token.type == 'number': return prop != 'line-height' and token.value != 0
if token.type == 'percentage': return prop not in ('font-size', 'line-height', 'text-indent', 'padding') and not prop.startswith('margin-')
units = {'px', 'pt', 'pc', 'in', 'cm', 'mm', 'q', 'em', 'rem', 'ex', 'rex', 'ch', 'rch', 'cap', 'rcap', 'ic', 'ric', 'lh', 'rlh',
'vw', 'vh', 'vi', 'vb', 'vmin', 'vmax', 'cqw', 'cqh', 'cqi', 'cqb', 'cqmin', 'cqmax'}
units.update(prefix + unit for prefix in ('s', 'l', 'd') for unit in ('vw', 'vh', 'vi', 'vb', 'vmin', 'vmax'))
return token.lower_unit not in units
if prop == 'font-weight' and token.type == 'number': return not 1 <= token.value <= 1000
return False
def _collect_cascade(source: str, result: Analysis):
"""Choose core declarations by importance, specificity and source order."""
winners = {target: {} for target in SELECTORS}
winners = {target: {} for target in (*SELECTORS, LIST_PARAGRAPH)}
for order, node in enumerate(css.parse_stylesheet(source, skip_comments=False, skip_whitespace=False)):
if node.type == "error":
result.errors.append(f"第 {node.source_line} 行:{node.message}")
@@ -228,7 +260,11 @@ def _collect_cascade(source: str, result: Analysis):
selector = _selector(part)
target = ALIASES.get(selector)
if target:
targets[target] = max(targets.get(target, (0, 0)), _specificity(selector))
direct = int(target != 'blockquote' or selector.endswith(' p'))
targets[target] = max(targets.get(target, (0, (0, 0))), (direct, _specificity(selector)))
if selector in ('p', '.reader p'):
for context in ('blockquote', LIST_PARAGRAPH):
targets[context] = max(targets.get(context, (0, (0, 0))), (1, _specificity(selector)))
else:
result.notes.append("其他选择器保留在 CSS 中")
declarations = css.parse_blocks_contents(node.content, skip_comments=False, skip_whitespace=False)
@@ -240,6 +276,11 @@ def _collect_cascade(source: str, result: Analysis):
result.errors.append(f"第 {raw.source_line} 行:{raw.name} 缺少属性值。")
continue
expanded = _expand(raw)
if any(d.type == 'declaration' and _property(d) in CORE_PROPERTIES and
_invalid_core_value(_property(d), d.value) for d in expanded):
# One invalid component invalidates the entire shorthand.
result.notes.append(f'已忽略无效的 {raw.lower_name}: {_text(raw.value)},沿用前面的有效声明')
continue
if raw.type in ("qualified-rule", "at-rule"):
result.notes.append("嵌套规则保留在 CSS 中")
if raw.type == "declaration" and raw.lower_name == "font" and len(expanded) == 1:
@@ -255,8 +296,8 @@ def _collect_cascade(source: str, result: Analysis):
result.notes.append("font 简写保留在 CSS 中;核心字体请使用 font-family/font-size 等属性")
if prop not in CORE_PROPERTIES:
continue
for target, specificity in targets.items():
rank = (declaration.important, specificity, order, position)
for target, (direct, specificity) in targets.items():
rank = (direct, declaration.important, specificity, order, position)
if prop not in winners[target] or rank >= winners[target][prop][0]:
winners[target][prop] = (rank, _text(declaration.value))
return winners
@@ -340,7 +381,9 @@ class _CoreRuleReader:
self.result.notes.append(f'{LABELS[self.target]}的 widows/orphans 仅保留为 CSS')
def read(self, prop, convert):
if prop not in self.props or self.props[prop].lower() in ('inherit', 'unset', 'revert'):
if prop not in self.props:
return
if self.props[prop].lower() in ('inherit', 'unset', 'revert') and prop != 'color':
return
try:
convert(self.props[prop])
@@ -367,7 +410,10 @@ class _CoreRuleReader:
self.rule.update(english_font_family=names[0], chinese_font_family=chinese)
def color(self, value):
if value.lower() in ('currentcolor', 'var(--reader-text-color, #23272f)'):
if value.lower() in ('currentcolor', 'inherit', 'unset'):
self.rule['font_color'] = 'inherit'
return
if value.lower() == 'var(--reader-text-color, #23272f)':
self.rule['font_color'] = 'auto'
return
rgba = parse_color(value)
@@ -420,7 +466,7 @@ def analyze_css(source: str, font_size_px: float = 16) -> Analysis:
return result
winners = _collect_cascade(source, result)
for target, entries in winners.items():
rule = _CoreRuleReader(target, entries, result, font_size_px).parse()
rule = _CoreRuleReader('paragraph' if target == LIST_PARAGRAPH else target, entries, result, font_size_px).parse()
if rule:
result.rules[target] = rule
result.notes = list(dict.fromkeys(result.notes))
@@ -522,7 +568,9 @@ def patch_core(source: str, target: str, before: dict, after: dict, *, reset=Fal
# This also avoids expanding a simple .reader p rule into a second block.
if marked:
canonical = next((node for node in reversed(output) if node.type == "qualified-rule" and
all(ALIASES.get(_selector(part)) == target for part in _split(node.prelude))), None)
all(ALIASES.get(_selector(part)) == target and
(target != 'blockquote' or _selector(part).endswith(' p'))
for part in _split(node.prelude))), None)
if canonical is not None:
content = css.serialize(canonical.content).rstrip() + "\n " + "\n ".join(marked) + "\n"
canonical.content = css.parse_component_value_list(content)
@@ -556,6 +604,12 @@ def render_css(source: str, rules: dict, font_family: str = '', font_size_px: fl
for key, rule in inherited.items():
declarations = _core_declarations(rule)
if declarations: helpers += '\n' + SELECTORS[key] + ' { ' + ' '.join(declarations) + ' }'
for key in ('table_head', 'table_cell'):
rule = {**inherited.get(key, {}), **rules.get(key, {})}
margins = {field: value for field, value in rule.items() if field.startswith(('space_before_', 'space_after_', 'left_indent_', 'right_indent_'))}
declarations = _core_declarations(margins)
if declarations:
helpers += '\n' + SELECTORS[key] + ' > .mdhelper-cell-paragraph { ' + ' '.join(declarations) + ' }'
# The legacy code rule also selects the inner <code>. Let the semantic
# block own its typography instead of leaving that old child rule in charge.
block = {**inherited.get('code_block', {}), **rules.get('code_block', {})}
@@ -598,7 +652,7 @@ def normalize_payload(payload: dict, fallback_name="自定义样式", font_size_
if metadata:
result.rules['_metadata'] = metadata
from .style_presets import DOCUMENT_STYLE_PRESETS
if supplied_rules.get('_preset') in DOCUMENT_STYLE_PRESETS:
if isinstance(supplied_rules.get('_preset'), str) and supplied_rules['_preset'] in DOCUMENT_STYLE_PRESETS:
result.rules['_preset'] = supplied_rules['_preset']
return {"name": str(payload.get("name") or fallback_name).strip() or fallback_name,
"css_sync_version": 1, "css": source,