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
+26 -6
View File
@@ -15,6 +15,7 @@ from markdown_it import MarkdownIt
from markdown_it.token import Token
from .markdown_compat import cjk_strong_plugin
from .docx_inline import source_style_name
WP_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
@@ -71,7 +72,7 @@ def export_markdown_to_docx(
with tempfile.TemporaryDirectory(prefix="mdhelper-export-") as directory:
target = Path(directory) / "document.docx"
if engine == "pandoc":
result = export_markdown_to_docx_pandoc(source, target, source_path=source_path, cancel=cancel)
result = export_markdown_to_docx_pandoc(source, target, source_path=source_path, cancel=cancel, semantic_styles=True)
elif engine == "python-docx":
result = export_markdown_to_docx_python_docx(source, target)
else:
@@ -96,11 +97,13 @@ def export_markdown_to_docx_builtin(source: str, output_path: Path) -> Path:
output_path = output_path.with_suffix(".docx")
blocks = _markdown_blocks(source)
links = {}
links, source_styles = {}, set()
for block in blocks:
groups = [block.runs] if isinstance(block, ParagraphBlock) else [runs for row in block.rows for runs in row]
for runs in groups:
for _, style in runs:
name = source_style_name(style.get('semantic_order', ()))
if name: source_styles.add(name)
if style.get('href'):
style['link_id'] = links.setdefault(style['href'], f'rIdLink{len(links) + 1}')
document_xml = _document_xml(blocks)
@@ -114,7 +117,8 @@ def export_markdown_to_docx_builtin(source: str, output_path: Path) -> Path:
package.writestr("[Content_Types].xml", content_types)
package.writestr("_rels/.rels", PACKAGE_RELS_XML)
package.writestr("word/document.xml", document_xml)
package.writestr("word/styles.xml", STYLES_XML)
markers = ''.join(f'<w:style w:type="character" w:styleId="{name}"><w:name w:val="{name}"/></w:style>' for name in sorted(source_styles))
package.writestr("word/styles.xml", STYLES_XML.replace('</w:styles>', markers + '</w:styles>'))
package.writestr("word/settings.xml", SETTINGS_XML)
relations = ''.join(f'<Relationship Id="{identifier}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target={quoteattr(href)} TargetMode="External"/>' for href, identifier in links.items())
if has_lists: relations += '<Relationship Id="rIdNumbering" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering" Target="numbering.xml"/>'
@@ -122,7 +126,7 @@ def export_markdown_to_docx_builtin(source: str, output_path: Path) -> Path:
return output_path
def export_markdown_to_docx_pandoc(source: str, output_path: Path, source_path: Path | None = None, cancel: object = None) -> Path:
def export_markdown_to_docx_pandoc(source: str, output_path: Path, source_path: Path | None = None, cancel: object = None, semantic_styles: bool = False) -> Path:
output_path = output_path.resolve()
if output_path.suffix.lower() != ".docx":
output_path = output_path.with_suffix(".docx")
@@ -141,6 +145,8 @@ def export_markdown_to_docx_pandoc(source: str, output_path: Path, source_path:
resource_directory = source_path.resolve().parent if source_path is not None else input_path.parent
command = [str(pandoc_path), str(input_path), "-o", str(output_path), "--standalone"]
if semantic_styles:
command.append('--lua-filter=' + str(Path(__file__).with_name('resources') / 'word_inline_styles.lua'))
run_options: dict[str, object] = {}
if sys.platform == "win32":
run_options["creationflags"] = subprocess.CREATE_NO_WINDOW
@@ -264,6 +270,12 @@ def _add_python_docx_run(paragraph, text, style):
if style.get('code'):
run.style = 'MDHelper Code Char'
run.font.name = 'Consolas'
marker = source_style_name(style.get('semantic_order', ()))
if marker:
from docx.enum.style import WD_STYLE_TYPE
styles = paragraph.part.document.styles
if marker not in styles: styles.add_style(marker, WD_STYLE_TYPE.CHARACTER)
run.style = marker
if style.get('href'):
link = OxmlElement('w:hyperlink')
link.set(qn('r:id'), paragraph.part.relate_to(style['href'], RT.HYPERLINK, is_external=True))
@@ -407,13 +419,18 @@ def _inline_runs(children: list[Token] | None) -> list[tuple[str, dict[str, obje
_pop_style(style_stack, "italic")
elif child.type == 's_open': style_stack.append('strike')
elif child.type == 's_close': _pop_style(style_stack, 'strike')
elif child.type == 'link_open': links.append(child.attrGet('href') or '')
elif child.type == 'link_open':
links.append(child.attrGet('href') or '')
style_stack.append('link')
elif child.type == 'link_close':
if links: links.pop()
_pop_style(style_stack, 'link')
elif child.type in {"text", "html_inline", 'code_inline'}:
text = html.unescape(child.content) if child.type == "html_inline" else child.content
style = {key: True for key in style_stack}
if child.type == 'code_inline': style['code'] = True
keys = {'bold': 'strong', 'italic': 'emphasis', 'strike': 'strike', 'link': 'link'}
style['semantic_order'] = tuple(dict.fromkeys([keys[key] for key in style_stack] + (['inline_code'] if style.get('code') else [])))
if links: style['href'] = links[-1]
runs.append((text, style))
elif child.type in {"softbreak", "hardbreak"}:
@@ -471,7 +488,10 @@ def _run_xml(text: str, style: dict[str, object]) -> str:
if style.get("italic"):
props.append("<w:i/>")
if style.get('strike'): props.append('<w:strike/>')
if style.get("code"):
marker = source_style_name(style.get('semantic_order', ()))
if marker:
props.append(f'<w:rStyle w:val="{marker}"/>')
elif style.get("code"):
props.append('<w:rStyle w:val="CodeChar"/>')
rpr = f"<w:rPr>{''.join(props)}</w:rPr>" if props else ""
preserve = ' xml:space="preserve"' if text[:1].isspace() or text[-1:].isspace() else ""
+15
View File
@@ -0,0 +1,15 @@
"""Private, temporary style markers shared by the three DOCX converters."""
PREFIX = 'MDHelperSource_'
CODES = {'strong': 'B', 'emphasis': 'I', 'strike': 'S', 'link': 'L', 'inline_code': 'C'}
def source_style_name(order):
keys = tuple(dict.fromkeys(key for key in order if key in CODES))
return PREFIX + '_'.join(CODES[key] for key in keys) if keys else ''
def source_style_order(name):
if not name.startswith(PREFIX): return ()
reverse = {code: key for key, code in CODES.items()}
codes = name[len(PREFIX):].split('_')
return tuple(reverse[code] for code in codes) if all(code in reverse for code in codes) else ()
+22 -9
View File
@@ -13,6 +13,7 @@ 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
from .docx_style import W, NS, child, val, properties, _run_properties, _paragraph_properties, _order_properties
from .docx_inline import source_style_order
RUN_FIELDS = 'rFonts sz szCs b bCs i iCs color spacing u strike shd'.split()
PARAGRAPH_FIELDS = 'jc spacing ind shd snapToGrid contextualSpacing keepNext keepLines pageBreakBefore widowControl rPr outlineLvl'.split()
@@ -158,16 +159,17 @@ class WordStyles:
return identifier
def combined_character(self, keys, paragraph_target):
keys = tuple(key for key in ('link', 'strong', 'emphasis', 'strike', 'inline_code') if key in keys)
keys = tuple(dict.fromkeys(keys))
if not keys: return ''
merged = dict(self.character_rule(keys[0]))
for key in keys[1:]: merged.update(self.character_rule(key))
identifier = self.character(keys[0]) if len(keys) == 1 else 'MDHelperMix' + ''.join(style_id(key)[8:] for key in keys)
if identifier not in self.created:
style = self.new(identifier, 'character', 'MDHelper ' + '+'.join(style_name(k, self.rules) for k in keys), self.character(keys[0]))
base = 'link' if 'link' in keys else keys[0]
style = self.new(identifier, 'character', 'MDHelper ' + '+'.join(style_name(k, self.rules) for k in keys), self.character(base))
props, old = child(style, 'rPr'), ET.Element(W + 'rPr')
_run_properties(props, merged)
_run_properties(old, self.character_rule(keys[0]))
_run_properties(old, self.character_rule(base))
_delta(props, old)
return identifier
@@ -298,6 +300,7 @@ class WordStyles:
rpr = properties(run, 'rPr')
run_id = reference(rpr, 'rStyle')
names = self.names(run_id)
source_order = next((order for style in self.chain(run_id) if (order := source_style_order(reference(style, 'name')))), ())
keys = set()
for tag, key, words in (('b', 'strong', ('strong',)), ('i', 'emphasis', ('emphasis',)), ('strike', 'strike', ('strike',))):
node = rpr.find(W + tag)
@@ -306,17 +309,18 @@ class WordStyles:
if target != 'code_block' and any(word in names for word in ('code', 'verbatim')): keys.add('inline_code')
# Preserve syntax-highlighting styles supplied by Pandoc for code blocks.
if target == 'code_block': keys.clear()
identifier = self.combined_character(keys, target)
ordered = source_order or tuple(key for key in ('link', 'strong', 'emphasis', 'strike', 'inline_code') if key in keys)
if target == 'code_block': ordered = ()
identifier = self.combined_character(ordered, target)
if target == 'code_block' and run_id: identifier = self.syntax_style(run_id, target)
remove_fields(rpr, RUN_FIELDS)
if identifier: val(rpr, 'rStyle', identifier)
else: remove_fields(rpr, ('rStyle',))
elif target == 'code_block' or not run_id: 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 key in ordered: 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]))
@@ -350,8 +354,17 @@ def apply_semantic_styles(path, rules, **defaults):
entries = [(info, package.read(info.filename)) for info in package.infolist()]
payloads = {info.filename: data for info, data in entries}
parser = ET.XMLParser(resolve_entities=False, no_network=True)
parts = {name: ET.fromstring(payloads[name], parser) for name in ('word/document.xml', 'word/styles.xml', 'word/numbering.xml') if name in payloads}
WordStyles(parts['word/styles.xml'], parts.get('word/numbering.xml'), rules, **defaults).apply(parts['word/document.xml'])
parts = {name: ET.fromstring(payloads[name], parser) for name in ('word/document.xml', 'word/styles.xml', 'word/numbering.xml', 'word/footnotes.xml', 'word/endnotes.xml') if name in payloads}
adapter = WordStyles(parts['word/styles.xml'], parts.get('word/numbering.xml'), rules, **defaults)
adapter.apply(parts['word/document.xml'])
for name in ('word/footnotes.xml', 'word/endnotes.xml'):
if name in parts:
for run in parts[name].iter(W + 'r'):
identifier = reference(run.find(W + 'rPr'), 'rStyle')
if any(source_style_order(reference(s, 'name')) for s in adapter.chain(identifier)):
adapter.apply_run(run, 'paragraph')
for style in list(parts['word/styles.xml']):
if source_style_order(reference(style, 'name')): parts['word/styles.xml'].remove(style)
for filename, root in parts.items():
_order_properties(root)
payloads[filename] = ET.tostring(root, encoding='UTF-8', xml_declaration=True, standalone=True)
+5
View File
@@ -88,6 +88,9 @@ def _paragraph_properties(ppr, rule):
spacing.set(W + side, str(round(length_points(amount, unit, points, line_points(rule, points)) * 20)))
if unit == "line":
spacing.set(W + side + "Lines", str(round(amount * 100)))
else:
spacing.set(W + side + 'Lines', '0')
spacing.set(W + side + 'Autospacing', '0')
mode = rule["line_spacing_mode"]
spacing.set(W + "line", str(round(number(rule["line_height_value"]) * (240 if mode == "multiple" else 20))))
spacing.set(W + "lineRule", {"multiple": "auto", "exact": "exact", "at_least": "atLeast"}[mode])
@@ -98,6 +101,8 @@ def _paragraph_properties(ppr, rule):
ind.set(W + side, str(round(length_points(amount, unit, points) * 20)))
if unit == "em":
ind.set(W + side + "Chars", str(round(amount * 100)))
else:
ind.set(W + side + 'Chars', '0')
kind = "hanging" if rule["indent_mode"] == "hanging" else "firstLine"
amount = number(rule["indent_value"]) if rule["indent_mode"] != "none" else 0
ind.set(W + kind, str(round(amount * points * 20)))
+50
View File
@@ -0,0 +1,50 @@
-- Private markers retain outer-to-inner Markdown order until the style pass.
-- Keep these codes in sync with docx_inline.py.
local prefix = 'MDHelperSource_'
local codes = {Strong='B', Emph='I', Strikeout='S', Link='L', Code='C'}
local function push(stack, code)
local copy, found = {}, false
for _, value in ipairs(stack) do
copy[#copy + 1] = value
if value == code then found = true end
end
if not found then copy[#copy + 1] = code end
return copy
end
local function mark(items, stack)
local output = pandoc.List()
local function append(item)
local last = output[#output]
if item.t == 'Span' and last and last.t == 'Span' and
item.attributes['custom-style'] == last.attributes['custom-style'] then
local content = last.content
content:extend(item.content)
last.content = content
output[#output] = last
else output:insert(item) end
end
for _, item in ipairs(items) do
local previous = item.t == 'Span' and item.attributes['custom-style'] or ''
if previous:sub(1, #prefix) == prefix then
local combined = stack
for code in previous:sub(#prefix + 1):gmatch('[BISLC]') do combined = push(combined, code) end
for _, nested in ipairs(mark(item.content, combined)) do append(nested) end
elseif codes[item.t] and item.t ~= 'Code' then
item.content = mark(item.content, push(stack, codes[item.t]))
output:insert(item)
elseif item.t == 'Code' or item.t == 'Str' or item.t == 'Space' or item.t == 'SoftBreak' or item.t == 'LineBreak' then
local active = item.t == 'Code' and push(stack, 'C') or stack
-- The final semantic style supplies the code font. Pandoc's Code writer
-- would otherwise replace our marker with its Verbatim character style.
if item.t == 'Code' then item = pandoc.Str(item.text) end
if #active > 0 then
append(pandoc.Span({item}, pandoc.Attr('', {}, {['custom-style']=prefix .. table.concat(active, '_')})))
else output:insert(item) end
else
if item.t == 'Span' or item.t == 'Quoted' or item.t == 'Cite' then item.content = mark(item.content, stack) end
output:insert(item)
end
end
return output
end
return {{Inlines=function(items) return mark(items, {}) end}}
+21 -5
View File
@@ -278,8 +278,9 @@ class _CoreRuleReader:
self.choice('text-align', 'alignment', {name: name for name in ('left', 'center', 'right', 'justify')})
self.read('color', self.color)
self.read('letter-spacing', self.tracking)
self.read('text-decoration', self.decoration)
self.read('text-decoration-line', self.decoration)
decorations = [prop for prop in ('text-decoration', 'text-decoration-line') if prop in self.entries]
if decorations:
self.read(max(decorations, key=lambda prop: self.entries[prop][0]), self.decoration)
for prop, field in (('background-color', 'background_color'), ('border-color', 'border_color')):
self.read(prop, lambda value, field=field: self.effect_color(value, field))
for prop, field in (('border-width', 'border_width'), ('padding', 'cell_padding'), ('--mdhelper-list-level-indent', 'level_indent')):
@@ -543,12 +544,27 @@ def render_css(source: str, rules: dict, font_family: str = '', font_size_px: fl
from .document_style import resolved_rules
effective = resolved_rules(rules, font_family, font_size_px, preset)
for key, metadata in normalize_metadata(rules.get('_metadata')).items():
if metadata.get('based_on') and CATALOG[key].kind != 'character':
inherited[key] = effective[key]
if 'based_on' in metadata and CATALOG[key].kind != 'character':
inherited[key] = dict(effective[key])
if not metadata['based_on'] and CATALOG[key].base:
legacy = rules.get(CATALOG[key].base, {})
defaults = {'underline': False, 'strike': False, 'background_color': 'transparent',
'list_marker': 'decimal' if key == 'list_ordered' else 'none' if key == 'list_task' else 'disc',
'level_indent': 36}
inherited[key].update({field: value for field, value in defaults.items() if field in legacy and field not in rules.get(key, {})})
inherited = {key: {field: value for field, value in rule.items() if field not in rules.get(key, {})} for key, rule in inherited.items()}
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)
# Emit the same font variables as the authored rules; a child's Chinese
# font declaration must not shadow an inherited English font declaration.
for key, rule in inherited.items():
declarations = _core_declarations(rule)
if declarations: helpers += '\n' + SELECTORS[key] + ' { ' + ' '.join(declarations) + ' }'
layout_helpers = {}
for key, rule in explicit_rules(rules).items():
materialized = {**inherited.get(key, {}), **rule}
layout_helpers[key] = {field: materialized[field] for field in ('level_indent', 'contextual_spacing') if field in materialized}
helpers += '\n' + build_document_style_css(layout_helpers)
# 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():