fix: preserve per-property inheritance and semantic emphasis

This commit is contained in:
2026-10-30 11:42:18 +08:00
parent 151b176c1a
commit 88e3fe9e2b
7 changed files with 163 additions and 21 deletions
+25 -16
View File
@@ -44,15 +44,26 @@ def _delta(current, base, authored=None):
'keepNext': ('keep_with_next',), 'keepLines': ('keep_lines_together',), 'pageBreakBefore': ('page_break_before',),
'widowControl': ('widow_control',), 'contextualSpacing': ('contextual_spacing',)}
for node in list(current):
if any(field in authored for field in fields.get(ET.QName(node).localname, ())): continue
old = base.find(node.tag)
if old is not None and node.attrib == old.attrib and node.text == old.text and not len(node) and not len(old):
current.remove(node)
elif old is not None and node.tag in {W + 'rFonts', W + 'spacing', W + 'ind'}:
compound = {
'rFonts': {'ascii': ('english_font_family',), 'hAnsi': ('english_font_family',),
'cs': ('english_font_family',), 'eastAsia': ('chinese_font_family',)},
'spacing': {**{attr: (f'space_{side}_value', f'space_{side}_unit')
for side in ('before', 'after') for attr in (side, side + 'Lines', side + 'Autospacing')},
'line': ('line_height_value', 'line_spacing_mode'), 'lineRule': ('line_height_value', 'line_spacing_mode')},
'ind': {**{attr: (f'{side}_indent_value', f'{side}_indent_unit')
for side in ('left', 'right') for attr in (side, side + 'Chars')},
**{attr: ('indent_mode', 'indent_value') for attr in ('firstLine', 'firstLineChars', 'hanging', 'hangingChars')}},
}.get(ET.QName(node).localname)
if old is not None and compound and not (node.tag == W + 'spacing' and current.tag == W + 'rPr'):
# These properties merge attribute by attribute in Word.
for key in list(node.attrib):
if old.get(key) == node.get(key): del node.attrib[key]
explicit = any(field in authored for field in compound.get(ET.QName(key).localname, ()))
if not explicit and old.get(key) == node.get(key): del node.attrib[key]
if not node.attrib and not len(node): current.remove(node)
elif not any(field in authored for field in fields.get(ET.QName(node).localname, ())):
if old is not None and node.attrib == old.attrib and node.text == old.text and not len(node) and not len(old):
current.remove(node)
class WordStyles:
@@ -158,17 +169,6 @@ class WordStyles:
_run_properties(props, merged)
_run_properties(old, self.character_rule(keys[0]))
_delta(props, old)
# Word XORs style-level emphasis with the paragraph's emphasis. A named
# context variant compensates for that (e.g. **text** in a bold heading),
# keeping all formatting editable in the Styles panel, not on each run.
compensate = [field for field in ('bold', 'italic', 'strike') if field in merged and self.effective[paragraph_target].get(field)]
if compensate:
context_id = identifier + 'In' + style_id(paragraph_target)[8:]
if context_id not in self.created:
style = self.new(context_id, 'character', 'MDHelper ' + '+'.join(style_name(k, self.rules) for k in keys) + '(' + style_name(paragraph_target, self.rules) + ')', identifier)
for field in compensate:
for tag in {'bold': ('b', 'bCs'), 'italic': ('i', 'iCs'), 'strike': ('strike',)}[field]: val(child(style, 'rPr'), tag, int(not merged[field]))
identifier = context_id
return identifier
def syntax_style(self, run_id, target):
@@ -311,6 +311,15 @@ class WordStyles:
remove_fields(rpr, RUN_FIELDS)
if identifier: val(rpr, 'rStyle', identifier)
else: remove_fields(rpr, ('rStyle',))
# Word character-style emphasis XORs with paragraph emphasis. Protect
# only explicit semantic emphasis; fonts, sizes, colors and spacing stay
# style-driven. This is an intentional export contract, not a style copy.
merged = {}
for key in ('link', 'strong', 'emphasis', 'strike', 'inline_code'):
if key in keys: merged.update(self.character_rule(key))
for field, tags in (('bold', ('b', 'bCs')), ('italic', ('i', 'iCs')), ('strike', ('strike',))):
if field in merged:
for tag in tags: val(rpr, tag, int(merged[field]))
def apply(self, document):
for paragraph in document.iter(W + 'p'):
+16 -2
View File
@@ -33,7 +33,7 @@ PROPERTIES = {
"fonts": {"font-family", "--mdhelper-font-chinese", "--mdhelper-font-english"},
"size": {"font-size"}, "bold": {"font-weight"}, "italic": {"font-style"}, "color": {"color"},
"tracking": {"letter-spacing"}, "align": {"text-align"},
'decoration': {'text-decoration', 'text-decoration-line'}, 'background': {'background-color'},
'decoration': {'text-decoration', 'text-decoration-line', '--mdhelper-underline', '--mdhelper-strike'}, 'background': {'background-color'},
'border_color': {'border-color'}, 'border_width': {'border-width', 'border-style'}, 'padding': {'padding'},
'marker': {'list-style-type'}, 'level_indent': {'--mdhelper-list-level-indent'},
"line": {"line-height", "--mdhelper-line-spacing-mode"}, "indent": {"text-indent"},
@@ -62,6 +62,7 @@ ALIASES.update({'strong': 'strong', 'em': 'emphasis', 's': 'strike', 'del': 'str
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)'
@dataclass
@@ -301,6 +302,10 @@ class _CoreRuleReader:
return self.rule
def decoration(self, value):
if re.sub(r'\s+', '', value) == re.sub(r'\s+', '', DECORATION_EXPRESSION):
for key in ('underline', 'strike'):
self.choice('--mdhelper-' + key, key, {'true': True, 'false': False})
return
parts = value.split()
if not parts or not set(parts) <= {'none', 'underline', 'line-through'}: raise ValueError
self.rule.update(underline='underline' in parts, strike='line-through' in parts)
@@ -426,7 +431,10 @@ def analyze_css(source: str, font_size_px: float = 16) -> Analysis:
def _core_declarations(rule):
declarations = [d for d in css_declarations(rule) if not d.startswith(("font-family:", "padding-left:"))]
declarations = [d for d in css_declarations(rule) if not d.startswith(("font-family:", "padding-left:", 'text-decoration-line:'))]
if 'underline' in rule or 'strike' in rule:
declarations.extend(f'--mdhelper-{key}: {str(rule[key]).lower()};' for key in ('underline', 'strike') if key in rule)
declarations.append(f'text-decoration-line: {DECORATION_EXPRESSION};')
if any(rule.get(key) for key in FONT_VARIABLES):
for key, variable in FONT_VARIABLES.items():
if rule.get(key):
@@ -541,6 +549,12 @@ def render_css(source: str, rules: dict, font_family: str = '', font_size_px: fl
contextual = {key: {"contextual_spacing": True} for key, rule in rules.items() if isinstance(rule, dict) and rule.get("contextual_spacing")}
helpers = build_document_style_css(contextual)
helpers += '\n' + build_document_style_css(inherited)
# Independent flags retain their inherited counterpart. Literal CSS such as
# text-decoration-line:none still wins over this opt-in variable expression.
for key, rule in effective.items():
if any(field in rules.get(key, {}) or field in inherited.get(key, {}) for field in ('underline', 'strike')):
decoration = ' '.join(token for field, token in (('underline', 'underline'), ('strike', 'line-through')) if rule.get(field)) or 'none'
helpers += '\n' + SELECTORS[key] + ' { --mdhelper-text-decoration: ' + decoration + '; }'
paragraph = rules.get("paragraph", {})
if paragraph.get("font_size"):
helpers += f"\n.reader {{ --reader-math-font-size: {fmt(paragraph['font_size'])}{paragraph.get('font_size_unit', 'px')}; }}"