feat: export editable named Word styles and release 0.5.0
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
"""Resolve the style cascade for appearance assertions; never modifies the DOCX."""
|
||||
from copy import deepcopy
|
||||
from lxml import etree as ET
|
||||
from mdhelper.docx_style import W, NS
|
||||
|
||||
|
||||
def effective_document(document, styles):
|
||||
result = deepcopy(document)
|
||||
by_id = {s.get(W + 'styleId'): s for s in styles.findall(W + 'style')}
|
||||
|
||||
def merge(target, source):
|
||||
if source is None: return
|
||||
for node in source:
|
||||
old = target.find(node.tag)
|
||||
if old is None: target.append(deepcopy(node))
|
||||
elif node.tag in {W + 'rFonts', W + 'spacing', W + 'ind'}: old.attrib.update(node.attrib)
|
||||
else:
|
||||
target.replace(old, deepcopy(node))
|
||||
|
||||
def resolve(identifier, tag, seen=()):
|
||||
result = ET.Element(W + tag)
|
||||
if identifier in seen or identifier not in by_id: return result
|
||||
style = by_id[identifier]
|
||||
parent = style.find(W + 'basedOn')
|
||||
if parent is not None: merge(result, resolve(parent.get(W + 'val'), tag, seen + (identifier,)))
|
||||
merge(result, style.find(W + tag))
|
||||
return result
|
||||
|
||||
for paragraph in result.iter(W + 'p'):
|
||||
direct = paragraph.find(W + 'pPr')
|
||||
if direct is None:
|
||||
direct = ET.Element(W + 'pPr'); paragraph.insert(0, direct)
|
||||
style = direct.find(W + 'pStyle')
|
||||
identifier = style.get(W + 'val') if style is not None else 'Normal'
|
||||
ppr = resolve(identifier, 'pPr')
|
||||
merge(ppr, direct)
|
||||
paragraph.replace(direct, ppr)
|
||||
for run in paragraph.iter(W + 'r'):
|
||||
direct = run.find(W + 'rPr')
|
||||
rpr = resolve(identifier, 'rPr')
|
||||
ref = direct.find(W + 'rStyle') if direct is not None else None
|
||||
if ref is not None:
|
||||
character = resolve(ref.get(W + 'val'), 'rPr')
|
||||
for tag in ('b', 'bCs', 'i', 'iCs', 'strike'):
|
||||
node, inherited = character.find(W + tag), rpr.find(W + tag)
|
||||
if node is not None and inherited is not None:
|
||||
on = lambda n: n.get(W + 'val', '1') not in ('0', 'false', 'off')
|
||||
node.set(W + 'val', str(int(on(node) != on(inherited))))
|
||||
merge(rpr, character)
|
||||
merge(rpr, direct)
|
||||
if direct is not None: run.replace(direct, rpr)
|
||||
else: run.insert(0, rpr)
|
||||
return result
|
||||
@@ -86,8 +86,10 @@ def test_dialog_legacy_px_and_no_duplicate_generated_css(app):
|
||||
|
||||
|
||||
def read_xml(path):
|
||||
from docx_assertions import effective_document
|
||||
with zipfile.ZipFile(path) as package:
|
||||
return ET.fromstring(package.read("word/document.xml")), ET.fromstring(package.read("word/styles.xml"))
|
||||
document, styles = ET.fromstring(package.read("word/document.xml")), ET.fromstring(package.read("word/styles.xml"))
|
||||
return effective_document(document, styles), styles
|
||||
|
||||
|
||||
@pytest.mark.parametrize("engine", ["builtin", "python-docx", "pandoc"])
|
||||
@@ -168,6 +170,8 @@ def test_pandoc_style_processing_preserves_math_links_and_numbering(tmp_path):
|
||||
path = export_markdown_to_docx(source, tmp_path / "semantic.docx", engine="pandoc", style_rules={"paragraph": RULE})
|
||||
with zipfile.ZipFile(path) as package:
|
||||
xml = ET.fromstring(package.read("word/document.xml"))
|
||||
from docx_assertions import effective_document
|
||||
xml = effective_document(xml, ET.fromstring(package.read('word/styles.xml')))
|
||||
rels = package.read("word/_rels/document.xml.rels").decode()
|
||||
assert xml.find(".//w:hyperlink", NS) is not None
|
||||
assert "https://openai.com" in rels
|
||||
|
||||
@@ -40,6 +40,8 @@ def test_word_page_settings_and_inline_styles(tmp_path, engine):
|
||||
style_rules={"paragraph": {"font_size": 14, "font_size_unit": "pt"}})
|
||||
with zipfile.ZipFile(path) as package:
|
||||
doc = etree.fromstring(package.read("word/document.xml"))
|
||||
from docx_assertions import effective_document
|
||||
doc = effective_document(doc, etree.fromstring(package.read('word/styles.xml')))
|
||||
ns = {"w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"}
|
||||
assert doc.xpath("//w:pgSz/@w:orient", namespaces=ns) == ["landscape"]
|
||||
assert int(doc.xpath("//w:pgSz/@w:w", namespaces=ns)[0]) > int(doc.xpath("//w:pgSz/@w:h", namespaces=ns)[0])
|
||||
|
||||
@@ -80,6 +80,8 @@ def test_word_export_preserves_cjk_bold_and_body_boundaries(tmp_path, engine):
|
||||
path = export_markdown_to_docx(SCREENSHOT_SOURCE, tmp_path / (engine + '.docx'), engine=engine)
|
||||
with zipfile.ZipFile(path) as package:
|
||||
root = ET.fromstring(package.read('word/document.xml'))
|
||||
from docx_assertions import effective_document
|
||||
root = effective_document(root, ET.fromstring(package.read('word/styles.xml')))
|
||||
ns = {'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'}
|
||||
all_text = ''.join(root.xpath('//w:t/text()', namespaces=ns))
|
||||
bold_text = ''.join(root.xpath('//w:r[w:rPr/w:b[not(@w:val="0")]]/w:t/text()', namespaces=ns))
|
||||
|
||||
@@ -20,6 +20,15 @@ def test_core_character_and_container_fields_roundtrip():
|
||||
assert normalize_payload(normalize_payload({'css': source}))['css'] == source
|
||||
|
||||
|
||||
def test_css_for_inapplicable_word_style_types_is_preserved_with_explanation():
|
||||
source = 'strong {margin-top: 3pt; color:red;} p {border-width:1pt; padding:4pt;}'
|
||||
payload = normalize_payload({'css': source})
|
||||
assert payload['css'] == source
|
||||
assert 'space_before_value' not in payload['rules']['strong']
|
||||
assert not payload['rules'].get('paragraph')
|
||||
assert analyze_css(source).notes
|
||||
|
||||
|
||||
def test_character_dialog_hides_paragraph_controls_and_preserves_other_types(qt_application):
|
||||
dialog = DocumentStyleEditorDialog({'rules': {'paragraph': {'alignment': 'justify'}}})
|
||||
try:
|
||||
|
||||
@@ -156,6 +156,8 @@ def test_css_edits_reach_word_via_saved_rules(tmp_path, engine):
|
||||
from lxml import etree
|
||||
with zipfile.ZipFile(docx) as archive:
|
||||
doc = etree.fromstring(archive.read("word/document.xml"))
|
||||
from docx_assertions import effective_document
|
||||
doc = effective_document(doc, etree.fromstring(archive.read('word/styles.xml')))
|
||||
ns = {"w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"}
|
||||
w = "{" + ns["w"] + "}"
|
||||
assert doc.find(".//w:sz", ns).get(w + "val") == "28"
|
||||
@@ -212,7 +214,7 @@ def test_style_file_roundtrip_reader_and_word_integration(app, tmp_path, monkeyp
|
||||
window.current_file = markdown
|
||||
docx_path = window.export_docx_to_path(tmp_path / 'test.docx')
|
||||
with zipfile.ZipFile(docx_path) as archive:
|
||||
xml = archive.read('word/document.xml').decode()
|
||||
xml = archive.read('word/styles.xml').decode()
|
||||
assert 'w:sz w:val="28"' in xml and 'w:color w:val="ff0000"' in xml
|
||||
finally:
|
||||
window.close()
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
import json
|
||||
import zipfile
|
||||
from lxml import etree as ET
|
||||
import pytest
|
||||
|
||||
from mdhelper.docx_exporter import export_markdown_to_docx
|
||||
from mdhelper.docx_semantic import style_id, RUN_FIELDS, PARAGRAPH_FIELDS
|
||||
from mdhelper.docx_style import W, NS
|
||||
from mdhelper.document_style import resolved_rules
|
||||
from mdhelper.style_sync import normalize_payload, render_css
|
||||
from docx_assertions import effective_document
|
||||
|
||||
SOURCE = '# Title **bold title**\n\nBody **strong** *emphasis* ~~strike~~ `code` [link](https://example.com) [**bold link**](https://example.com).\n\nSecond **strong second**.\n\n- Bullet\n\n1. Ordered\n\n - Nested\n\n- [ ] Task\n\n> Quote\n\n```python\nprint(1)\n```\n\n| Header | **Strong header** |\n|---|---|\n| Cell | Content |'
|
||||
|
||||
|
||||
def read_parts(path):
|
||||
with zipfile.ZipFile(path) as package:
|
||||
return {name: ET.fromstring(package.read(name)) for name in ('word/document.xml', 'word/styles.xml', 'word/_rels/document.xml.rels')}
|
||||
|
||||
|
||||
@pytest.mark.parametrize('engine', ['builtin', 'python-docx', 'pandoc'])
|
||||
def test_shared_named_styles_without_direct_format_overrides(tmp_path, engine):
|
||||
path = export_markdown_to_docx(SOURCE, tmp_path / 'named.docx', engine=engine)
|
||||
parts = read_parts(path); doc = parts['word/document.xml']; styles = parts['word/styles.xml']
|
||||
by_id = {s.get(W + 'styleId'): s for s in styles.findall(W + 'style')}
|
||||
for paragraph in doc.iter(W + 'p'):
|
||||
ppr = paragraph.find(W + 'pPr')
|
||||
assert all(ppr.find(W + field) is None for field in PARAGRAPH_FIELDS)
|
||||
assert ppr.find(W + 'pStyle').get(W + 'val') in by_id
|
||||
for run in doc.iter(W + 'r'):
|
||||
rpr = run.find(W + 'rPr')
|
||||
assert all(rpr.find(W + field) is None for field in RUN_FIELDS)
|
||||
ref = rpr.find(W + 'rStyle')
|
||||
if ref is not None: assert ref.get(W + 'val') in by_id
|
||||
paragraph_ids = {p.find('w:pPr/w:pStyle', NS).get(W + 'val') for p in doc.iter(W + 'p')}
|
||||
assert {style_id(k) for k in ('paragraph', 'h1', 'list_bullet', 'list_ordered', 'list_task', 'blockquote', 'code_block', 'table_head', 'table_cell')} <= paragraph_ids
|
||||
for key in ('strong', 'emphasis', 'strike', 'link', 'inline_code'):
|
||||
style = by_id[style_id(key)]
|
||||
assert style.get(W + 'type') == 'character'
|
||||
assert style.find('w:rPr/w:sz', NS) is None
|
||||
assert by_id[style_id('strong')].find('w:rPr/w:rFonts', NS) is None
|
||||
assert doc.find('.//w:hyperlink', NS) is not None
|
||||
assert any(e.get('Target') == 'https://example.com' for e in parts['word/_rels/document.xml.rels'])
|
||||
# Editing the shared body style reaches plain and strongly emphasized text.
|
||||
by_id[style_id('paragraph')].find('w:rPr/w:sz', NS).set(W + 'val', '46')
|
||||
effective = effective_document(doc, styles)
|
||||
for word in ('Body', 'strong second'):
|
||||
run = next(r for r in effective.iter(W + 'r') if word in ''.join(r.itertext()))
|
||||
assert run.find('w:rPr/w:sz', NS).get(W + 'val') == '46'
|
||||
# Combined styles inherit link color instead of baking it into every run.
|
||||
mixed = next(s for s in styles if 'MixLinkStrong' == s.get(W + 'styleId', '').removeprefix('MDHelper'))
|
||||
assert mixed.find('w:basedOn', NS).get(W + 'val') == style_id('link')
|
||||
assert mixed.find('w:rPr/w:color', NS) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize('engine', ['builtin', 'python-docx', 'pandoc'])
|
||||
def test_inheritance_metadata_and_character_overrides_survive_export(tmp_path, engine):
|
||||
rules = {'h1': {'font_size': 28, 'font_size_unit': 'pt', 'font_color': '#123456'},
|
||||
'h2': {'alignment': 'center'}, 'link': {'underline': False, 'font_color': '#ff0000'},
|
||||
'strong': {'font_color': '#008800'},
|
||||
'_metadata': {'h2': {'name': '子章节', 'based_on': 'h1'}, 'emphasis': {'based_on': 'strong'}}}
|
||||
payload = normalize_payload(json.loads(json.dumps({'rules': rules})))
|
||||
path = export_markdown_to_docx('# One\n\n## Two\n\n[link](https://example.com) *emphasized*', tmp_path / 'inherit.docx', engine=engine, style_rules=payload['rules'])
|
||||
parts = read_parts(path); styles = parts['word/styles.xml']
|
||||
h2 = styles.find(f"w:style[@w:styleId='{style_id('h2')}']", NS)
|
||||
assert h2.find('w:name', NS).get(W + 'val') == 'MDHelper 子章节'
|
||||
assert h2.find('w:basedOn', NS).get(W + 'val') == style_id('h1')
|
||||
assert h2.find('w:rPr/w:sz', NS) is None
|
||||
assert h2.find('w:pPr/w:jc', NS).get(W + 'val') == 'center'
|
||||
link = styles.find(f"w:style[@w:styleId='{style_id('link')}']", NS)
|
||||
assert link.find('w:rPr/w:u', NS).get(W + 'val') == 'none'
|
||||
assert link.find('w:rPr/w:color', NS).get(W + 'val') == 'ff0000'
|
||||
emphasis = styles.find(f"w:style[@w:styleId='{style_id('emphasis')}']", NS)
|
||||
assert emphasis.find('w:basedOn', NS).get(W + 'val') == style_id('strong')
|
||||
assert emphasis.find('w:rPr/w:i', NS) is not None
|
||||
|
||||
|
||||
def test_inherit_default_parent_values_in_reader_and_word():
|
||||
rules = {'_metadata': {'h2': {'based_on': 'h1'}}}
|
||||
effective = resolved_rules(rules, font_size_px=20)
|
||||
assert effective['h2']['font_size'] == effective['h1']['font_size'] == 41
|
||||
css = render_css('', rules, font_size_px=20)
|
||||
assert '.reader h2' in css and 'font-size: 41px' in css
|
||||
|
||||
|
||||
@pytest.mark.parametrize('engine', ['builtin', 'python-docx', 'pandoc'])
|
||||
def test_table_borders_padding_and_nested_list_styles(tmp_path, engine):
|
||||
rules = {'table': {'border_width': 1.5, 'border_color': '#123456', 'cell_padding': 6},
|
||||
'table_head': {'background_color': '#ffeecc'}, 'list_bullet': {'level_indent': 24},
|
||||
'list_ordered': {'list_marker': 'upper-roman'}}
|
||||
path = export_markdown_to_docx(SOURCE, tmp_path / 'containers.docx', engine=engine, style_rules=rules)
|
||||
with zipfile.ZipFile(path) as package:
|
||||
styles = ET.fromstring(package.read('word/styles.xml'))
|
||||
numbers = ET.fromstring(package.read('word/numbering.xml'))
|
||||
table = styles.find(f"w:style[@w:styleId='{style_id('table')}']", NS)
|
||||
assert table.find('w:tblPr/w:tblBorders/w:top', NS).get(W + 'sz') == '12'
|
||||
assert table.find('w:tblPr/w:tblCellMar/w:top', NS).get(W + 'w') == '120'
|
||||
assert table.find("w:tblStylePr[@w:type='firstRow']/w:tcPr/w:shd", NS).get(W + 'fill') == 'ffeecc'
|
||||
nested = styles.find(f"w:style[@w:styleId='{style_id('list_bullet')}Level2']", NS)
|
||||
assert nested.find('w:basedOn', NS).get(W + 'val') == style_id('list_bullet')
|
||||
assert nested.find('w:rPr', NS) is None
|
||||
assert numbers.find(".//w:numFmt[@w:val='upperRoman']", NS) is not None
|
||||
|
||||
|
||||
def test_explicit_child_font_stays_independent_even_when_initially_equal(tmp_path):
|
||||
rules = {'h1': {'font_size': 28, 'font_size_unit': 'pt'}, 'h2': {'font_size': 28, 'font_size_unit': 'pt'},
|
||||
'_metadata': {'h2': {'based_on': 'h1'}}}
|
||||
path = export_markdown_to_docx('## Child', tmp_path / 'child.docx', style_rules=rules)
|
||||
styles = read_parts(path)['word/styles.xml']
|
||||
child = styles.find(f"w:style[@w:styleId='{style_id('h2')}']", NS)
|
||||
assert child.find('w:rPr/w:sz', NS).get(W + 'val') == '56'
|
||||
|
||||
|
||||
def test_duplicate_display_names_do_not_merge_distinct_word_styles(tmp_path):
|
||||
path = export_markdown_to_docx('# Heading\n\nBody', tmp_path / 'names.docx',
|
||||
style_rules={'_metadata': {'h1': {'name': '正文'}}})
|
||||
styles = read_parts(path)['word/styles.xml']
|
||||
names = [s.find(W + 'name').get(W + 'val') for s in styles.findall(W + 'style')]
|
||||
assert len(names) == len(set(names))
|
||||
|
||||
|
||||
def test_project_preset_retains_semantic_names_and_bases():
|
||||
from mdhelper.project_presets import capture_preset, portable_preset, read_portable_preset
|
||||
from mdhelper.preferences import ReaderPreferences
|
||||
from mdhelper.export_settings import PageSettings
|
||||
rules = {'h1': {'font_size': 22}, '_metadata': {'h2': {'name': '章节', 'based_on': 'h1'}}}
|
||||
reader = ReaderPreferences.from_mapping({'document_style_id': 'custom:test', 'custom_document_styles': {'custom:test': {'rules': rules}}})
|
||||
preset = read_portable_preset(json.loads(json.dumps(portable_preset(capture_preset('Styles', reader, PageSettings())))))
|
||||
assert preset['reader']['custom_document_styles']['custom:test']['rules']['_metadata'] == rules['_metadata']
|
||||
@@ -0,0 +1,60 @@
|
||||
param([string]$Python = (Join-Path $PSScriptRoot '..\mdhelper_env\mdhelper_env\Scripts\python.exe'))
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Push-Location (Join-Path $PSScriptRoot '..')
|
||||
$testDirectory = $null
|
||||
$word = $null
|
||||
try {
|
||||
$testDirectory = (@'
|
||||
import json, tempfile, sys
|
||||
from pathlib import Path
|
||||
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
|
||||
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)
|
||||
(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()
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Fixture generation failed.' }
|
||||
$names = Get-Content -LiteralPath (Join-Path $testDirectory 'names.json') -Raw -Encoding UTF8 | ConvertFrom-Json
|
||||
$word = New-Object -ComObject Word.Application
|
||||
$word.Visible = $false
|
||||
$word.DisplayAlerts = 0
|
||||
foreach ($engine in @('builtin', 'python-docx', 'pandoc')) {
|
||||
$doc = $word.Documents.Open((Join-Path $testDirectory "$engine.docx"), $false, $true)
|
||||
try {
|
||||
$range = $doc.Content.Duplicate
|
||||
if (-not $range.Find.Execute('bold title')) { throw 'Missing heading text.' }
|
||||
if ($range.Font.Bold -ne -1) { throw "$engine lost emphasis inside bold heading." }
|
||||
$range = $doc.Content.Duplicate
|
||||
if (-not $range.Find.Execute('strong second')) { throw 'Missing body text.' }
|
||||
$doc.Styles.Item($names.paragraph).Font.Size = 23
|
||||
if ($range.Font.Size -ne 23) { throw "$engine body style does not reach emphasized text." }
|
||||
$doc.Styles.Item($names.strong).Font.Color = 255
|
||||
if ($range.Font.Color -ne 255) { throw "$engine character style edit did not propagate." }
|
||||
$range = $doc.Content.Duplicate
|
||||
if (-not $range.Find.Execute('bold link')) { throw 'Missing mixed link text.' }
|
||||
$doc.Styles.Item($names.link).Font.Color = 65280
|
||||
if ($range.Font.Color -ne 65280) { throw "$engine link color does not reach combined styles." }
|
||||
$range = $doc.Content.Duplicate
|
||||
if (-not $range.Find.Execute('Child title')) { throw 'Missing derived heading text.' }
|
||||
if ($range.Font.Bold -ne 0) { throw "$engine explicit child-style bold=False did not override its base." }
|
||||
$doc.Styles.Item($names.h1).Font.Size = 30
|
||||
if ($range.Font.Size -ne 30) { throw "$engine base-style change does not reach child heading." }
|
||||
Write-Output "$engine passed: Word opened document, heading emphasis, body and character edits, mixed links, base-style inheritance."
|
||||
} finally { $doc.Close(0); [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($doc) }
|
||||
}
|
||||
} finally {
|
||||
if ($word) { $word.Quit(); [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($word) }
|
||||
if ($testDirectory -and (Test-Path -LiteralPath $testDirectory)) {
|
||||
$resolved = [IO.Path]::GetFullPath($testDirectory)
|
||||
$tempRoot = [IO.Path]::GetFullPath([IO.Path]::GetTempPath()).TrimEnd('\') + '\'
|
||||
if ($resolved.StartsWith($tempRoot, [StringComparison]::OrdinalIgnoreCase) -and ([IO.Path]::GetFileName($resolved)).StartsWith('MDHelper-Word-Styles-')) {
|
||||
Remove-Item -LiteralPath $resolved -Recurse -Force
|
||||
}
|
||||
}
|
||||
Pop-Location
|
||||
}
|
||||
Reference in New Issue
Block a user