fix: retain code ancestor styles and numbering across list blocks

This commit is contained in:
2026-11-05 11:00:20 +08:00
parent 9af74df775
commit f36bd3199c
7 changed files with 231 additions and 19 deletions
+3
View File
@@ -153,6 +153,9 @@ def resolved_rules(rules: dict | None, font_family: str = "", font_size_px: floa
inherited[target] = value
return value
for target in result: resolve(target)
from .style_catalog import character_declarations
for target, declarations in character_declarations(authored, inherited).items():
inherited[target].update(normalize_rule(declarations))
return inherited
+14 -9
View File
@@ -235,19 +235,20 @@ def _markdown_blocks(source: str) -> list[ParagraphBlock | TableBlock]:
def _add_python_docx_paragraph(document: object, block: ParagraphBlock) -> None:
style = f"Heading {block.style.removeprefix('Heading')}" if block.style.startswith("Heading") else None
if block.list_kind == "bullet":
special = block.style.startswith('Heading') or block.style == 'Code'
if block.list_kind == "bullet" and not special:
style = "List Bullet"
elif block.list_kind == "number":
elif block.list_kind == "number" and not special:
style = "List Number"
elif block.style == "Code":
from docx.enum.style import WD_STYLE_TYPE
if "MDHelper Code" not in document.styles:
document.styles.add_style("MDHelper Code", WD_STYLE_TYPE.PARAGRAPH)
style = "MDHelper Code"
elif block.quote_depth:
elif block.quote_depth and not special:
style = "Quote"
if block.list_kind and block.loose:
if block.list_kind and block.loose and not special:
from docx.enum.style import WD_STYLE_TYPE
name = QUOTED_LIST_PARAGRAPH_STYLE if block.quote_depth else LIST_PARAGRAPH_STYLE
if block.inner_quote: name = INNER_QUOTE_STYLE
@@ -366,7 +367,7 @@ class _DocxBuilder:
token = self.tokens[self.index]
if token.type == "heading_open":
level = min(max(int(token.tag[1:]), 1), 6) if token.tag.startswith("h") else 1
self._add_next_inline(f"Heading{level}")
self._add_next_inline(f"Heading{level}", list_kind=self.list_stack[-1] if self.list_stack else "")
continue
if token.type == "paragraph_open":
style = "Quote" if self.quote_depth else "Normal"
@@ -374,7 +375,7 @@ class _DocxBuilder:
continue
if token.type in {"fence", "code_block"}:
for line in token.content.rstrip("\n").splitlines() or [""]:
self.blocks.append(ParagraphBlock([(line, {"code": True})], style="Code"))
self._append_paragraph([(line, {"code": True})], 'Code', self.list_stack[-1] if self.list_stack else '')
elif token.type == 'list_item_open':
self.item_pending.append(True)
self.item_targets.append('list_ordered' if self.list_stack[-1] == 'number' else 'list_bullet')
@@ -409,14 +410,17 @@ class _DocxBuilder:
runs = _inline_runs(inline.children if inline is not None else None)
if list_kind and self.item_pending[-1] and inline is not None:
if re.match(r'^\[[ xX]\]\s', inline.content): self.item_targets[-1] = 'list_task'
self._append_paragraph(runs, style, list_kind, not self.tokens[self.index].hidden)
self.index += 3
def _append_paragraph(self, runs, style, list_kind, loose=False):
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, loose=not self.tokens[self.index].hidden,
list_start=self.list_starts[-1] if self.list_starts else 1, loose=loose,
continuation=bool(list_kind and self.item_pending and not self.item_pending[-1]),
list_target=self.item_targets[-1] if list_kind else '',
inner_quote=bool(self.list_quote_depths and self.quote_depth > self.list_quote_depths[-1])))
if self.item_pending: self.item_pending[-1] = False
self.index += 3
def _collect_table(self) -> TableBlock:
rows: list[list[list[tuple[str, dict[str, bool]]]]] = []
@@ -515,7 +519,8 @@ def _paragraph_xml(block: ParagraphBlock) -> str:
if block.list_kind:
name = (QUOTED_LIST_PARAGRAPH_STYLE if block.quote_depth else LIST_PARAGRAPH_STYLE) if block.loose else 'ListParagraph'
if block.inner_quote: name = INNER_QUOTE_STYLE
props = [f'<w:pStyle w:val="{name}"/>']
if not block.style.startswith('Heading') and block.style != 'Code':
props = [f'<w:pStyle w:val="{name}"/>']
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"/>')
+37 -8
View File
@@ -11,7 +11,7 @@ import zipfile
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, legacy_base
from .style_catalog import CATALOG, CHARACTER_DEFAULTS, explicit_rules, character_declarations, parent_style, style_name, legacy_base
from .docx_style import W, NS, child, val, properties, _run_properties, _paragraph_properties, _order_properties
from .docx_inline import source_style_order, ordered_styles, LIST_PARAGRAPH_STYLE, QUOTED_LIST_PARAGRAPH_STYLE, SOURCE_PARAGRAPH_STYLES, CONTINUATION, INNER_QUOTE_STYLE, LIST_TARGET, LIST_TARGETS, SOURCE_LIST_STYLES
from .table_style import HEADER_COLOR, STRIPE_COLOR, BORDER_COLOR, VERTICAL_BORDER_COLOR
@@ -74,6 +74,7 @@ class WordStyles:
self.rules = rules if isinstance(rules, dict) else {}
self.effective = resolved_rules(self.rules, **defaults)
self.explicit = explicit_rules(self.rules)
self.explicit.update(character_declarations(self.rules, self.effective))
self.original = {s.get(W + 'styleId'): s for s in styles.findall(W + 'style')}
self.used_names = {reference(s, 'name') for s in self.original.values()}
self.created = {}
@@ -174,13 +175,16 @@ class WordStyles:
val(style, 'link', paragraph_id)
val(self.created[paragraph_id], 'link', identifier)
props = child(style, 'rPr')
_run_properties(props, self.explicit[key])
_run_properties(props, self.code_character_rule(key))
if base:
old = ET.Element(W + 'rPr')
_run_properties(old, self.explicit[base])
_run_properties(old, self.code_character_rule(base))
_delta(props, old, normalize_rule(self.rules.get(key)))
return identifier
def code_character_rule(self, key='code'):
return self.effective[key] if parent_style('code', self.rules) else self.explicit[key]
def character(self, key):
identifier = style_id(key)
if identifier in self.created: return identifier
@@ -192,14 +196,14 @@ class WordStyles:
base_id = self.paragraph_character('code')
# Word cannot clear one inherited character-style property. Preserve
# the resolved remaining properties and inherit color from the text.
base_rule = self.explicit['code'] if legacy else self.character_rule(base) if base else {}
base_rule = self.code_character_rule() if legacy else self.character_rule(base) if base else {}
if rule.get('font_color') == 'inherit' and base_rule.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_id:
old = ET.Element(W + 'rPr')
_run_properties(old, self.explicit['code'] if legacy else self.character_rule(base))
_run_properties(old, base_rule)
_delta(child(style, 'rPr'), old, normalize_rule(self.rules.get(key)))
return identifier
@@ -368,6 +372,19 @@ class WordStyles:
_delta(props, old, authored)
return identifier
def list_block(self, target, list_target, level):
"""Keep a heading/code style as the editable base inside a numbered item."""
identifier = style_id(target) + style_id(list_target) + 'Level' + str(level + 1)
if identifier not in self.created:
style = self.new(identifier, 'paragraph', 'MDHelper ' + style_name(target, self.rules) +
'(' + style_name(list_target, self.rules) + f'第 {level + 1} 级)', self.paragraph(target))
own = {k: v for k, v in self.effective[target].items() if 'indent' not in k}
own.update({k: v for k, v in self.explicit[target].items() if 'indent' in k})
rule = self.contextual_list_rule(list_target, own, level)
props = ET.Element(W + 'pPr'); _paragraph_properties(props, rule)
child(style, 'pPr').append(props.find(W + 'ind'))
return identifier
def quoted_list(self, target, base_id, level):
"""A real p inside a quoted list receives the quote's explicit format."""
identifier = base_id + 'Quote'
@@ -500,17 +517,29 @@ class WordStyles:
target = self.classify(paragraph, original_id)
if target.startswith('list_') and list_target in LIST_TARGETS: target = list_target
identifier = self.paragraph(target)
numpr = ppr.find(W + 'numPr')
# Every numbered paragraph in a list must share the same rewritten
# numbering instance, including headings and code. Otherwise Word
# restarts numbering when the next ordinary paragraph is reached.
if numpr is not None:
if not list_target:
_, original_level = self.list_level(numpr)
list_target = 'list_bullet' if reference(original_level, 'numFmt') == 'bullet' else 'list_ordered'
self.inherit_list_indents(numpr)
if target == 'code_block' or re.fullmatch('h[1-6]', target):
level, _ = self.list_level(numpr)
identifier = self.list_block(target, list_target, level)
marker = self.effective[list_target].get('list_marker')
if marker: self.apply_list_marker(numpr, list_target, marker)
if continuation and target == 'blockquote': remove_fields(ppr, ('numPr',))
if target.startswith('list_'):
numpr = ppr.find(W + 'numPr')
self.inherit_list_indents(numpr)
level, _ = self.list_level(numpr)
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, level)
if QUOTED_LIST_PARAGRAPH_STYLE in names: identifier = self.quoted_list(target, identifier, level)
if continuation: remove_fields(ppr, ('numPr',))
if continuation: remove_fields(ppr, ('numPr',))
alignment = reference(ppr, 'jc')
if target in ('table_head','table_cell') and alignment in ('left','center','right','both'):
identifier = self.table_column(target, alignment)
+23 -1
View File
@@ -97,7 +97,7 @@ def explicit_rules(rules):
legacy = rules.get('table') if isinstance(rules.get('table'), dict) else {}
inherited.update({k: v for k, v in legacy.items() if k not in TABLE_ONLY_FIELDS})
if key == 'inline_code' and not base and legacy_base(key, rules):
legacy = rules.get('code') if isinstance(rules.get('code'), dict) else {}
legacy = resolve('code')
inherited.update({k: v for k, v in legacy.items() if k in CHARACTER_FIELDS})
inherited.update(own)
if CATALOG[key].kind == 'character': inherited = {k: v for k, v in inherited.items() if k in CHARACTER_FIELDS}
@@ -107,6 +107,28 @@ def explicit_rules(rules):
return result
def character_declarations(rules, effective):
"""Include a deliberately selected code ancestor, without imposing legacy defaults.
Old code settings only override authored fields. Selecting a paragraph base
for code also selects that base's defaults, as it does for code blocks.
"""
explicit = explicit_rules(rules)
result = {}
def resolve(key):
if key in result: return result[key]
base = parent_style(key, rules)
inherited = {**CHARACTER_DEFAULTS.get(base, {}), **resolve(base)} if base else dict(explicit[key])
if key == 'inline_code' and legacy_base(key, rules) and parent_style('code', rules):
inherited.update({k: v for k, v in effective['code'].items() if k in CHARACTER_FIELDS})
own = rules.get(key, {})
result[key] = {**inherited, **{k: v for k, v in own.items() if k in CHARACTER_FIELDS}} if isinstance(own, dict) else inherited
return result[key]
for key, definition in CATALOG.items():
if definition.kind == 'character': resolve(key)
return result
@dataclass(frozen=True)
class StyleRegion:
start: int
+2 -1
View File
@@ -706,10 +706,11 @@ def patch_core(source: str, target: str, before: dict, after: dict, *, reset=Fal
def render_css(source: str, rules: dict, font_family: str = '', font_size_px: float = 16, preset: str = 'default') -> str:
"""Materialize the few core features which need companion reader rules."""
from .style_catalog import explicit_rules, normalize_metadata, CATALOG
from .style_catalog import explicit_rules, character_declarations, normalize_metadata, CATALOG
inherited = explicit_rules(rules)
from .document_style import resolved_rules
effective = resolved_rules(rules, font_family, font_size_px, preset)
inherited.update(character_declarations(rules, effective))
winners = _collect_cascade(source, Analysis())
def priority(declarations, entries):
important_groups = {g for g, props in PROPERTIES.items() if any(p in entries and entries[p][0][1] for p in props)}
+88
View File
@@ -0,0 +1,88 @@
"""Code ancestor defaults and non-paragraph blocks inside Markdown lists."""
import pytest
from mdhelper.style_sync import normalize_payload
from mdhelper.document_style import resolved_rules
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
ENGINES = ('builtin', 'python-docx', 'pandoc')
CODE_RULES = {'h1': {'font_color': '#ff0000', 'font_size': 20, 'font_size_unit': 'pt', 'underline': False},
'strong': {'underline': True}, '_metadata': {'code': {'based_on': 'h1'}}}
CODE_SOURCE = '# Parent\n\n`PlainCode`\n\n**Outer `InnerCode` outer**\n\n**Other `OtherCode`**'
BOLD_RULES = {'paragraph': {'bold': True}, 'h1': {'bold': True}, '_metadata': {'code': {'based_on': 'h1'}}}
HEADING_LIST = '1. ### FirstHeading\n\n Continuation\n\n2. ### SecondHeading'
CODE_LIST = '1. ```text\n CodeFirst\n CodeLine\n ```\n\n Continuation\n\n2. Second'
NESTED_LIST = '1. Outer\n\n 1. ### NestedHeading\n\n 2. ```text\n NestedCode\n ```\n\n 3. LastNested\n\n2. LastOuter'
def test_code_ancestor_is_shared_by_reader_and_graphical_settings(qt_application, tmp_path):
payload = normalize_payload({'rules': CODE_RULES})
rule = resolved_rules(payload['rules'])['inline_code']
assert (rule['font_color'], rule['font_size'], rule['bold'], rule['underline']) == ('#ff0000', 20, True, False)
assert normalize_payload(payload) == payload
result = browser(qt_application, tmp_path, payload, CODE_SOURCE,
"[...document.querySelectorAll('code')].map(e=>{const s=getComputedStyle(e);return [s.color,s.fontSize,s.fontWeight,getComputedStyle(e.querySelector('[data-mdh-text]')).textDecorationLine]})")
assert len(result) == 3
for color, size, weight, line in result:
assert color == 'rgb(255, 0, 0)' and abs(float(size[:-2])-20*96/72) < .01
assert weight == '700' and line == 'none'
def test_character_descendants_keep_materialized_code_ancestor():
rules = {'h1': {'english_font_family': 'Arial'}, '_metadata': {
'code': {'based_on': 'h1'}, 'emphasis': {'based_on': 'inline_code'}}}
effective = resolved_rules(rules)
assert effective['emphasis']['english_font_family'] == effective['inline_code']['english_font_family'] == 'Arial'
assert effective['emphasis']['font_size'] == effective['h1']['font_size']
@pytest.mark.parametrize('engine', ENGINES)
def test_word_nested_code_keeps_ancestor_attributes_and_named_style(tmp_path, engine):
doc, styles = parts(export_markdown_to_docx(CODE_SOURCE, tmp_path/'code.docx', engine=engine, style_rules=CODE_RULES))
effective = effective_document(doc, styles)
for word in ('PlainCode', 'InnerCode', 'OtherCode'):
run = next(r for r in effective.iter(W+'r') if ''.join(r.itertext()) == word)
assert run.find('w:rPr/w:color', NS).get(W+'val') == 'ff0000'
assert run.find('w:rPr/w:sz', NS).get(W+'val') == '40'
assert run.find('w:rPr/w:b', NS).get(W+'val', '1') == '1'
assert run.find('w:rPr/w:u', NS).get(W+'val') == 'none'
mixed = styles.find("w:style[@w:styleId='MDHelperMixStrongInlineCode']", NS)
mixed.find('w:rPr/w:color', NS).set(W+'val', '0000ff')
for run in effective_document(doc, styles).iter(W+'r'):
if ''.join(run.itertext()) in ('InnerCode', 'OtherCode'):
assert run.find('w:rPr/w:color', NS).get(W+'val') == '0000ff'
@pytest.mark.parametrize('engine', ENGINES)
def test_code_ancestor_emphasis_is_protected_in_bold_paragraph(tmp_path, engine):
doc, styles = parts(export_markdown_to_docx('# Parent\n\nBody `Inline`', tmp_path/'bold.docx', engine=engine, style_rules=BOLD_RULES))
run = next(r for r in effective_document(doc, styles).iter(W+'r') if ''.join(r.itertext()) == 'Inline')
assert run.find('w:rPr/w:b', NS).get(W+'val', '1') == '1'
assert run.find('w:rPr/w:sz', NS).get(W+'val') == '49' # Default h1, rounded to Word half-points.
@pytest.mark.parametrize('engine', ENGINES)
@pytest.mark.parametrize('source,words', [(HEADING_LIST, ('FirstHeading', 'SecondHeading')),
(CODE_LIST, ('CodeFirst', 'Second')),
(NESTED_LIST, ('NestedHeading', 'NestedCode', 'LastNested'))])
def test_list_blocks_share_numbering_and_keep_editable_block_styles(tmp_path, engine, source, words):
path = export_markdown_to_docx(source, tmp_path/'list.docx', engine=engine)
doc, styles = parts(path)
paragraphs = {''.join(p.itertext()): p for p in doc.iter(W+'p')}
numbers = []
for word in words:
p = next(p for text,p in paragraphs.items() if text.startswith(word))
numbers.append(p.find('w:pPr/w:numPr/w:numId', NS).get(W+'val'))
style_id = p.find('w:pPr/w:pStyle', NS).get(W+'val')
style = styles.find(f"w:style[@w:styleId='{style_id}']", NS)
if 'Heading' in word:
assert style.find('w:basedOn', NS).get(W+'val') == 'MDHelperH3'
if 'Code' in word:
assert style.find('w:basedOn', NS).get(W+'val') == 'MDHelperCodeBlock'
assert len(set(numbers)) == 1
for text,p in paragraphs.items():
if text in ('Continuation', 'CodeLine'):
assert p.find('w:pPr/w:numPr', NS) is None or engine == 'pandoc'
assert not any(a.startswith('{urn:mdhelper:source}') for p in doc.iter(W+'p') for a in p.attrib)
+64
View File
@@ -0,0 +1,64 @@
param([string]$Python = (Join-Path $PSScriptRoot '..\mdhelper_env\mdhelper_env\Scripts\python.exe'))
$ErrorActionPreference='Stop'
Push-Location (Join-Path $PSScriptRoot '..')
$word=$null
try {
$folder = (@'
import sys,tempfile
from pathlib import Path
sys.path.insert(0,str(Path('tests').resolve()))
from test_style_revision_056 import *
folder=Path(tempfile.mkdtemp(prefix='MDHelper-056-Word-'))
for engine in ENGINES:
for name,source,rules in [('code',CODE_SOURCE,CODE_RULES),('bold','# Parent\n\nBody `Inline`',BOLD_RULES),
('heading',HEADING_LIST,{}),('listcode',CODE_LIST,{}),('nested',NESTED_LIST,{})]:
export_markdown_to_docx(source,folder/f'{engine}-{name}.docx',engine=engine,style_rules=rules)
print(folder)
'@ | & $Python -B -).Trim()
if ($LASTEXITCODE -ne 0) {throw 'Fixture generation failed'}
$word=New-Object -ComObject Word.Application
$word.Visible=$false;$word.DisplayAlerts=0
foreach($engine in @('builtin','python-docx','pandoc')) {
foreach($case in @('code','bold','heading','listcode','nested')) {
$doc=$word.Documents.Open((Join-Path $folder "$engine-$case.docx"),$false,$true)
try {
if($case -eq 'code') {
foreach($text in @('PlainCode','InnerCode','OtherCode')) {
$r=$doc.Content.Duplicate;[void]$r.Find.Execute($text)
if($r.Font.Color -ne 255 -or $r.Font.Size -ne 20 -or $r.Font.Bold -ne -1 -or $r.Font.Underline -ne 0){throw "$engine $text lost code ancestor formatting"}
}
$doc.Styles.Item('MDHelper 标题 1').Font.Color=16711680
$r=$doc.Content.Duplicate;[void]$r.Find.Execute('PlainCode')
if($r.Font.Color -ne 16711680){throw "$engine code ancestor no longer editable"}
$doc.Styles.Item('MDHelper 加粗+行内代码').Font.Color=65280
foreach($text in @('InnerCode','OtherCode')) {
$r=$doc.Content.Duplicate;[void]$r.Find.Execute($text)
if($r.Font.Color -ne 65280){throw "$engine shared mixed style no longer editable"}
}
} elseif($case -eq 'bold') {
$r=$doc.Content.Duplicate;[void]$r.Find.Execute('Inline')
if($r.Font.Bold -ne -1 -or $r.Font.Size -ne 24.5){throw "$engine code emphasis reversed or defaults lost"}
} else {
$pairs = switch($case) {
'heading' { ,@(@('FirstHeading','1.'),@('Continuation',''),@('SecondHeading','2.')) }
'listcode' { ,@(@('CodeFirst','1.'),@('Continuation',''),@('Second','2.')) }
'nested' { ,@(@('Outer','1.'),@('NestedHeading','1.'),@('NestedCode','2.'),@('LastNested','3.'),@('LastOuter','2.')) }
}
foreach($pair in $pairs) {
$r=$doc.Content.Duplicate;[void]$r.Find.Execute($pair[0])
if($r.ListFormat.ListString.Trim() -ne $pair[1]){throw "$engine $case $($pair[0]) marker: $($r.ListFormat.ListString) expected $($pair[1])"}
}
$target=if($case -eq 'heading'){'FirstHeading'}elseif($case -eq 'listcode'){'CodeFirst'}else{'NestedHeading'}
$style=if($case -eq 'listcode'){'MDHelper 代码块'}else{'MDHelper 标题 3'}
$doc.Styles.Item($style).Font.Color=65280
$r=$doc.Content.Duplicate;[void]$r.Find.Execute($target)
if($r.Font.Color -ne 65280){throw "$engine list block lost editable paragraph base"}
}
Write-Output "$engine $case passed"
} finally {$doc.Close(0);[void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($doc)}
}
}
} finally {
if($word){$word.Quit();[void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($word)}
Pop-Location
}