diff --git a/docs/architecture.md b/docs/architecture.md
index 749759f..d33ebfe 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -29,6 +29,8 @@
`style_catalog.py` 定义稳定的语义标识、类型、名称、同类型继承及 Markdown 使用情况。格式声明仍以 `style_sync.py` 解析的核心 CSS 为准,名称与基准单独保存在 `rules._metadata`,通过原有配置和项目预设路径持久化。旧 `list`、`code`、`table` 作为兼容基准,细分对象未设置时继承它们。
+从内置样式复制时,`rules._preset` 保留原默认值来源;绝对首行/悬挂缩进使用 `indent_unit`,缺省仍为旧版的字符单位。图形编辑器对比控件加载快照,只写回实际编辑的组,避免范围限制和显示精度改写未编辑的 CSS。
+
`style_panel.py` 仅在用户打开时创建,按文档版本缓存语法分析,隐藏时停止刷新;`style_dialog.py` 的实际阅读预览也只在切换到该页时创建。启动路径不创建这些浏览器,不重建主窗口。
`docx_style.py` 负责格式字段与 OOXML 属性的转换及属性顺序;`docx_semantic.py` 识别各引擎输出的语义、生成命名段落/字符/表格样式,并按属性保留继承。保留编号、公式、关系和书签;除用于防止 Word 反向切换的明确字符字形(加粗、斜体、删除线)外,不重复写入直接字体、字号、颜色和段落格式。组合字符采用命名样式。`tests/word_styles_smoke.ps1` 使用本机 Word 的独立隐藏实例,验证打开文件、样式修改传播及继承,关闭时不保存测试修改。
@@ -49,6 +51,8 @@
CSS 同步按三个步骤处理:`_collect_cascade` 决定生效的声明,`_CoreRuleReader` 转换可表达的字体和段落属性,`analyze_css` 汇总结果。无法映射的 CSS 继续保留原文,不改写级联规则或 Word 的支持范围。
+明确无效的声明在级联选择前忽略;简写中任一无效组件使整条简写失效,有效但不支持的表达式仍遮盖前面的值。普通 `p` 同时映射引用段落及 `rules._list_paragraph` 上下文;各引擎通过临时段落标记区分宽松列表和紧凑列表。表格文字使用独立内容容器承载段间距,表格边框和单元格内边距保持原位置。
+
`render_css` 使用与图形写入相同的字体变量表达继承,并生成列表层级缩进及独立文字修饰的辅助规则。显式取消列表基准时会恢复该语义类型的默认格式,旧配置缺少元数据时仍保留兼容基准。
`docx_inline.py` 定义转换阶段的临时字符样式标记,记录 Markdown 从外到内的语义顺序。两个基础引擎直接记录解析栈;Pandoc 使用随包资源 `word_inline_styles.lua` 记录同一顺序。最终样式处理替换并删除临时标记,脚注仍保留原段落样式、编号和关系;导出文件不需要脚本或宏。
diff --git a/docs/user_manual.md b/docs/user_manual.md
index 3e4fdce..7f005ed 100644
--- a/docs/user_manual.md
+++ b/docs/user_manual.md
@@ -187,6 +187,10 @@ Word 的字符样式会把加粗、斜体和删除线作为与段落格式叠加
核心同步覆盖对象的常规选择器,例如 `p`、`.reader p`、`h1`、`.reader h1`、`strong`、`em`、`s`、`a`,以及程序生成的 `data-mdh-style` 语义选择器。可识别的属性包括字体、字号、颜色、字符间距、`text-decoration-line`、`background-color`、对齐、行距、缩进、四向间距、换行分页,以及 `border-color` / `border-width`、表格 `padding` 和 `list-style-type`。支持常见字体简写、间距简写和 `!important`;重置当前对象只清除其核心设置,保留扩展效果。
+普通 `p` 选择器也作用于引用和宽松列表中的段落,Word 会保留这些上下文格式;紧凑列表没有独立段落元素,不受该选择器影响。表头和单元格的段前、段后及左右间距作用于内部文字区域,表格内边距仍独立设置。明显无效的 CSS 值(例如 `font-size:nope`)会被忽略并提示,前面的有效声明继续同步;有效但不能转换为 Word 的扩展表达式仍保留为 CSS。
+
+颜色选择“随所在文字颜色”(CSS `currentColor` / `inherit`)会继承段落或外层文字的颜色,不等同于“自动(随主题)”。如果它同时需要取消某个字符基准中的固定颜色,Word 无法只取消一个继承属性,因此导出会将该基准的其他已解析格式保留在当前命名字符样式内;导出后请修改此命名样式,其他普通样式的基准继承保持不变。
+
例如,将正文规则中的 `font-size: 12pt` 改成 `font-size: 14pt`,图形字号会变为 14 磅,导出 Word 也使用 14 磅。之后在图形界面调整字号,CSS 对应值会随之更新。删除某项属性后,如果没有其他常规规则提供该属性,图形设置显示“继承”。
中英文字体及 Word 特有设置使用可编辑的 CSS 自定义属性:`--mdhelper-font-chinese` / `--mdhelper-font-english` 区分字体;`--mdhelper-line-spacing-mode: at-least` 配合磅值 `line-height` 表示最小值行距;`--mdhelper-contextual-spacing: true` 表示同样式段落间不添加间距。这些属性由图形设置自动生成。
diff --git a/mdhelper/document_style.py b/mdhelper/document_style.py
index 76f3bfa..3e94e70 100644
--- a/mdhelper/document_style.py
+++ b/mdhelper/document_style.py
@@ -65,7 +65,7 @@ def normalize_rule(value: object) -> dict[str, Any]:
if key in rule and not isinstance(rule[key], bool):
rule.pop(key)
for key in ('font_color', 'background_color', 'border_color'):
- if key in rule and not re.fullmatch(r"auto|transparent|#[0-9a-fA-F]{6}", str(rule[key])):
+ if key in rule and not re.fullmatch(r"auto|transparent|inherit|#[0-9a-fA-F]{6}", str(rule[key])):
rule.pop(key)
for key, allowed in {"alignment": {"left", "center", "right", "justify"},
"indent_mode": {"none", "first", "hanging"},
diff --git a/mdhelper/docx_exporter.py b/mdhelper/docx_exporter.py
index 26b76e0..a0afe05 100644
--- a/mdhelper/docx_exporter.py
+++ b/mdhelper/docx_exporter.py
@@ -15,7 +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
+from .docx_inline import source_style_name, LIST_PARAGRAPH_STYLE
WP_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
@@ -118,6 +118,7 @@ def export_markdown_to_docx_builtin(source: str, output_path: Path) -> Path:
package.writestr("_rels/.rels", PACKAGE_RELS_XML)
package.writestr("word/document.xml", document_xml)
markers = ''.join(f'
. Let the semantic
# block own its typography instead of leaving that old child rule in charge.
block = {**inherited.get('code_block', {}), **rules.get('code_block', {})}
@@ -598,7 +652,7 @@ def normalize_payload(payload: dict, fallback_name="自定义样式", font_size_
if metadata:
result.rules['_metadata'] = metadata
from .style_presets import DOCUMENT_STYLE_PRESETS
- if supplied_rules.get('_preset') in DOCUMENT_STYLE_PRESETS:
+ if isinstance(supplied_rules.get('_preset'), str) and supplied_rules['_preset'] in DOCUMENT_STYLE_PRESETS:
result.rules['_preset'] = supplied_rules['_preset']
return {"name": str(payload.get("name") or fallback_name).strip() or fallback_name,
"css_sync_version": 1, "css": source,
diff --git a/tests/conftest.py b/tests/conftest.py
index 91c0ce3..bfc4960 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -8,6 +8,7 @@ os.environ.setdefault("QTWEBENGINE_CHROMIUM_FLAGS", "--disable-gpu --no-sandbox
import pytest
from PySide6.QtWidgets import QApplication
from PySide6.QtGui import QFontDatabase
+from PySide6.QtCore import QCoreApplication, QEvent
@pytest.fixture(scope="session", autouse=True)
@@ -19,3 +20,12 @@ def qt_application():
QFontDatabase.addApplicationFont(os.path.join(os.environ.get("WINDIR", "C:/Windows"), "Fonts", "msyh.ttc"))
yield app
app.processEvents()
+
+
+@pytest.fixture(autouse=True)
+def release_closed_widgets(qt_application):
+ yield
+ # processEvents alone does not flush DeferredDelete without app.exec().
+ # Release closed WebEngine pages before the next rendering regression.
+ QCoreApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete)
+ qt_application.processEvents()
diff --git a/tests/gui_smoke.py b/tests/gui_smoke.py
index e0fb3f2..6e4e571 100644
--- a/tests/gui_smoke.py
+++ b/tests/gui_smoke.py
@@ -92,12 +92,11 @@ def main() -> int:
(switch_root / "first.md").write_text("# First\n", encoding="utf-8")
(nested_root / "inside.md").write_text("# Inside\n", encoding="utf-8")
first_reader = empty_window._reader_from_tab(fixed_reader_host)
- first_load_loop = QEventLoop()
- if first_reader is not None:
- first_reader.loadFinished.connect(first_load_loop.quit)
empty_window.open_document(project_root / "sample.md", add_history=False)
- QTimer.singleShot(5000, first_load_loop.quit)
- first_load_loop.exec()
+ wait_until(
+ lambda: first_reader is not None and fixed_reader_host.stack.currentWidget() is first_reader,
+ timeout_ms=30000,
+ )
if empty_window.tabs.currentWidget() is not fixed_reader_host:
checks.append("first_open_fixed_tab_host")
if first_reader is None or fixed_reader_host.stack.currentWidget() is not first_reader:
@@ -682,9 +681,7 @@ def main() -> int:
window.set_theme_background_from_action(peony_action)
if window.theme_background != "peony":
checks.append("background_enabled_for_colorful")
- toc_refresh_loop = QEventLoop()
- QTimer.singleShot(700, toc_refresh_loop.quit)
- toc_refresh_loop.exec()
+ wait_until(lambda: not window.web_view.page().isLoading(), timeout_ms=30000)
if not hasattr(window, "manage_external_apps_action"):
checks.append("manage_external_apps_action")
close_window = MainWindow(project_root=project_root)
@@ -724,11 +721,9 @@ def main() -> int:
result["scroll_y"] = float(value or 0)
except (TypeError, ValueError):
result["scroll_y"] = -1
- toc_loop.quit()
window.web_view.page().runJavaScript("Math.max(0, window.scrollY || document.documentElement.scrollTop || 0)", store_scroll)
- QTimer.singleShot(1000, toc_loop.quit)
- toc_loop.exec()
+ wait_until(lambda: "scroll_y" in result, timeout_ms=30000)
if result.get("scroll_y", -1) < 0:
checks.append("toc_second_click_scroll")
if window.search_index.search("斐波那契") == []:
@@ -820,18 +815,11 @@ def main() -> int:
pass
pdf_test_path = project_root / "__gui_smoke_export.pdf"
try:
- pdf_loop = QEventLoop()
window.export_pdf_to_path(pdf_test_path)
-
- def poll_pdf_export() -> None:
- if pdf_test_path.exists() or getattr(window, "_pdf_export_page", None) is None:
- pdf_loop.quit()
- return
- QTimer.singleShot(100, poll_pdf_export)
-
- QTimer.singleShot(100, poll_pdf_export)
- QTimer.singleShot(15000, pdf_loop.quit)
- pdf_loop.exec()
+ wait_until(
+ lambda: pdf_test_path.exists() or getattr(window, "_pdf_export_page", None) is None,
+ timeout_ms=60000,
+ )
if not pdf_test_path.exists() or pdf_test_path.stat().st_size <= 0:
checks.append("export_pdf_write")
finally:
diff --git a/tests/test_semantic_style_controls.py b/tests/test_semantic_style_controls.py
index 2f37ecb..1bf641b 100644
--- a/tests/test_semantic_style_controls.py
+++ b/tests/test_semantic_style_controls.py
@@ -55,7 +55,7 @@ def test_browser_semantic_styles_and_contextual_character_inheritance(qt_applica
page = QWebEnginePage(); loaded = []
page.loadFinished.connect(loaded.append); page.setHtml(content)
def wait(condition):
- deadline = time.monotonic() + 10
+ deadline = time.monotonic() + 30
while not condition() and time.monotonic() < deadline: qt_application.processEvents(); time.sleep(.01)
assert condition()
try:
diff --git a/tests/test_style_regressions.py b/tests/test_style_regressions.py
index bc4c118..b45385d 100644
--- a/tests/test_style_regressions.py
+++ b/tests/test_style_regressions.py
@@ -3,7 +3,7 @@ import time
import zipfile
from lxml import etree as ET
import pytest
-from PySide6.QtCore import Qt
+from PySide6.QtCore import Qt, QCoreApplication, QEvent
from PySide6.QtWebEngineCore import QWebEnginePage
from mdhelper.docx_exporter import export_markdown_to_docx
from mdhelper.docx_style import W, NS, val
@@ -37,7 +37,7 @@ def parts(path):
def browser(qapp, tmp_path, payload, source, expression):
page = QWebEnginePage(); loaded = []; result = []
def wait(predicate):
- end = time.monotonic() + 12
+ end = time.monotonic() + 30
while not predicate() and time.monotonic() < end: qapp.processEvents(); time.sleep(.01)
assert predicate(), 'WebEngine timed out'
try:
@@ -48,7 +48,10 @@ def browser(qapp, tmp_path, payload, source, expression):
page.runJavaScript('JSON.stringify(' + expression + ')', result.append)
wait(lambda: result)
return json.loads(result[0])
- finally: page.deleteLater(); qapp.processEvents()
+ finally:
+ page.deleteLater()
+ QCoreApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete)
+ qapp.processEvents()
@pytest.mark.parametrize('engine', ['builtin', 'python-docx', 'pandoc'])
diff --git a/tests/test_style_revision_052.py b/tests/test_style_revision_052.py
index b33dd34..af92013 100644
--- a/tests/test_style_revision_052.py
+++ b/tests/test_style_revision_052.py
@@ -17,6 +17,8 @@ REPEATED_RULES = {'strong': {'font_color': '#ff0000'}, 'emphasis': {'font_color'
ABSOLUTE_PAYLOAD = {'css_sync_version': 1,
'css': '.reader h1 {font-size:20pt;} .reader h2 {text-indent:24pt;}',
'rules': {'_metadata': {'h2': {'based_on': 'h1'}}}}
+SCOPED_SOURCE = 'BodyText\n\n> QuoteText\n\n- TightItem\n- TightSecond\n\n---\n\n- LooseItem\n\n- LooseSecond'
+SCOPED_CSS = 'p {color:red; font-size:20pt;} blockquote {color:blue;}'
def text_run(document, word):
@@ -128,3 +130,120 @@ def test_absolute_first_indent_survives_inherited_font_and_gui_roundtrip(qt_appl
ind = effective_document(doc, styles).find('.//w:pPr/w:ind', NS)
assert ind.get(W + 'firstLine') == '480' and ind.get(W + 'firstLineChars') == '0'
finally: dialog.close()
+
+
+@pytest.mark.parametrize('engine', ENGINES)
+def test_p_selector_covers_quotes_and_loose_lists_without_changing_tight_lists(qt_application, tmp_path, engine):
+ payload = normalize_payload({'css': SCOPED_CSS})
+ assert payload['rules']['blockquote']['font_color'] == '#ff0000'
+ dialog = DocumentStyleEditorDialog(payload)
+ try:
+ dialog.font_size_spin.setValue(21)
+ payload = normalize_payload(dialog.style_payload())
+ assert payload['rules']['blockquote']['font_size'] == 21
+ assert payload['rules']['_list_paragraph']['font_size'] == 21
+ finally: dialog.close()
+ path = export_markdown_to_docx(SCOPED_SOURCE, tmp_path / 'scope.docx', engine=engine, style_rules=payload['rules'])
+ doc, styles = parts(path)
+ rendered = effective_document(doc, styles)
+ for word in ('BodyText', 'QuoteText', 'LooseItem', 'LooseSecond'):
+ run = text_run(rendered, word)
+ assert run.find('w:rPr/w:color', NS).get(W + 'val') == 'ff0000', (engine, word)
+ assert run.find('w:rPr/w:sz', NS).get(W + 'val') == '42'
+ assert text_run(rendered, 'TightItem').find('w:rPr/w:color', NS).get(W + 'val') == 'auto'
+ for word in ('LooseItem', 'LooseSecond'):
+ p = next(p for p in doc.iter(W + 'p') if word in ''.join(p.itertext()))
+ assert p.find('w:pPr/w:numPr', NS) is not None
+ assert not any('MDHelperSourceListParagraph' in str(s.attrib) for s in styles)
+
+
+def test_reader_p_scope_and_table_paragraph_spacing(qt_application, tmp_path):
+ payload = normalize_payload({'css': SCOPED_CSS})
+ colors = browser(qt_application, tmp_path, payload, SCOPED_SOURCE,
+ "[...document.querySelectorAll('p,li')].filter(e=>['BodyText','QuoteText','TightItem','LooseItem'].includes(e.textContent.trim())).map(e=>[e.textContent.trim(),getComputedStyle(e).color])")
+ assert ['BodyText', 'rgb(255, 0, 0)'] in colors and ['QuoteText', 'rgb(255, 0, 0)'] in colors
+ assert ['LooseItem', 'rgb(255, 0, 0)'] in colors and ['TightItem', 'rgb(35, 39, 47)'] in colors
+ sizes = []
+ for amount in (0, 30):
+ payload = normalize_payload({'rules': {'table_cell': {'space_before_value': amount, 'space_before_unit': 'pt',
+ 'space_after_value': amount, 'space_after_unit': 'pt'}}})
+ sizes.append(browser(qt_application, tmp_path, payload, '| Header |\n|---|\n| Cell |',
+ "(()=>{let c=document.querySelector('td'),p=c.querySelector('.mdhelper-cell-paragraph');return [c.getBoundingClientRect().height,p.getBoundingClientRect().top-c.getBoundingClientRect().top]})()"))
+ assert sizes[1][0] - sizes[0][0] == pytest.approx(80, abs=.1)
+ assert sizes[1][1] - sizes[0][1] == pytest.approx(40, abs=.1)
+
+
+@pytest.mark.parametrize('engine', ENGINES)
+def test_contextual_color_follows_paragraph_and_outer_inline_color(qt_application, tmp_path, engine):
+ source = 'Body **Colored** [Link](https://example.com)\n\n# Heading **HeadingColor**\n\n**[Nested](https://example.com)**'
+ css = '.reader p {color:red;} h1 {color:blue;} strong {color:currentColor;} a {color:currentColor;}'
+ payload = normalize_payload({'css': css})
+ assert payload['rules']['strong']['font_color'] == 'inherit'
+ dialog = DocumentStyleEditorDialog(payload)
+ try:
+ dialog.select_target('strong')
+ assert dialog.color_combo.currentData() == 'inherit'
+ assert normalize_payload(dialog.style_payload()) == payload
+ finally: dialog.close()
+ path = export_markdown_to_docx(source, tmp_path / 'color.docx', engine=engine, style_rules=payload['rules'])
+ doc, styles = parts(path)
+ rendered = effective_document(doc, styles)
+ for word, color in (('Colored', 'ff0000'), ('Link', 'ff0000'), ('Nested', 'ff0000'), ('HeadingColor', '0000ff')):
+ assert text_run(rendered, word).find('w:rPr/w:color', NS).get(W + 'val') == color
+ assert styles.find("w:style[@w:styleId='MDHelperStrong']/w:rPr/w:color", NS) is None
+
+
+@pytest.mark.parametrize('invalid', ['font-size:nope', 'font-size:-2pt !important', 'font-size:20wrong', 'color:invalid !important'])
+def test_invalid_declaration_keeps_previous_valid_core_value(qt_application, tmp_path, invalid):
+ css = 'p {font-size:20pt;color:red;' + invalid + ';}'
+ payload = normalize_payload({'css': css})
+ assert payload['rules']['paragraph']['font_size'] == 20
+ assert payload['rules']['paragraph']['font_color'] == '#ff0000'
+ assert payload['css'] == css and analyze_css(css).notes
+ value = browser(qt_application, tmp_path, payload, 'Text',
+ "(()=>{const s=getComputedStyle(document.querySelector('p'));return [parseFloat(s.fontSize),s.color]})()")
+ assert value[0] == pytest.approx(20 * 4/3, abs=.01) and value[1] == 'rgb(255, 0, 0)'
+
+
+@pytest.mark.parametrize('value', ['calc(10pt + 2vw)', '5vw', 'larger', 'var(--size)'])
+def test_valid_extended_values_do_not_restore_obsolete_core_values(value):
+ result = analyze_css('p {font-size:20pt;font-size:' + value + ';color:red;}')
+ assert 'font_size' not in result.rules['paragraph']
+ assert result.notes
+
+
+def test_graphical_quote_override_wins_over_broad_p_rule(qt_application, tmp_path):
+ dialog = DocumentStyleEditorDialog({'css': SCOPED_CSS})
+ try:
+ dialog.select_target('blockquote')
+ dialog.color_button.setText('#008800')
+ dialog._store_and_refresh()
+ payload = dialog.style_payload()
+ assert payload['rules']['blockquote']['font_color'] == '#008800'
+ assert payload['rules']['paragraph']['font_color'] == '#ff0000'
+ assert browser(qt_application, tmp_path, payload, '> Quote',
+ "getComputedStyle(document.querySelector('blockquote p')).color") == 'rgb(0, 136, 0)'
+ finally: dialog.close()
+
+
+@pytest.mark.parametrize('engine', ENGINES)
+@pytest.mark.parametrize('colored_base', [False, True])
+def test_contextual_color_preserves_other_resolved_character_fields(tmp_path, engine, colored_base):
+ rules = {'paragraph': {'font_color': '#ff0000'}, 'emphasis': {'english_font_family': 'Arial'},
+ 'strong': {'font_color': 'inherit'}, '_metadata': {'strong': {'based_on': 'emphasis'}}}
+ if colored_base: rules['emphasis']['font_color'] = '#0000ff'
+ path = export_markdown_to_docx('**InheritedText**', tmp_path / 'context-base.docx', engine=engine, style_rules=rules)
+ doc, styles = parts(path)
+ run = text_run(effective_document(doc, styles), 'InheritedText')
+ assert run.find('w:rPr/w:color', NS).get(W + 'val') == 'ff0000'
+ assert run.find('w:rPr/w:rFonts', NS).get(W + 'ascii') == 'Arial'
+ assert run.find('w:rPr/w:i', NS).get(W + 'val') == '1'
+ if not colored_base:
+ assert styles.find("w:style[@w:styleId='MDHelperStrong']/w:basedOn", NS).get(W + 'val') == 'MDHelperEmphasis'
+
+
+def test_invalid_shorthand_does_not_apply_its_valid_components():
+ result = analyze_css('p {margin:20pt; margin:3pt nope; font-size:18pt; font:14pt/nope Arial;}')
+ rule = result.rules['paragraph']
+ assert rule['space_before_value'] == rule['space_after_value'] == rule['left_indent_value'] == rule['right_indent_value'] == 20
+ assert rule['font_size'] == 18
diff --git a/tests/word_styles_smoke.ps1 b/tests/word_styles_smoke.ps1
index 426a447..2672508 100644
--- a/tests/word_styles_smoke.ps1
+++ b/tests/word_styles_smoke.ps1
@@ -12,7 +12,7 @@ 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, UNIT_RULES, NESTED_SOURCE, NESTED_RULES
-from test_style_revision_052 import REPEATED_SOURCE, REPEATED_RULES, ABSOLUTE_PAYLOAD
+from test_style_revision_052 import REPEATED_SOURCE, REPEATED_RULES, ABSOLUTE_PAYLOAD, SCOPED_SOURCE, SCOPED_CSS
from mdhelper.style_sync import normalize_payload
folder = Path(tempfile.mkdtemp(prefix='MDHelper-Word-Styles-'))
rules = {'h2': {'bold': False}, '_metadata': {'h2': {'based_on': 'h1'}}}
@@ -25,6 +25,11 @@ for engine in ('builtin', 'python-docx', 'pandoc'):
export_markdown_to_docx('- OuterList\n - InnerList', folder / (engine + '-list.docx'), engine=engine)
export_markdown_to_docx('## Indented', folder / (engine + '-absolute.docx'), engine=engine, style_rules=normalize_payload(ABSOLUTE_PAYLOAD)['rules'])
export_markdown_to_docx('BookText', folder / (engine + '-preset.docx'), engine=engine, style_rules={'_preset': 'serif'}, preset='custom:copy')
+ export_markdown_to_docx(SCOPED_SOURCE, folder / (engine + '-scope.docx'), engine=engine, style_rules=normalize_payload({'css': SCOPED_CSS})['rules'])
+ export_markdown_to_docx('Body **ContextColor** [ContextLink](https://example.com)', folder / (engine + '-context.docx'), engine=engine,
+ style_rules=normalize_payload({'css': 'p {color:red;} strong,a {color:currentColor;}'})['rules'])
+ export_markdown_to_docx('ValidValue', folder / (engine + '-fallback.docx'), engine=engine,
+ style_rules=normalize_payload({'css': 'p {font-size:20pt;font-size:nope;color:red;color:invalid;}'})['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()
@@ -109,6 +114,23 @@ print(folder)
} finally { $doc.Close(0); [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($doc) }
}
Write-Output "$engine passed: repeated inline styles, nested list edits, absolute indents and copied presets."
+ foreach ($case in @('scope', 'context', 'fallback')) {
+ $doc = $word.Documents.Open((Join-Path $testDirectory "$engine-$case.docx"), $false, $true)
+ try {
+ $texts = switch ($case) { 'scope' { @('BodyText', 'QuoteText', 'LooseItem', 'LooseSecond') }; 'context' { @('ContextColor', 'ContextLink') }; 'fallback' { @('ValidValue') } }
+ foreach ($text in $texts) {
+ $range = $doc.Content.Duplicate
+ if (-not $range.Find.Execute($text)) { throw "Missing $text" }
+ if ($range.Font.Color -ne 255) { throw "$engine lost $case color for $text." }
+ if ($case -ne 'context' -and $range.Font.Size -ne 20) { throw "$engine lost $case font size." }
+ }
+ if ($case -eq 'scope') {
+ $range = $doc.Content.Duplicate; [void]$range.Find.Execute('TightItem')
+ if ($range.Font.Color -eq 255) { throw "$engine applied paragraph CSS to tight list." }
+ }
+ } finally { $doc.Close(0); [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($doc) }
+ }
+ Write-Output "$engine passed: paragraph selector scope, contextual colors and invalid-value fallback."
}
} finally {
if ($word) { $word.Quit(); [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($word) }