diff --git a/docs/architecture.md b/docs/architecture.md
index 9687b3c..749759f 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -49,6 +49,10 @@
CSS 同步按三个步骤处理:`_collect_cascade` 决定生效的声明,`_CoreRuleReader` 转换可表达的字体和段落属性,`analyze_css` 汇总结果。无法映射的 CSS 继续保留原文,不改写级联规则或 Word 的支持范围。
+`render_css` 使用与图形写入相同的字体变量表达继承,并生成列表层级缩进及独立文字修饰的辅助规则。显式取消列表基准时会恢复该语义类型的默认格式,旧配置缺少元数据时仍保留兼容基准。
+
+`docx_inline.py` 定义转换阶段的临时字符样式标记,记录 Markdown 从外到内的语义顺序。两个基础引擎直接记录解析栈;Pandoc 使用随包资源 `word_inline_styles.lua` 记录同一顺序。最终样式处理替换并删除临时标记,脚注仍保留原段落样式、编号和关系;导出文件不需要脚本或宏。
+
MHTML 的浏览器加载与归档转换分开。`mhtml_archive.py` 分别处理资源标识、CSS 依赖、HTML 引用和 MIME 编码;入口 `portable_archive` 只组织这些步骤,保留原有本地字体嵌入与缺失资源检查。
## 验证约定
diff --git a/docs/user_manual.md b/docs/user_manual.md
index 9573a2f..90878da 100644
--- a/docs/user_manual.md
+++ b/docs/user_manual.md
@@ -173,7 +173,7 @@ Markdown 支持:
三个 Word 导出引擎均创建 `MDHelper 正文`、`MDHelper 标题 1`、`MDHelper 加粗` 等命名样式。导出后,在 Word 的样式面板中修改相应样式,即可统一调整引用该样式的内容;正文的字体和字号也会传递到未单独设置字体的加粗、强调和链接文字。表格边框及内边距通过 Word 表格样式修改。
-Word 每段文字只能引用一个字符样式,因此加粗链接等组合会生成 `MDHelper 超链接+加粗` 等组合样式;组合不会同时继承多个字符样式。嵌套列表使用基于对应列表样式的层级样式,层级缩进可单独修改。
+Word 每段文字只能引用一个字符样式,因此加粗链接等组合会生成 `MDHelper 超链接+加粗` 等组合样式。不同嵌套顺序分别保存,按 Markdown 从外到内应用格式;含链接的组合以超链接为基准,内层明确设置可覆盖外层。组合不会同时继承多个字符样式,其他组合属性可通过对应组合样式统一修改。嵌套列表使用基于对应列表样式的层级样式,层级缩进可单独修改。
Word 的字符样式会把加粗、斜体和删除线作为与段落格式叠加的开关。导出采用强调保护:明确字符样式中的这些字形设置会固定在对应文字上,避免修改正文或标题样式时反向关闭强调。字体、字号、颜色、下划线和段落仍由命名样式统一控制;受保护的加粗、斜体和删除线不能仅通过 Word 字符样式关闭,可在 MDHelper 调整后重新导出,或在 Word 中清除对应文字的直接字形格式再使用其原生样式规则。
@@ -189,6 +189,8 @@ Word 的字符样式会把加粗、斜体和删除线作为与段落格式叠加
中英文字体及 Word 特有设置使用可编辑的 CSS 自定义属性:`--mdhelper-font-chinese` / `--mdhelper-font-english` 区分字体;`--mdhelper-line-spacing-mode: at-least` 配合磅值 `line-height` 表示最小值行距;`--mdhelper-contextual-spacing: true` 表示同样式段落间不添加间距。这些属性由图形设置自动生成。
+下划线和删除线分别使用 `--mdhelper-underline: true/false`、`--mdhelper-strike: true/false`,配合程序生成的 `text-decoration-line: var(--mdhelper-text-decoration, none)`。未指定的一项继续继承,修改另一项不会将它关闭。也可直接写标准 `text-decoration` / `text-decoration-line`,这时按 CSS 声明顺序、选择器优先级及 `!important` 解析整组文字修饰。
+
`@media`、嵌套规则、局部选择器(例如 `p:hover`、特定类名),以及图形界面无法表示的 `calc()`、动态变量、透明颜色等值会保留在 CSS 中,并在编辑器底部说明同步范围。它们不会被猜测为统一的图形设置或 Word 格式。需要统一控制文档核心排版时,建议修改程序生成的对象规则;扩展规则仍可用于阅读器及 HTML/PDF 的显示效果。
## 10. 媒体与表格
diff --git a/mdhelper/docx_exporter.py b/mdhelper/docx_exporter.py
index f967ba6..cfff1c8 100644
--- a/mdhelper/docx_exporter.py
+++ b/mdhelper/docx_exporter.py
@@ -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'' for name in sorted(source_styles))
+ package.writestr("word/styles.xml", STYLES_XML.replace('', markers + ''))
package.writestr("word/settings.xml", SETTINGS_XML)
relations = ''.join(f'' for href, identifier in links.items())
if has_lists: relations += ''
@@ -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("")
if style.get('strike'): props.append('')
- if style.get("code"):
+ marker = source_style_name(style.get('semantic_order', ()))
+ if marker:
+ props.append(f'')
+ elif style.get("code"):
props.append('')
rpr = f"{''.join(props)}" if props else ""
preserve = ' xml:space="preserve"' if text[:1].isspace() or text[-1:].isspace() else ""
diff --git a/mdhelper/docx_inline.py b/mdhelper/docx_inline.py
new file mode 100644
index 0000000..0118a66
--- /dev/null
+++ b/mdhelper/docx_inline.py
@@ -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 ()
diff --git a/mdhelper/docx_semantic.py b/mdhelper/docx_semantic.py
index 87c8398..7862568 100644
--- a/mdhelper/docx_semantic.py
+++ b/mdhelper/docx_semantic.py
@@ -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)
diff --git a/mdhelper/docx_style.py b/mdhelper/docx_style.py
index 0c69481..f6b3baa 100644
--- a/mdhelper/docx_style.py
+++ b/mdhelper/docx_style.py
@@ -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)))
diff --git a/mdhelper/resources/word_inline_styles.lua b/mdhelper/resources/word_inline_styles.lua
new file mode 100644
index 0000000..42ebfba
--- /dev/null
+++ b/mdhelper/resources/word_inline_styles.lua
@@ -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}}
diff --git a/mdhelper/style_sync.py b/mdhelper/style_sync.py
index 448ba93..3eb9796 100644
--- a/mdhelper/style_sync.py
+++ b/mdhelper/style_sync.py
@@ -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():
diff --git a/tests/test_style_regressions.py b/tests/test_style_regressions.py
index 0f1be5d..bc4c118 100644
--- a/tests/test_style_regressions.py
+++ b/tests/test_style_regressions.py
@@ -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
diff --git a/tests/word_styles_smoke.ps1 b/tests/word_styles_smoke.ps1
index 77655b7..29be388 100644
--- a/tests/word_styles_smoke.ps1
+++ b/tests/word_styles_smoke.ps1
@@ -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) }