fix: align reader and Word inheritance and nested formatting

This commit is contained in:
2026-10-30 12:04:51 +08:00
parent 88e3fe9e2b
commit df1fb2140f
10 changed files with 254 additions and 24 deletions
+91 -2
View File
@@ -12,6 +12,13 @@ from mdhelper.style_sync import normalize_payload, render_css
from mdhelper.markdown_renderer import MarkdownRenderer
from docx_assertions import effective_document
UNIT_RULES = {'h1': {'font_size': 12, 'font_size_unit': 'pt', 'left_indent_value': 2, 'left_indent_unit': 'em',
'space_before_value': .5, 'space_before_unit': 'line'},
'h2': {'left_indent_value': 20, 'left_indent_unit': 'pt', 'space_before_value': 0, 'space_before_unit': 'pt'},
'_metadata': {'h2': {'based_on': 'h1'}}}
NESTED_SOURCE = '**[InnerLink](https://example.com)** and [**InnerBold**](https://example.com) and [**`InlineCode`**](https://example.com)'
NESTED_RULES = {'strong': {'font_color': '#ff0000'}, 'link': {'font_color': '#0000ff'}}
PARTIAL_RULES = {
'h1': {'chinese_font_family': 'SimSun', 'english_font_family': 'Arial', 'font_size': 12, 'font_size_unit': 'pt',
'space_after_value': 8, 'space_after_unit': 'pt', 'line_height_value': 1.5, 'line_spacing_mode': 'multiple',
@@ -52,8 +59,8 @@ def test_word_inherits_other_attributes_when_one_attribute_is_explicit(tmp_path,
child = styles.find("w:style[@w:styleId='MDHelperH2']", NS)
assert child.find('w:rPr/w:rFonts', NS).get(W + 'eastAsia') is None
assert child.find('w:rPr/w:rFonts', NS).get(W + 'ascii') == 'Courier New'
assert set(child.find('w:pPr/w:spacing', NS).attrib) == {W + 'before'}
assert set(child.find('w:pPr/w:ind', NS).attrib) == {W + 'right'}
assert set(child.find('w:pPr/w:spacing', NS).attrib) == {W + key for key in ('before', 'beforeLines', 'beforeAutospacing')}
assert set(child.find('w:pPr/w:ind', NS).attrib) == {W + 'right', W + 'rightChars'}
base.find('w:rPr/w:rFonts', NS).set(W + 'eastAsia', 'KaiTi')
base.find('w:pPr/w:spacing', NS).set(W + 'after', '480')
rendered = effective_document(doc, styles)
@@ -95,3 +102,85 @@ def test_graphical_decoration_preserves_inherited_counterpart(qt_application, tm
dialog.bool_boxes[other].setCheckState(Qt.CheckState.Unchecked)
assert dialog.style_payload()['rules'][key][other] is False
finally: dialog.close()
@pytest.mark.parametrize('engine', ['builtin', 'python-docx', 'pandoc'])
def test_word_unit_switch_clears_inherited_character_and_line_units(tmp_path, engine):
path = export_markdown_to_docx('# Parent\n\n## ChildUnits', tmp_path / 'units.docx', engine=engine, style_rules=UNIT_RULES)
doc, styles = parts(path)
p = next(p for p in effective_document(doc, styles).iter(W + 'p') if 'ChildUnits' in ''.join(p.itertext()))
ind, spacing = p.find('w:pPr/w:ind', NS), p.find('w:pPr/w:spacing', NS)
assert ind.get(W + 'left') == '400' and ind.get(W + 'leftChars') == '0'
assert spacing.get(W + 'before') == spacing.get(W + 'beforeLines') == '0'
def test_reader_separate_language_font_inheritance(qt_application, tmp_path):
payload = normalize_payload({'rules': {'h1': {'english_font_family': 'Arial'}, 'h2': {'chinese_font_family': 'SimSun'}, '_metadata': {'h2': {'based_on': 'h1'}}}})
font = browser(qt_application, tmp_path, payload, '## Child', "getComputedStyle(document.querySelector('h2')).fontFamily")
assert font.startswith('Arial, SimSun')
def test_reader_clear_list_base_and_keep_own_overrides(qt_application, tmp_path):
payload = normalize_payload({'rules': {'list': {'font_color': '#ff0000', 'bold': True, 'background_color': '#ffff00', 'list_marker': 'upper-roman'},
'list_bullet': {'italic': True}, '_metadata': {'list_bullet': {'based_on': ''}}}})
actual = browser(qt_application, tmp_path, payload, '- Item', "(()=>{const s=getComputedStyle(document.querySelector('li'));return [s.color,s.fontWeight,s.fontStyle,s.backgroundColor,s.listStyleType]})()")
assert actual == ['rgb(35, 39, 47)', '400', 'italic', 'rgba(0, 0, 0, 0)', 'disc']
# Legacy configurations without metadata still inherit the list baseline.
payload = normalize_payload({'rules': {'list': {'font_color': '#ff0000', 'bold': True}}})
assert browser(qt_application, tmp_path, payload, '- Item', "getComputedStyle(document.querySelector('li')).color") == 'rgb(255, 0, 0)'
@pytest.mark.parametrize('points', [10, 60])
def test_reader_nested_list_indent_uses_own_core_setting(qt_application, tmp_path, points):
payload = normalize_payload({'rules': {'list_bullet': {'level_indent': points}}})
padding = browser(qt_application, tmp_path, payload, '- Outer\n - Inner', "parseFloat(getComputedStyle(document.querySelector('li > ul')).paddingLeft)")
assert padding == pytest.approx(points * 4/3, abs=.01)
@pytest.mark.parametrize('css,expected', [
('a {text-decoration-line:underline; text-decoration:none;}', False),
('a {text-decoration:underline !important; text-decoration-line:none;}', True),
('.reader a {text-decoration:none;} a {text-decoration-line:underline;}', False),
])
def test_decoration_shorthand_obeys_cascade_in_browser_controls_and_word(qt_application, tmp_path, css, expected):
payload = normalize_payload({'css': css})
assert payload['rules']['link']['underline'] is expected
actual = browser(qt_application, tmp_path, payload, '[Link](#link)', "getComputedStyle(document.querySelector('p a')).textDecorationLine")
assert ('underline' in actual) is expected
dialog = DocumentStyleEditorDialog(payload)
try:
dialog.select_target('link')
assert dialog.bool_boxes['underline'].isChecked() is expected
finally: dialog.close()
path = export_markdown_to_docx('[Link](https://example.com)', tmp_path / 'decoration.docx', style_rules=payload['rules'])
_, styles = parts(path)
assert styles.find("w:style[@w:styleId='MDHelperLink']/w:rPr/w:u", NS).get(W + 'val') == ('single' if expected else 'none')
@pytest.mark.parametrize('engine', ['builtin', 'python-docx', 'pandoc'])
def test_word_retains_nested_inline_order_and_styles_remain_editable(tmp_path, engine):
path = export_markdown_to_docx(NESTED_SOURCE, tmp_path / 'nested.docx', engine=engine, style_rules=NESTED_RULES)
doc, styles = parts(path)
assert not any((s.find(W + 'name').get(W + 'val', '') if s.find(W + 'name') is not None else '').startswith('MDHelperSource_') for s in styles)
def color(word):
rendered = effective_document(doc, styles)
run = next(r for r in rendered.iter(W + 'r') if word in ''.join(r.itertext()))
return run.find('w:rPr/w:color', NS).get(W + 'val')
assert color('InnerLink') == '0000ff' and color('InnerBold') == 'ff0000'
code = next(r for r in effective_document(doc, styles).iter(W + 'r') if 'InlineCode' in ''.join(r.itertext()))
assert code.find('w:rPr/w:rFonts', NS).get(W + 'ascii') == 'Consolas'
styles.find("w:style[@w:styleId='MDHelperLink']/w:rPr/w:color", NS).set(W + 'val', '008800')
assert color('InnerLink') == '008800' and color('InnerBold') == 'ff0000'
def test_pandoc_footnotes_and_equations_survive_semantic_annotation(tmp_path):
source = 'Math $x^2$ and a note[^1].\n\n[^1]: **[Link](https://example.com)** and `code`.'
path = export_markdown_to_docx(source, tmp_path / 'notes.docx', engine='pandoc', style_rules=NESTED_RULES)
with zipfile.ZipFile(path) as z:
document = ET.fromstring(z.read('word/document.xml')); notes = ET.fromstring(z.read('word/footnotes.xml'))
styles = ET.fromstring(z.read('word/styles.xml')); ids = {s.get(W + 'styleId') for s in styles}
assert document.find('.//{http://schemas.openxmlformats.org/officeDocument/2006/math}oMath') is not None
assert document.find('.//w:footnoteReference', NS) is not None
assert document.find(".//w:rStyle[@w:val='FootnoteReference']", NS) is not None
assert all(ref.get(W + 'val') in ids for ref in notes.findall('.//w:rStyle', NS))
assert notes.find('.//w:hyperlink', NS) is not None
+17 -1
View File
@@ -11,12 +11,14 @@ sys.path.insert(0, str(Path('tests').resolve()))
from test_word_named_styles import SOURCE
from mdhelper.docx_exporter import export_markdown_to_docx
from mdhelper.style_catalog import style_name
from test_style_regressions import PARTIAL_RULES
from test_style_regressions import PARTIAL_RULES, UNIT_RULES, NESTED_SOURCE, NESTED_RULES
folder = Path(tempfile.mkdtemp(prefix='MDHelper-Word-Styles-'))
rules = {'h2': {'bold': False}, '_metadata': {'h2': {'based_on': 'h1'}}}
for engine in ('builtin', 'python-docx', 'pandoc'):
export_markdown_to_docx(SOURCE + '\n\n## Child title', folder / (engine + '.docx'), engine=engine, style_rules=rules)
export_markdown_to_docx('# Parent\n\n## Child', folder / (engine + '-partial.docx'), engine=engine, style_rules=PARTIAL_RULES)
export_markdown_to_docx('# Parent\n\n## ChildUnits', folder / (engine + '-units.docx'), engine=engine, style_rules=UNIT_RULES)
export_markdown_to_docx(NESTED_SOURCE, folder / (engine + '-nested.docx'), engine=engine, style_rules=NESTED_RULES)
(folder / 'names.json').write_text(json.dumps({key: 'MDHelper ' + style_name(key) for key in ('paragraph', 'strong', 'link', 'h1')}), encoding='utf-8')
print(folder)
'@ | & $Python -B -).Trim()
@@ -65,6 +67,20 @@ print(folder)
}
Write-Output "$engine passed: partial overrides preserve inheritance of fonts, spacing and indents."
} finally { $doc.Close(0); [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($doc) }
$doc = $word.Documents.Open((Join-Path $testDirectory "$engine-units.docx"), $false, $true)
try {
$range = $doc.Content.Duplicate; [void]$range.Find.Execute('ChildUnits')
if ($range.ParagraphFormat.LeftIndent -ne 20 -or $range.ParagraphFormat.SpaceBefore -ne 0) { throw "$engine child units did not override parent units." }
} finally { $doc.Close(0); [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($doc) }
$doc = $word.Documents.Open((Join-Path $testDirectory "$engine-nested.docx"), $false, $true)
try {
$link = $doc.Content.Duplicate; [void]$link.Find.Execute('InnerLink')
$bold = $doc.Content.Duplicate; [void]$bold.Find.Execute('InnerBold')
if ($link.Font.Color -ne 16711680 -or $bold.Font.Color -ne 255) { throw "$engine lost inline nesting order." }
$doc.Styles.Item($names.link).Font.Color = 65280
if ($link.Font.Color -ne 65280 -or $bold.Font.Color -ne 255) { throw "$engine lost shared link style or inner override." }
Write-Output "$engine passed: child units, nested colors and shared style updates."
} finally { $doc.Close(0); [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($doc) }
}
} finally {
if ($word) { $word.Quit(); [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($word) }