fix: align nested Word blocks and synchronize CSS and heading navigation

This commit is contained in:
2026-11-05 12:11:42 +08:00
parent b3a0907e1a
commit 36f0d7856e
15 changed files with 383 additions and 96 deletions
+63
View File
@@ -0,0 +1,63 @@
"""CSS reset/grammar parity, graphical roundtrips and ancestor suppression."""
import pytest
from PySide6.QtCore import Qt
from mdhelper.style_sync import normalize_payload, analyze_css, patch_core
from mdhelper.style_dialog import DocumentStyleEditorDialog
from mdhelper.docx_exporter import export_markdown_to_docx
from mdhelper.docx_style import W, NS
from test_style_regressions import browser, parts
from docx_assertions import effective_document
@pytest.mark.parametrize('declaration', ['text-decoration:unset','text-decoration-line:UNSET','text-decoration:initial'])
def test_resets_disable_link_and_strike_core_styles(qt_application,tmp_path,declaration):
payload=normalize_payload({'css':f'a{{{declaration}}} s{{{declaration}}}'})
for key in ('link','strike'):
assert payload['rules'][key]['underline'] is False and payload['rules'][key]['strike'] is False
assert normalize_payload(payload)==payload
assert browser(qt_application,tmp_path,payload,'[Link](#x) ~~Strike~~',
"[...document.querySelectorAll('a,s')].map(e=>getComputedStyle(e.querySelector('[data-mdh-text]')||e).textDecorationLine)")==['none','none']
@pytest.mark.parametrize('engine', ['builtin','python-docx','pandoc'])
def test_css_resets_and_uppercase_reach_word(tmp_path,engine):
payload=normalize_payload({'css':'a{text-decoration:unset}s{text-decoration:unset}strong{text-decoration:UNDERLINE}p{line-height:NORMAL}'})
doc,styles=parts(export_markdown_to_docx('[Link](#x) ~~Strike~~ **Bold**',tmp_path/'reset.docx',engine=engine,style_rules=payload['rules']))
rendered=effective_document(doc,styles)
for r in rendered.iter(W+'r'):
text=''.join(r.itertext())
if text in ('Link','Strike','Bold'):
assert r.find('w:rPr/w:u',NS).get(W+'val')==('single' if text=='Bold' else 'none')
if text=='Strike': assert r.find('w:rPr/w:strike',NS).get(W+'val')=='0'
assert rendered.find('.//w:pPr/w:spacing',NS).get(W+'line')=='240'
@pytest.mark.parametrize('invalid', ['italic 30pt inherit','italic 30pt Arial, unset','oblique 200deg 30pt Arial','oblique -200deg 30pt Arial'])
def test_invalid_font_keeps_previous_declarations(qt_application,tmp_path,invalid):
payload=normalize_payload({'css':f'p{{font-size:20pt;font-style:normal;font:{invalid}}}'})
assert payload['rules']['paragraph']['font_size']==20 and payload['rules']['paragraph']['italic'] is False
assert any('已忽略无效' in note for note in analyze_css(payload['css']).notes)
result=browser(qt_application,tmp_path,payload,'Text',"[getComputedStyle(document.querySelector('p')).fontSize,getComputedStyle(document.querySelector('p')).fontStyle]")
assert abs(float(result[0][:-2])-20*96/72)<.01 and result[1]=='normal'
def test_uppercase_and_reset_controls_roundtrip(qt_application):
dialog=DocumentStyleEditorDialog({'css':'p{text-decoration:UNDERLINE;line-height:NORMAL;letter-spacing:NORMAL}'})
try:
assert dialog.bool_boxes['underline'].checkState()==Qt.CheckState.Checked
dialog.bool_boxes['underline'].setCheckState(Qt.CheckState.Unchecked)
assert analyze_css(dialog.style_payload()['css']).rules['paragraph']['underline'] is False
dialog.extra_css_edit.setPlainText('p{text-decoration:UNSET}')
assert dialog.style_payload()['rules']['paragraph']['underline'] is False
assert dialog.bool_boxes['underline'].checkState()==Qt.CheckState.Unchecked
finally:dialog.close()
@pytest.mark.parametrize('selector', ['#mdhelper-reader a','#mdhelper-reader.reader a',':is(#mdhelper-reader) a'])
def test_high_specificity_important_ancestor_does_not_paint_over_inner_toggle(qt_application,tmp_path,selector):
css=selector+'{text-decoration:underline line-through!important}'
css=patch_core(css,'emphasis',{}, {'underline':False})
payload=normalize_payload({'css':css})
result=browser(qt_application,tmp_path,payload,'[Outer *Inner*](#x)',
"[getComputedStyle(document.querySelector('a')).textDecorationLine,...[...document.querySelectorAll('[data-mdh-text]')].map(e=>getComputedStyle(e).textDecorationLine)]")
assert result==['none','underline line-through','line-through']
+6 -2
View File
@@ -106,7 +106,10 @@ def test_word_preserves_all_settings_and_content(tmp_path: Path, engine):
assert spacing.get(W + "before") == spacing.get(W + "after") == "0"
assert spacing.get(W + "line") == "400" and spacing.get(W + "lineRule") == "exact"
ind = ppr.find(W + "ind")
assert ind.get(W + "firstLineChars") == "200" and ind.get(W + "right") == "120"
# List geometry uses absolute lengths so Word's document grid cannot
# shift code/heading continuations away from their list's text column.
assert ind.get(W + "firstLineChars") == ("0" if ppr.find(W + 'numPr') is not None else "200")
assert ind.get(W + "firstLine") == "420" and ind.get(W + "right") == "120"
assert ind.get(W + "left") == "850"
for name, value in (("keepNext", "1"), ("keepLines", "1"), ("contextualSpacing", "1"), ("pageBreakBefore", "0"), ("widowControl", "0")):
assert ppr.find(W + name).get(W + "val") == value
@@ -181,4 +184,5 @@ def test_pandoc_style_processing_preserves_math_links_and_numbering(tmp_path):
levels = xml.findall(".//w:pPr[w:numPr]", NS)
nested = [p for p in levels if p.find("w:numPr/w:ilvl", NS).get(W + "val") == "1"]
assert nested and int(nested[0].find(W + "ind").get(W + "left")) > 720
assert nested[0].find(W + "ind").get(W + "leftChars") == "500"
assert nested[0].find(W + "ind").get(W + "leftChars") == "0"
assert nested[0].find(W + "ind").get(W + "left") == "1200"
+25
View File
@@ -0,0 +1,25 @@
import pytest
from mdhelper.markdown_utils import extract_headings_from_text, heading_locations
from mdhelper.markdown_renderer import MarkdownRenderer
from mdhelper.markdown_editor import MarkdownEditorDialog
@pytest.mark.parametrize('source,expected', [
('````markdown\n```\n# Fake\n````\n\n# Real',[('real',5)]),
('Title\n====\n\nBody',[('title',0)]),
('> # Quoted\n\n1. ### Listed',[('quoted',0),('listed',2)]),
(' # Fake\n\n# Real',[('real',2)]),
('# Same\n\nSame\n----\n\n> # Same',[('same',0),('same-2',2),('same-3',5)]),
('$$\n# Fake\n$$\n\n# Real',[('real',4)]),
])
def test_outline_reader_and_editor_use_identical_headings(qt_application,tmp_path,source,expected):
renderer=MarkdownRenderer(tmp_path);env={};renderer.markdown.parse(source,env)
assert [h.slug for h in extract_headings_from_text(source)]==[h['slug'] for h in env['headings']]
assert [(h.slug,line) for h,line in heading_locations(source)]==expected
editor=MarkdownEditorDialog(tmp_path/'note.md',source,renderer,'light',1,'',16)
try:
for slug,line in expected:
assert editor.scroll_to_heading(slug)
assert editor.editor.textCursor().blockNumber()==line
assert editor._heading_line_for_slug('fake') is None
finally:editor.close();editor.deleteLater()
+52
View File
@@ -0,0 +1,52 @@
"""Nested block geometry and editable style inheritance in all Word engines."""
import pytest
from mdhelper.docx_exporter import export_markdown_to_docx
from mdhelper.docx_style import W, NS
from test_style_regressions import parts
from docx_assertions import effective_document
ENGINES = ('builtin','python-docx','pandoc')
CONTINUED = '1. FirstText\n\n ContinuedText\n\n ### ContinuedHeading\n\n ```text\n CodeFirst\n CodeSecond\n ```\n\n2. LastText'
CODE = '1. ```text\n CodeFirst\n CodeSecond\n ```\n\n2. LastText'
QUOTE = '> ### QuotedHeading\n>\n> ```text\n> QuotedCode\n> ```\n>\n> > ### InnerHeading'
@pytest.mark.parametrize('engine', ENGINES)
def test_continuations_cancel_hanging_and_preserve_parent_styles(tmp_path, engine):
doc, styles = parts(export_markdown_to_docx(CONTINUED,tmp_path/'continued.docx',engine=engine))
effective = effective_document(doc,styles)
for p in effective.iter(W+'p'):
text = ''.join(p.itertext())
if text.startswith(('Continued','Code')):
ind=p.find('w:pPr/w:ind',NS)
assert int(ind.get(W+'left')) == 480
assert ind.get(W+'hanging','0') == ind.get(W+'hangingChars','0') == '0'
assert p.find('w:pPr/w:numPr',NS) is None
heading = next(p for p in doc.iter(W+'p') if ''.join(p.itertext()) == 'ContinuedHeading')
style_id=heading.find('w:pPr/w:pStyle',NS).get(W+'val')
assert 'ListOrdered' in style_id and 'Continuation' in style_id
styles.find("w:style[@w:styleId='MDHelperH3']/w:rPr/w:color",NS).set(W+'val','ff0000')
heading=next(p for p in effective_document(doc,styles).iter(W+'p') if ''.join(p.itertext()) == 'ContinuedHeading')
assert heading.find('w:r/w:rPr/w:color',NS).get(W+'val') == 'ff0000'
assert not any(a.startswith('{urn:mdhelper:source}') for el in doc.iter() for a in el.attrib)
@pytest.mark.parametrize('engine', ENGINES)
def test_multiline_code_remains_one_numbered_paragraph(tmp_path, engine):
doc, _ = parts(export_markdown_to_docx(CODE,tmp_path/'code.docx',engine=engine))
code = next(p for p in doc.iter(W+'p') if 'CodeFirst' in ''.join(p.itertext()))
assert 'CodeSecond' in ''.join(code.itertext()) and code.find('.//w:br',NS) is not None
assert code.find('w:pPr/w:numPr',NS) is not None
@pytest.mark.parametrize('engine', ENGINES)
def test_quote_blocks_keep_container_depth_and_editable_heading_base(tmp_path, engine):
doc, styles = parts(export_markdown_to_docx(QUOTE,tmp_path/'quote.docx',engine=engine))
rendered=effective_document(doc,styles)
for p in rendered.iter(W+'p'):
text=''.join(p.itertext())
if text in ('QuotedHeading','QuotedCode','InnerHeading'):
assert int(p.find('w:pPr/w:ind',NS).get(W+'left')) == (600 if text=='InnerHeading' else 300)
styles.find("w:style[@w:styleId='MDHelperH3']/w:rPr/w:sz",NS).set(W+'val','40')
for p in effective_document(doc,styles).iter(W+'p'):
if 'Heading' in ''.join(p.itertext()): assert p.find('w:r/w:rPr/w:sz',NS).get(W+'val')=='40'
+52
View File
@@ -8,9 +8,15 @@ import sys,tempfile
from pathlib import Path
sys.path.insert(0,str(Path('tests').resolve()))
from test_content_revision_057 import *
from test_style_revision_057 import CONTINUED,CODE,QUOTE
from mdhelper.style_sync import normalize_payload
folder=Path(tempfile.mkdtemp(prefix='MDHelper-057-Word-'))
for engine in ('builtin','python-docx','pandoc'):
export_markdown_to_docx(TABLE_LIST,folder/f'{engine}-table.docx',engine=engine)
for name,source in [('continued',CONTINUED),('code',CODE),('quote',QUOTE)]:
export_markdown_to_docx(source,folder/f'{engine}-{name}.docx',engine=engine)
rules=normalize_payload({'css':'a{text-decoration:unset}s{text-decoration:unset}strong{text-decoration:UNDERLINE}p{font-size:12pt;font:italic 30pt inherit;line-height:NORMAL}'})['rules']
export_markdown_to_docx('[Link](#x) ~~Strike~~ **Bold**',folder/f'{engine}-css.docx',engine=engine,style_rules=rules)
combined=batch.combine_documents([batch.BatchDocument(folder/'chapter.md',HEADING_LIST)],MarkdownRenderer(folder))
export_markdown_to_docx(combined.word_source,folder/'pandoc-combined.docx',engine='pandoc')
print(folder)
@@ -32,6 +38,32 @@ print(folder)
if($r.ListFormat.ListString.Trim() -ne '2.'){throw "$engine numbering restarted"}
Write-Output "$engine table content and numbering PASS"
} finally {$doc.Close(0)}
foreach($case in @('continued','code','quote','css')) {
$doc=$word.Documents.Open((Join-Path $folder "$engine-$case.docx"),$false,$true,$false)
try {
if($case -eq 'css') {
foreach($text in @('Link','Strike','Bold')) {
$r=$doc.Content.Duplicate;[void]$r.Find.Execute($text)
$expectedUnderline=if($text -eq 'Bold'){1}else{0}
if($r.Font.Underline -ne $expectedUnderline -or $r.Font.StrikeThrough -ne 0 -or $r.Font.Size -ne 12){throw "$engine CSS mismatch: $text"}
}
} else {
$doc.ExportAsFixedFormat((Join-Path $folder "$engine-$case.pdf"),17)
if($case -eq 'quote') {
$doc.Styles.Item('MDHelper 标题 3').Font.Size=20
foreach($text in @('QuotedHeading','InnerHeading')) {
$r=$doc.Content.Duplicate;[void]$r.Find.Execute($text)
if($r.Font.Size -ne 20){throw "$engine quote heading no longer inherits its base"}
}
} elseif($case -eq 'continued') {
$doc.Styles.Item('MDHelper 标题 3').Font.Color=255
$r=$doc.Content.Duplicate;[void]$r.Find.Execute('ContinuedHeading')
if($r.Font.Color -ne 255){throw "$engine list heading no longer inherits its base"}
}
}
Write-Output "$engine $case styles PASS"
} finally {$doc.Close(0)}
}
}
$doc=$word.Documents.Open((Join-Path $folder 'pandoc-combined.docx'),$false,$true,$false)
try {
@@ -41,6 +73,26 @@ print(folder)
}
Write-Output 'combined headings PASS'
} finally {$doc.Close(0)}
@'
import sys
from pathlib import Path
from pypdf import PdfReader
folder=Path(sys.argv[1])
for engine in ('builtin','python-docx','pandoc'):
for case in ('continued','code','quote'):
positions={}
def visit(text,cm,tm,font,size):
text=text.strip()
if text:positions[text]=tm[4]*cm[0]+tm[5]*cm[2]+cm[4]
for page in PdfReader(folder/f'{engine}-{case}.pdf').pages:page.extract_text(visitor_text=visit)
words={'continued':['FirstText','ContinuedText','ContinuedHeading','CodeFirst','CodeSecond','LastText'],
'code':['CodeFirst','CodeSecond','LastText'], 'quote':['QuotedHeading','QuotedCode']}[case]
values=[positions[word] for word in words]
assert max(values)-min(values)<.3,(engine,case,positions)
if case=='quote':assert abs(positions['InnerHeading']-positions['QuotedHeading']-15)<.3,(engine,positions)
print(engine,case,'actual Word PDF alignment PASS',positions)
'@ | & $Python -B - $folder
if($LASTEXITCODE -ne 0){throw 'Word PDF alignment failed'}
Write-Output "Fixtures: $folder"
} finally {
if($word){$word.Quit();[void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($word)}