From 151b176c1ababbdea066910cf634db006489b08e Mon Sep 17 00:00:00 2001 From: shen Date: Fri, 30 Oct 2026 10:58:37 +0800 Subject: [PATCH] feat: export editable named Word styles and release 0.5.0 --- README.md | 5 +- docs/architecture.md | 6 + docs/user_manual.md | 18 +- mdhelper/__init__.py | 2 +- mdhelper/document_style.py | 24 +- mdhelper/docx_exporter.py | 137 +++++++--- mdhelper/docx_semantic.py | 350 ++++++++++++++++++++++++++ mdhelper/docx_style.py | 145 +++-------- mdhelper/main_window.py | 2 +- mdhelper/style_catalog.py | 6 +- mdhelper/style_dialog.py | 7 +- mdhelper/style_sync.py | 20 +- tests/docx_assertions.py | 53 ++++ tests/test_document_style.py | 6 +- tests/test_export_improvements.py | 2 + tests/test_markdown_compat.py | 2 + tests/test_semantic_style_controls.py | 9 + tests/test_style_sync.py | 4 +- tests/test_word_named_styles.py | 129 ++++++++++ tests/word_styles_smoke.ps1 | 60 +++++ 20 files changed, 818 insertions(+), 169 deletions(-) create mode 100644 mdhelper/docx_semantic.py create mode 100644 tests/docx_assertions.py create mode 100644 tests/test_word_named_styles.py create mode 100644 tests/word_styles_smoke.ps1 diff --git a/README.md b/README.md index e98a8cd..27c030e 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # MDHelper -当前版本:`0.4.0` +当前版本:`0.5.0` MDHelper 是一个本地 Markdown / 代码文档阅读器,使用 PySide6 构建桌面窗口,用 Qt WebEngine 展示由 Markdown 转换得到的 HTML 页面。它面向本地项目文档、技术手册、源码说明和离线帮助文件,重点是离线可用、多标签阅读、全文搜索、样式管理和导出。 @@ -26,7 +26,8 @@ MDHelper 是一个本地 Markdown / 代码文档阅读器,使用 PySide6 构 - 自动刷新当前文档、已打开文档和引用资源;外部修改后会重新读取并渲染。 - 可配置主题颜色、主题背景、正文字号倍率、鼠标滚轮速度、纸张宽度、自动刷新策略和非预览文件打开策略。 - 提供“样式”菜单,支持内置文档样式和自定义样式文件,样式可配置字体、缩进、行距、段前段后间距等。 -- 图形样式支持磅值/中文字号、字体颜色、字符间距、对齐、左右和特殊缩进、同样式段落间距及分页控制。图形设置与高级 CSS 双向同步,三个 DOCX 导出引擎均保留可识别的核心设置;背景、边框及条件规则等扩展效果用于阅读器及 HTML/PDF。 +- “样式 → 样式面板”按 Markdown 语义区分正文、六级标题、引用、三类列表、代码块、表头/单元格以及加粗、强调、删除线、链接和行内代码。支持名称、同类型基准样式、当前段落提示、已用样式筛选及实际阅读预览。 +- 图形样式与高级 CSS 双向同步,支持字体、字符装饰、背景、段落、列表标记及表格边框/内边距。旧配置和项目预设自动兼容。三个 DOCX 引擎均输出共享命名样式,可在 Word 样式面板统一修改;动态 CSS、阴影及条件选择器等扩展效果继续用于阅读器及 HTML/PDF。 - 导出支持 PDF、HTML、DOCX、MHTML;DOCX 可选择 `pandoc` 或 `python-docx` 相关实现。 - 退出时检查未保存内容;另存为到其他目录会复制相对引用图片。MHTML 保存已渲染的图片、公式、图表及样式资源,支持离线携带。 - 图片点击放大,支持缩放、旋转、适应窗口、原始大小、保存图片和在文件夹中显示。 diff --git a/docs/architecture.md b/docs/architecture.md index 0479dc1..6250771 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -27,6 +27,12 @@ ## 配置与迁移 +`style_catalog.py` 定义稳定的语义标识、类型、名称、同类型继承及 Markdown 使用情况。格式声明仍以 `style_sync.py` 解析的核心 CSS 为准,名称与基准单独保存在 `rules._metadata`,通过原有配置和项目预设路径持久化。旧 `list`、`code`、`table` 作为兼容基准,细分对象未设置时继承它们。 + +`style_panel.py` 仅在用户打开时创建,按文档版本缓存语法分析,隐藏时停止刷新;`style_dialog.py` 的实际阅读预览也只在切换到该页时创建。启动路径不创建这些浏览器,不重建主窗口。 + +`docx_style.py` 负责格式字段与 OOXML 属性的转换及属性顺序;`docx_semantic.py` 识别各引擎输出的语义、生成命名段落/字符/表格样式,并移除会遮盖样式的重复直接格式。保留编号、公式、关系和书签;组合字符与加粗段落上下文采用命名变体。`tests/word_styles_smoke.ps1` 使用本机 Word 的独立隐藏实例,验证打开文件、样式修改传播及继承,关闭时不保存测试修改。 + `preferences.py` 定义 `ReaderPreferences` 和 `ApplicationConfiguration`。本地设置与 JSON 导入共用字段、取值检查和旧版迁移规则;`ConfigurationStore` 负责持久化。页面设置保留旧版 PDF 页边距的读取方式。窗口几何状态和草稿仍由各自的界面、文档组件管理。内置文档样式集中在 `style_presets.py`。 ## 编辑器边界 diff --git a/docs/user_manual.md b/docs/user_manual.md index 538b909..ff43542 100644 --- a/docs/user_manual.md +++ b/docs/user_manual.md @@ -152,7 +152,9 @@ Markdown 支持: 图形界面可设置不同对象的字体和段落格式,例如: -- 正文段落、一级到六级标题、列表项、引用、代码块、表格。 +- 正文、一级到六级标题、引用、无序/有序/任务列表、代码块、表头文字和单元格文字。 +- 加粗、强调、删除线、超链接、行内代码采用字符样式;可设置下划线、删除线和背景色,未设置的字体与字号继承所在段落。 +- 表格基准可设置边框颜色、宽度和单元格内边距;列表可设置标记形式与嵌套层级缩进。 - 中文字体和英文字体分开设置。 - 字号支持磅(pt)、像素(px)和中文常用字号,例如五号 10.5 磅;可设置加粗、斜体、字体颜色和字符间距。 - 对齐支持左对齐、居中、右对齐和两端对齐。 @@ -161,7 +163,17 @@ Markdown 支持: - 左右缩进支持字符、磅或厘米;特殊缩进可选择无、首行或悬挂,首行与悬挂互斥。 - 分页支持与下段同页、段中不分页、段前分页和孤行控制。 -“继承”沿用当前文档默认值;数字 0 表示明确清零。复选框方块表示继承、勾选表示开启、空白表示关闭。设置窗口下方提供实时预览;分页效果以 Word 为准。旧样式文件会自动兼容原有的像素字号、字符间距和缩进。 +“继承”沿用基准样式或文档默认值;数字 0 表示明确清零。复选框方块表示继承、勾选表示开启、空白表示关闭。设置窗口下方提供快速预览,“实际阅读效果”页使用阅读器显示完整示例;分页效果以 Word 为准。旧样式文件会自动兼容原有的像素字号、字符间距和缩进。 + +### 样式面板与 Word 导出 + +打开“样式 → 样式面板”,可查看全部样式或当前文档已用样式。编辑 Markdown 时,面板提示光标所在段落及其中包含的字符样式。双击条目修改样式名称、同类型基准及格式;改变样式不会改写 Markdown 内容。基于内置样式修改时自动创建自定义样式集。 + +样式集是一整套格式方案,正文、标题和链接等是其中的单个样式。启用项目默认后,修改作用于当前项目;否则修改全局默认。原有样式文件、配置导入导出和项目模板继续可用。面板和实际阅读预览按需创建,不增加启动阶段的窗口或浏览器切换。 + +三个 Word 导出引擎均创建 `MDHelper 正文`、`MDHelper 标题 1`、`MDHelper 加粗` 等命名样式。导出后,在 Word 的样式面板中修改相应样式,即可统一调整引用该样式的内容;正文的字体和字号也会传递到未单独设置字体的加粗、强调和链接文字。表格边框及内边距通过 Word 表格样式修改。 + +Word 每段文字只能引用一个字符样式,因此加粗链接等组合会生成 `MDHelper 超链接+加粗` 等组合样式;组合优先以超链接为基准,其余效果保存在组合样式中。标题中加粗等情况会生成带段落名称的变体,以适配 Word 的加粗叠加规则。组合和变体都可以在 Word 样式面板统一修改,但不会同时继承多个字符样式。嵌套列表使用基于对应列表样式的层级样式,层级缩进可单独修改。 纸张宽度是全局阅读设置,内置样式不再写死正文宽度,会跟随纸张宽度变化。 @@ -169,7 +181,7 @@ Markdown 支持: “高级 CSS”显示完整的自定义样式。修改图形设置时,只更新对应对象的核心属性;原有背景、边框、阴影、注释和其他对象的规则会保留。直接修改 CSS 后,停止输入约 0.35 秒即可回填到图形设置和预览;立即点击确定也会先同步再保存。CSS 未写完整或存在语法错误时,保留上一次有效设置并提示修正,避免把半成品保存为样式。 -核心同步覆盖对象的常规选择器,例如 `p`、`.reader p`、`h1`、`.reader h1`,以及程序生成的正文、列表、引用、代码和表格选择器。可识别的属性包括 `font-family`、`font-size`、`font-weight`、`font-style`、`color`、`letter-spacing`、`text-align`、`line-height`、`text-indent`、`margin`/四个方向的间距,以及换行、分页属性。支持常见字体简写、间距简写和 `!important`;重置当前对象只清除其核心设置,保留扩展效果。 +核心同步覆盖对象的常规选择器,例如 `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`;重置当前对象只清除其核心设置,保留扩展效果。 例如,将正文规则中的 `font-size: 12pt` 改成 `font-size: 14pt`,图形字号会变为 14 磅,导出 Word 也使用 14 磅。之后在图形界面调整字号,CSS 对应值会随之更新。删除某项属性后,如果没有其他常规规则提供该属性,图形设置显示“继承”。 diff --git a/mdhelper/__init__.py b/mdhelper/__init__.py index c0f411c..bc86b28 100644 --- a/mdhelper/__init__.py +++ b/mdhelper/__init__.py @@ -1,3 +1,3 @@ """MDHelper package.""" -__version__ = "0.4.0" +__version__ = "0.5.0" diff --git a/mdhelper/document_style.py b/mdhelper/document_style.py index 72def5b..8841a40 100644 --- a/mdhelper/document_style.py +++ b/mdhelper/document_style.py @@ -94,8 +94,9 @@ def line_points(rule: dict, font_pt: float) -> float: def resolved_rules(rules: dict | None, font_family: str = "", font_size_px: float = 16, preset: str = "default") -> dict[str, dict]: """Reader defaults, not Word's theme-dependent defaults.""" - from .style_catalog import explicit_rules - rules = explicit_rules(rules) + from .style_catalog import explicit_rules, parent_style, CATALOG + authored = rules if isinstance(rules, dict) else {} + rules = explicit_rules(authored) base = dict(chinese_font_family=font_family or "Microsoft YaHei UI", english_font_family=font_family or "Microsoft YaHei UI", font_size=font_size_px, font_size_unit="px", bold=False, italic=False, font_color="auto", line_spacing_mode="multiple", line_height_value=1.72, @@ -129,11 +130,26 @@ def resolved_rules(rules: dict | None, font_family: str = "", font_size_px: floa rule.update(left_indent_value=2, indent_mode="hanging", indent_value=1) elif target in ("table", 'table_head', 'table_cell'): rule.update(space_before_value=0, space_after_value=0) + if target == 'table_head': rule['bold'] = True from .style_catalog import CHARACTER_DEFAULTS rule.update(CHARACTER_DEFAULTS.get(target, {})) rule.update(normalize_rule((rules or {}).get(target, {}))) result[target] = rule - return result + # An explicitly selected base inherits its defaults as well as declarations. + # Implicit legacy bases keep the same defaults as earlier releases. + inherited = {} + def resolve(target): + if target in inherited: return inherited[target] + parent = parent_style(target, authored) + if parent and CATALOG[target].kind != 'character': + value = dict(resolve(parent)) + value.update(normalize_rule(authored.get(target, {}))) + else: + value = result[target] + inherited[target] = value + return value + for target in result: resolve(target) + return inherited def fmt(value: object) -> str: @@ -220,6 +236,8 @@ def build_document_style_css(rules: dict | None, extra_css: str = "") -> str: contexts = {"paragraph": (("", "p:not(:where(li p, blockquote p, .admonition p, th p, td p))"),), "list": (("", "li"),), "blockquote": (("blockquote > ", "p"), (".admonition > ", "p")), "code": (("", "pre"),), "table": (("th > ", "p"), ("td > ", "p"))} + if target in ('list_bullet', 'list_ordered', 'list_task', 'code_block', 'table_head', 'table_cell'): + contexts[target] = (("", f'[data-mdh-style="{target}"]'),) for scope, tag in contexts.get(target, (("", target),)): parts.append(f".reader {scope}{tag} + {tag} {{ margin-top: 0; }}\n.reader {scope}{tag}:has(+ {tag}) {{ margin-bottom: 0; }}") if extra_css.strip(): diff --git a/mdhelper/docx_exporter.py b/mdhelper/docx_exporter.py index f338d33..f967ba6 100644 --- a/mdhelper/docx_exporter.py +++ b/mdhelper/docx_exporter.py @@ -9,7 +9,7 @@ import time import zipfile from dataclasses import dataclass from pathlib import Path -from xml.sax.saxutils import escape +from xml.sax.saxutils import escape, quoteattr from markdown_it import MarkdownIt from markdown_it.token import Token @@ -96,15 +96,29 @@ def export_markdown_to_docx_builtin(source: str, output_path: Path) -> Path: output_path = output_path.with_suffix(".docx") blocks = _markdown_blocks(source) + links = {} + 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: + if style.get('href'): + style['link_id'] = links.setdefault(style['href'], f'rIdLink{len(links) + 1}') document_xml = _document_xml(blocks) + has_lists = any(isinstance(b, ParagraphBlock) and b.list_kind for b in blocks) output_path.parent.mkdir(parents=True, exist_ok=True) with zipfile.ZipFile(output_path, "w", compression=zipfile.ZIP_DEFLATED) as package: - package.writestr("[Content_Types].xml", CONTENT_TYPES_XML) + content_types = CONTENT_TYPES_XML + if has_lists: + content_types = content_types.replace('', '') + package.writestr('word/numbering.xml', _numbering_xml(blocks)) + 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) package.writestr("word/settings.xml", SETTINGS_XML) - package.writestr("word/_rels/document.xml.rels", DOCUMENT_RELS_XML) + relations = ''.join(f'' for href, identifier in links.items()) + if has_lists: relations += '' + package.writestr("word/_rels/document.xml.rels", DOCUMENT_RELS_XML.replace('', relations + '')) return output_path @@ -191,7 +205,11 @@ def export_markdown_to_docx_python_docx(source: str, output_path: Path) -> Path: normal.element.rPr.rFonts.set(qn("w:eastAsia"), "Microsoft YaHei") document.styles.add_style("MDHelper Code Char", WD_STYLE_TYPE.CHARACTER) - for block in _markdown_blocks(source): + blocks = _markdown_blocks(source) + from docx.oxml import parse_xml + for numbering in parse_xml(_numbering_xml(blocks)): + document.part.numbering_part.element.append(numbering) + for block in blocks: if isinstance(block, TableBlock): _add_python_docx_table(document, block) continue @@ -222,6 +240,9 @@ def _add_python_docx_paragraph(document: object, block: ParagraphBlock) -> None: style = "Quote" paragraph = document.add_paragraph(style=style) + if block.list_kind: + from docx.oxml import parse_xml + paragraph._p.get_or_add_pPr().append(parse_xml(f'')) if block.quote_depth: paragraph.paragraph_format.left_indent = _docx_inches(0.35) for text, run_style in block.runs: @@ -229,16 +250,25 @@ def _add_python_docx_paragraph(document: object, block: ParagraphBlock) -> None: for part_index, part in enumerate(parts): if part_index: paragraph.add_run().add_break() - run = paragraph.add_run(part) - if run_style.get("bold"): - run.bold = True - if run_style.get("italic"): - run.italic = True - if run_style.get("code") or block.style == "Code": - if run_style.get("code"): - run.style = "MDHelper Code Char" - run.font.name = "Consolas" - run.font.size = _docx_pt(10) + _add_python_docx_run(paragraph, part, run_style) + + +def _add_python_docx_run(paragraph, text, style): + from docx.oxml import OxmlElement + from docx.oxml.ns import qn + from docx.opc.constants import RELATIONSHIP_TYPE as RT + run = paragraph.add_run(text) + if style.get('bold'): run.bold = True + if style.get('italic'): run.italic = True + if style.get('strike'): run.font.strike = True + if style.get('code'): + run.style = 'MDHelper Code Char' + run.font.name = 'Consolas' + if style.get('href'): + link = OxmlElement('w:hyperlink') + link.set(qn('r:id'), paragraph.part.relate_to(style['href'], RT.HYPERLINK, is_external=True)) + run._r.addprevious(link) + link.append(run._r) def _add_python_docx_table(document: object, block: TableBlock) -> None: @@ -253,15 +283,7 @@ def _add_python_docx_table(document: object, block: TableBlock) -> None: runs = row[col_index] if col_index < len(row) else [("", {})] paragraph = cell.paragraphs[0] for text, run_style in runs: - run = paragraph.add_run(text) - if run_style.get("bold") or row_index == 0: - run.bold = True - if run_style.get("italic"): - run.italic = True - if run_style.get("code"): - run.style = "MDHelper Code Char" - run.font.name = "Consolas" - run.font.size = _docx_pt(10) + _add_python_docx_run(paragraph, text, run_style) def _docx_pt(value: int) -> object: @@ -278,10 +300,13 @@ def _docx_inches(value: float) -> object: @dataclass class ParagraphBlock: - runs: list[tuple[str, dict[str, bool]]] + runs: list[tuple[str, dict[str, object]]] style: str = "Normal" list_kind: str = "" quote_depth: int = 0 + list_level: int = 0 + list_id: int = 0 + list_start: int = 1 @dataclass @@ -295,6 +320,9 @@ class _DocxBuilder: self.blocks: list[ParagraphBlock | TableBlock] = [] self.index = 0 self.list_stack: list[str] = [] + self.list_ids: list[int] = [] + self.list_starts: list[int] = [] + self.list_sequence = 1000 self.quote_depth = 0 def build(self) -> list[ParagraphBlock | TableBlock]: @@ -315,12 +343,15 @@ class _DocxBuilder: self.quote_depth += 1 elif token.type == "blockquote_close": self.quote_depth = max(0, self.quote_depth - 1) - elif token.type == "bullet_list_open": - self.list_stack.append("bullet") - elif token.type == "ordered_list_open": - self.list_stack.append("number") + elif token.type in ('bullet_list_open', 'ordered_list_open'): + self.list_stack.append('bullet' if token.type == 'bullet_list_open' else 'number') + self.list_sequence += 1 + self.list_ids.append(self.list_sequence) + self.list_starts.append(int(token.attrGet('start') or 1)) elif token.type in {"bullet_list_close", "ordered_list_close"} and self.list_stack: self.list_stack.pop() + self.list_ids.pop() + self.list_starts.pop() elif token.type == "table_open": self.blocks.append(self._collect_table()) continue @@ -332,7 +363,9 @@ class _DocxBuilder: def _add_next_inline(self, style: str, list_kind: str = "") -> None: inline = self.tokens[self.index + 1] if self.index + 1 < len(self.tokens) else None runs = _inline_runs(inline.children if inline is not None else None) - self.blocks.append(ParagraphBlock(runs, style=style, list_kind=list_kind, quote_depth=self.quote_depth)) + 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)) self.index += 3 def _collect_table(self) -> TableBlock: @@ -356,12 +389,13 @@ class _DocxBuilder: return TableBlock(rows) -def _inline_runs(children: list[Token] | None) -> list[tuple[str, dict[str, bool]]]: +def _inline_runs(children: list[Token] | None) -> list[tuple[str, dict[str, object]]]: if not children: return [("", {})] - runs: list[tuple[str, dict[str, bool]]] = [] + runs: list[tuple[str, dict[str, object]]] = [] style_stack: list[str] = [] + links = [] for child in children: if child.type == "strong_open": style_stack.append("bold") @@ -371,11 +405,17 @@ def _inline_runs(children: list[Token] | None) -> list[tuple[str, dict[str, bool style_stack.append("italic") elif child.type == "em_close": _pop_style(style_stack, "italic") - elif child.type == "code_inline": - runs.append((child.content, {"code": True})) - elif child.type in {"text", "html_inline"}: + 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_close': + if links: links.pop() + elif child.type in {"text", "html_inline", 'code_inline'}: text = html.unescape(child.content) if child.type == "html_inline" else child.content - runs.append((text, {"bold": "bold" in style_stack, "italic": "italic" in style_stack})) + style = {key: True for key in style_stack} + if child.type == 'code_inline': style['code'] = True + if links: style['href'] = links[-1] + runs.append((text, style)) elif child.type in {"softbreak", "hardbreak"}: runs.append(("\n", {})) elif child.children: @@ -393,7 +433,7 @@ def _pop_style(style_stack: list[str], value: str) -> None: def _document_xml(blocks: list[ParagraphBlock | TableBlock]) -> str: body = "\n".join(_block_xml(block) for block in blocks) return f""" - + {body} @@ -415,16 +455,14 @@ def _paragraph_xml(block: ParagraphBlock) -> str: props = [f''] if block.style != "Normal" else [] if block.list_kind: props = [''] - bullet = "•" if block.list_kind == "bullet" else "1." - block = ParagraphBlock([(bullet + " ", {"bold": True}), *block.runs], style=block.style, quote_depth=block.quote_depth) - props.append('') + props.append(f'') if block.quote_depth: props.append('') ppr = f"{''.join(props)}" if props else "" return f"{ppr}{''.join(_run_xml(text, style) for text, style in block.runs)}" -def _run_xml(text: str, style: dict[str, bool]) -> str: +def _run_xml(text: str, style: dict[str, object]) -> str: if text == "\n": return "" props = [] @@ -432,11 +470,28 @@ def _run_xml(text: str, style: dict[str, bool]) -> str: props.append("") if style.get("italic"): props.append("") + if style.get('strike'): props.append('') if 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 "" - return f"{rpr}{escape(text)}" + run = f"{rpr}{escape(text)}" + if style.get('link_id'): run = f'{run}' + return run + + +def _numbering_xml(blocks): + """Use real numbering for both basic engines, including starts and nesting.""" + definitions = {b.list_id: b for b in blocks if isinstance(b, ParagraphBlock) and b.list_kind} + abstracts, instances = [], [] + for identifier, block in definitions.items(): + levels = [] + for level in range(9): + fmt, text = ('decimal', f'%{level + 1}.') if block.list_kind == 'number' else ('bullet', '•') + levels.append(f'') + abstracts.append(f'{"".join(levels)}') + instances.append(f'') + return f'{"".join(abstracts + instances)}' def _table_xml(block: TableBlock) -> str: diff --git a/mdhelper/docx_semantic.py b/mdhelper/docx_semantic.py new file mode 100644 index 0000000..d74f8db --- /dev/null +++ b/mdhelper/docx_semantic.py @@ -0,0 +1,350 @@ +"""Attach editable, shared Word styles without rewriting document content. + +Only the formatting owned by MDHelper is removed from document.xml. Numbering, +relationships, equations, bookmarks and other engine content remain in place. +""" +from __future__ import annotations + +from copy import deepcopy +import re +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 +from .docx_style import W, NS, child, val, properties, _run_properties, _paragraph_properties, _order_properties + +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() + + +def style_id(key): + return 'MDHelper' + ''.join(word.capitalize() for word in key.split('_')) + + +def reference(parent, name): + node = parent.find(W + name) if parent is not None else None + return node.get(W + 'val', '') if node is not None else '' + + +def remove_fields(parent, names): + for name in names: + for element in parent.findall(W + name): parent.remove(element) + + +def _delta(current, base, authored=None): + """Keep just changed properties, allowing subsequent Word base-style edits.""" + if base is None: return + authored = authored or {} + fields = {'rFonts': ('english_font_family', 'chinese_font_family'), 'sz': ('font_size',), 'szCs': ('font_size',), + 'b': ('bold',), 'bCs': ('bold',), 'i': ('italic',), 'iCs': ('italic',), 'strike': ('strike',), + 'u': ('underline',), 'shd': ('background_color',), 'color': ('font_color',), 'jc': ('alignment',), + 'ind': ('indent_mode', 'indent_value', 'left_indent_value', 'right_indent_value'), + 'spacing': ('letter_spacing', 'space_before_value', 'space_after_value', 'line_height_value'), + 'keepNext': ('keep_with_next',), 'keepLines': ('keep_lines_together',), 'pageBreakBefore': ('page_break_before',), + 'widowControl': ('widow_control',), 'contextualSpacing': ('contextual_spacing',)} + for node in list(current): + if any(field in authored for field in fields.get(ET.QName(node).localname, ())): continue + old = base.find(node.tag) + if old is not None and node.attrib == old.attrib and node.text == old.text and not len(node) and not len(old): + current.remove(node) + elif old is not None and node.tag in {W + 'rFonts', W + 'spacing', W + 'ind'}: + # These properties merge attribute by attribute in Word. + for key in list(node.attrib): + if old.get(key) == node.get(key): del node.attrib[key] + if not node.attrib and not len(node): current.remove(node) + + +class WordStyles: + def __init__(self, styles, numbering, rules, **defaults): + self.styles, self.numbering = styles, numbering + self.rules = rules if isinstance(rules, dict) else {} + self.effective = resolved_rules(self.rules, **defaults) + self.explicit = explicit_rules(self.rules) + 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 = {} + self.characters = {} + self.number_overrides = {} + for key in CATALOG: + if CATALOG[key].kind == 'character': self.character(key) + elif CATALOG[key].kind == 'paragraph': self.paragraph(key) + self.table() + + def chain(self, identifier): + seen = set() + while identifier in self.original and identifier not in seen: + seen.add(identifier) + style = self.original[identifier] + yield style + identifier = reference(style, 'basedOn') + + def names(self, identifier): + return ' '.join([identifier] + [reference(s, 'name') for s in self.chain(identifier)]).lower() + + def new(self, identifier, kind, name, base=''): + if name in self.used_names: name += ' [' + identifier + ']' + self.used_names.add(name) + style = ET.SubElement(self.styles, W + 'style', {W + 'type': kind, W + 'customStyle': '1', W + 'styleId': identifier}) + val(style, 'name', name) + if base: val(style, 'basedOn', base) + val(style, 'uiPriority', 10 + len(self.created)) + child(style, 'qFormat') + self.created[identifier] = style + return style + + def paragraph(self, key): + identifier = style_id(key) + if identifier in self.created: return identifier + base = parent_style(key, self.rules) + base_id = self.paragraph(base) if base else '' + # Table styles cannot be a paragraph's basedOn. A shared paragraph base + # carries the legacy table text settings and remains editable in Word. + if key in ('table_head', 'table_cell') and not base: + base_id = 'MDHelperTableText' + if base_id not in self.created: + table_text = self.new(base_id, 'paragraph', 'MDHelper 表格文字基准') + _paragraph_properties(child(table_text, 'pPr'), self.effective['table']) + _run_properties(child(table_text, 'rPr'), self.effective['table']) + remove_fields(child(table_text, 'rPr'), ('shd',)) + base = 'table' + style = self.new(identifier, 'paragraph', 'MDHelper ' + style_name(key, self.rules), base_id) + rule = self.effective[key] + _paragraph_properties(child(style, 'pPr'), rule) + _run_properties(child(style, 'rPr'), rule) + remove_fields(child(style, 'rPr'), ('shd',)) + if base: + for tag, writer in (('pPr', _paragraph_properties), ('rPr', _run_properties)): + base_props = ET.Element(W + tag) + writer(base_props, self.effective[base]) + if tag == 'rPr': remove_fields(base_props, ('shd',)) + _delta(child(style, tag), base_props, normalize_rule(self.rules.get(key))) + if re.fullmatch('h[1-6]', key): val(child(style, 'pPr'), 'outlineLvl', int(key[1]) - 1) + val(style, 'next', style_id('paragraph')) + return identifier + + def character_rule(self, key): + if key not in self.characters: + base = parent_style(key, self.rules) + rule = dict(CHARACTER_DEFAULTS.get(key, {})) + if base: rule.update(self.character_rule(base)) + rule.update(normalize_rule(self.explicit[key])) + self.characters[key] = rule + return self.characters[key] + + def character(self, key): + identifier = style_id(key) + if identifier in self.created: return identifier + base = parent_style(key, self.rules) + base_id = self.character(base) if base else '' + style = self.new(identifier, 'character', 'MDHelper ' + style_name(key, self.rules), base_id) + rule = self.character_rule(key) + _run_properties(child(style, 'rPr'), rule) + if base: + old = ET.Element(W + 'rPr') + _run_properties(old, self.character_rule(base)) + _delta(child(style, 'rPr'), old, normalize_rule(self.rules.get(key))) + 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) + 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])) + props, old = child(style, 'rPr'), ET.Element(W + 'rPr') + _run_properties(props, merged) + _run_properties(old, self.character_rule(keys[0])) + _delta(props, old) + # Word XORs style-level emphasis with the paragraph's emphasis. A named + # context variant compensates for that (e.g. **text** in a bold heading), + # keeping all formatting editable in the Styles panel, not on each run. + compensate = [field for field in ('bold', 'italic', 'strike') if field in merged and self.effective[paragraph_target].get(field)] + if compensate: + context_id = identifier + 'In' + style_id(paragraph_target)[8:] + if context_id not in self.created: + style = self.new(context_id, 'character', 'MDHelper ' + '+'.join(style_name(k, self.rules) for k in keys) + '(' + style_name(paragraph_target, self.rules) + ')', identifier) + for field in compensate: + for tag in {'bold': ('b', 'bCs'), 'italic': ('i', 'iCs'), 'strike': ('strike',)}[field]: val(child(style, 'rPr'), tag, int(not merged[field])) + identifier = context_id + return identifier + + def syntax_style(self, run_id, target): + """Preserve token colors, while letting the code paragraph own its font.""" + identifier = 'MDHelperSyntax' + run_id + if identifier in self.created: return identifier + props = ET.Element(W + 'rPr') + for original in reversed(list(self.chain(run_id))): + source = original.find(W + 'rPr') + if source is None: continue + for item in source: + remove_fields(props, (ET.QName(item).localname,)) + props.append(deepcopy(item)) + remove_fields(props, ('rFonts', 'sz', 'szCs', 'rStyle')) + for field, tags in (('font_color', ('color',)), ('bold', ('b', 'bCs')), ('italic', ('i', 'iCs')), ('letter_spacing', ('spacing',))): + if field in self.explicit[target]: remove_fields(props, tags) + if not len(props): return '' + style = self.new(identifier, 'character', 'MDHelper 代码着色 ' + (reference(self.original.get(run_id), 'name') or run_id)) + style.append(props) + return identifier + + def list_level(self, numpr): + level = int(number(reference(numpr, 'ilvl'))) + num_id = reference(numpr, 'numId') + if self.numbering is None or not num_id: return level, None + num = self.numbering.find(f"w:num[@w:numId='{num_id}']", NS) + abstract_id = reference(num, 'abstractNumId') + abstract = self.numbering.find(f"w:abstractNum[@w:abstractNumId='{abstract_id}']", NS) + return level, abstract.find(f"w:lvl[@w:ilvl='{level}']", NS) if abstract is not None else None + + def classify(self, paragraph, original_id): + names = self.names(original_id) + heading = re.search(r'heading\s*([1-6])', names) + if heading: return 'h' + heading[1] + if any(word in names for word in ('sourcecode', 'source code', 'code', 'verbatim')): return 'code_block' + for ancestor in paragraph.iterancestors(W + 'tc'): + row = ancestor.getparent() + table = row.getparent() + is_head = row is table.find(W + 'tr') or row.find('w:trPr/w:tblHeader', NS) is not None + return 'table_head' if is_head else 'table_cell' + ppr = properties(paragraph, 'pPr') + numpr = ppr.find(W + 'numPr') + if numpr is None: + inherited = next((s.find('w:pPr/w:numPr', NS) for s in self.chain(original_id) if s.find('w:pPr/w:numPr', NS) is not None), None) + if inherited is not None: + numpr = deepcopy(inherited) + ppr.append(numpr) + if 'list' in names or numpr is not None: + text = ''.join(paragraph.itertext()).lstrip('• ') + if re.match(r'^(?:\[[ xX]\]|[☐☒☑])', text): return 'list_task' + _, level = self.list_level(numpr) + if reference(level, 'lvlText') in ('☐', '☒', '☑'): return 'list_task' + fmt = reference(level, 'numFmt') + ordered = (fmt and fmt != 'bullet') or 'number' in names or re.match(r'^\d+[.)]\s', text) + return 'list_ordered' if ordered else 'list_bullet' + if any(word in names for word in ('quote', 'quotation', 'blockquote', 'blocktext', 'block text')): return 'blockquote' + return 'paragraph' + + def nested_list(self, target, level): + identifier = style_id(target) + 'Level' + str(level + 1) + if identifier not in self.created: + style = self.new(identifier, 'paragraph', 'MDHelper ' + style_name(target, self.rules) + f'(第 {level + 1} 级)', self.paragraph(target)) + rule = dict(self.effective[target]) + points = font_points(rule) + offset = level * number(rule.get('level_indent', 36)) + if rule['left_indent_unit'] == 'em': rule['left_indent_value'] += offset / points + else: + rule['left_indent_value'] = length_points(rule['left_indent_value'], rule['left_indent_unit'], points) + offset + rule['left_indent_unit'] = 'pt' + temp = ET.Element(W + 'pPr') + _paragraph_properties(temp, rule) + child(style, 'pPr').append(temp.find(W + 'ind')) + return identifier + + def apply_list_marker(self, numpr, target, marker): + level, original_level = self.list_level(numpr) + if original_level is None: return + formats = {'decimal': ('decimal', f'%{level + 1}.'), 'lower-alpha': ('lowerLetter', f'%{level + 1}.'), + 'upper-alpha': ('upperLetter', f'%{level + 1}.'), 'lower-roman': ('lowerRoman', f'%{level + 1}.'), + 'upper-roman': ('upperRoman', f'%{level + 1}.'), 'disc': ('bullet', '•'), 'circle': ('bullet', '○'), + 'square': ('bullet', '▪'), 'none': ('none', '')} + if marker not in formats: return + key = (reference(numpr, 'numId'), target, marker) + if key not in self.number_overrides: + # Numbering definitions may be shared by unrelated semantic types. + # Clone before modifying, retaining starts and per-instance overrides. + num = deepcopy(self.numbering.find(f"w:num[@w:numId='{key[0]}']", NS)) + abstract = deepcopy(original_level.getparent()) + num_id = 1 + max(int(n.get(W + 'numId')) for n in self.numbering.findall(W + 'num')) + abstract_id = 1 + max(int(n.get(W + 'abstractNumId')) for n in self.numbering.findall(W + 'abstractNum')) + num.set(W + 'numId', str(num_id)); val(num, 'abstractNumId', abstract_id) + abstract.set(W + 'abstractNumId', str(abstract_id)) + self.numbering.extend((abstract, num)) + self.number_overrides[key] = str(num_id) + val(numpr, 'numId', self.number_overrides[key]) + _, numbering_level = self.list_level(numpr) + fmt, text = formats[marker] + val(numbering_level, 'numFmt', fmt); val(numbering_level, 'lvlText', text) + rpr = numbering_level.find(W + 'rPr') + if rpr is not None: remove_fields(rpr, ('rFonts',)) + + def table(self): + identifier = style_id('table') + style = self.new(identifier, 'table', 'MDHelper ' + style_name('table', self.rules)) + rule = self.effective['table'] + props = child(style, 'tblPr') + borders = child(props, 'tblBorders') + for edge in ('top', 'left', 'bottom', 'right', 'insideH', 'insideV'): + element = child(borders, edge) + width = number(rule.get('border_width', .5)) + color = str(rule.get('border_color', '#d0d7de')) + element.attrib.update({W + 'val': 'single' if width and color != 'transparent' else 'nil', W + 'sz': str(max(2, round(width * 8))), W + 'color': color.lstrip('#') if color != 'transparent' else 'auto'}) + if 'cell_padding' in rule: + margins = child(props, 'tblCellMar') + for side in ('top', 'left', 'bottom', 'right'): + child(margins, side).attrib.update({W + 'w': str(round(number(rule['cell_padding']) * 20)), W + 'type': 'dxa'}) + if 'background_color' in rule: + child(child(style, 'tcPr'), 'shd').attrib.update({W + 'val': 'clear', W + 'fill': str(rule['background_color']).lstrip('#') if rule['background_color'] != 'transparent' else 'auto'}) + for target, condition in (('table_head', 'firstRow'), ('table_cell', 'band1Horz'), ('table_cell', 'band2Horz')): + color = self.explicit[target].get('background_color') + if color: + conditional = ET.SubElement(style, W + 'tblStylePr', {W + 'type': condition}) + child(child(conditional, 'tcPr'), 'shd').attrib.update({W + 'val': 'clear', W + 'fill': color.lstrip('#') if color != 'transparent' else 'auto'}) + return identifier + + def apply_run(self, run, target): + rpr = properties(run, 'rPr') + run_id = reference(rpr, 'rStyle') + names = self.names(run_id) + keys = set() + for tag, key, words in (('b', 'strong', ('strong',)), ('i', 'emphasis', ('emphasis',)), ('strike', 'strike', ('strike',))): + node = rpr.find(W + tag) + if node is not None and node.get(W + 'val', '1') not in ('0', 'false', 'off') or any(word in names for word in words): keys.add(key) + if any(a.tag == W + 'hyperlink' for a in run.iterancestors()) or 'hyperlink' in names: keys.add('link') + 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) + 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',)) + + def apply(self, document): + for paragraph in document.iter(W + 'p'): + ppr = properties(paragraph, 'pPr') + target = self.classify(paragraph, reference(ppr, 'pStyle') or 'Normal') + identifier = self.paragraph(target) + if target.startswith('list_'): + numpr = ppr.find(W + '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) + remove_fields(ppr, PARAGRAPH_FIELDS) + val(ppr, 'pStyle', identifier) + for run in paragraph.iter(W + 'r'): self.apply_run(run, target) + for table in document.iter(W + 'tbl'): + props = properties(table, 'tblPr') + remove_fields(props, ('tblBorders', 'tblCellMar', 'shd')) + val(props, 'tblStyle', style_id('table')) + child(props, 'tblLook').attrib.update({W + 'val': '0020', W + 'firstRow': '1', W + 'noHBand': '0', W + 'noVBand': '1'}) + for cell in table.iter(W + 'tc'): + tcpr = cell.find(W + 'tcPr') + if tcpr is not None: remove_fields(tcpr, ('shd', 'tcBorders', 'tcMar')) + + +def apply_semantic_styles(path, rules, **defaults): + with zipfile.ZipFile(path) as package: + 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']) + for filename, root in parts.items(): + _order_properties(root) + payloads[filename] = ET.tostring(root, encoding='UTF-8', xml_declaration=True, standalone=True) + with zipfile.ZipFile(path, 'w', compression=zipfile.ZIP_DEFLATED) as package: + for info, _ in entries: package.writestr(info, payloads[info.filename]) diff --git a/mdhelper/docx_style.py b/mdhelper/docx_style.py index cfbaa4a..0c69481 100644 --- a/mdhelper/docx_style.py +++ b/mdhelper/docx_style.py @@ -1,12 +1,10 @@ """Apply reader typography to OOXML without round-tripping document content.""" from __future__ import annotations -import re -import zipfile from pathlib import Path from lxml import etree as ET -from .document_style import font_points, length_points, line_points, number, resolved_rules +from .document_style import font_points, length_points, line_points, number W = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}" NS = {"w": W[1:-1]} @@ -35,6 +33,10 @@ def _order_properties(root): # ECMA-376 property children are ordered. Keep unrelated properties (math, # numbering, bookmarks, tracked changes) while inserting ours in that order. orders = { + 'numbering': 'numPicBullet abstractNum num numIdMacAtCleanup', + 'style': 'name aliases basedOn next link autoRedefine hidden uiPriority semiHidden unhideWhenUsed qFormat locked personal personalCompose personalReply rsid pPr rPr tblPr trPr tcPr tblStylePr', + 'tblPr': 'tblStyle tblpPr tblOverlap bidiVisual tblStyleRowBandSize tblStyleColBandSize tblW jc tblCellSpacing tblInd tblBorders shd tblLayout tblCellMar tblLook tblCaption tblDescription tblPrChange', + 'tcPr': 'cnfStyle tcW gridSpan hMerge vMerge tcBorders shd noWrap tcMar textDirection tcFitText vAlign hideMark cellIns cellDel cellMerge tcPrChange', "pPr": "pStyle keepNext keepLines pageBreakBefore framePr widowControl numPr suppressLineNumbers pBdr shd tabs suppressAutoHyphens kinsoku wordWrap overflowPunct topLinePunct autoSpaceDE autoSpaceDN bidi adjustRightInd snapToGrid spacing ind contextualSpacing mirrorIndents suppressOverlap jc textDirection textAlignment textboxTightWrap outlineLvl divId cnfStyle rPr sectPr pPrChange", "rPr": "rStyle rFonts b bCs i iCs caps smallCaps strike dstrike outline shadow emboss imprint noProof snapToGrid vanish webHidden color spacing w kern position sz szCs highlight u effect bdr shd fitText vertAlign rtl cs em lang eastAsianLayout specVanish oMath rPrChange", } @@ -44,27 +46,35 @@ def _order_properties(root): element[:] = sorted(element, key=lambda e: ranks.get(e.tag, len(ranks))) -def _run_properties(rpr, rule, preserve_emphasis=False): - fonts = child(rpr, "rFonts") +def _run_properties(rpr, rule): + """Write only declared fields; character styles must inherit paragraph fonts.""" + fonts = child(rpr, "rFonts") if any(k in rule for k in ('english_font_family', 'chinese_font_family')) else None # Explicit font selections must override the engine's theme fonts. - for attr in list(fonts.attrib): + for attr in list(fonts.attrib) if fonts is not None else []: if attr.endswith("Theme"): del fonts.attrib[attr] - for key in ("ascii", "hAnsi", "cs"): - fonts.set(W + key, str(rule["english_font_family"])) - fonts.set(W + "eastAsia", str(rule["chinese_font_family"])) - size = max(1, round(font_points(rule) * 2)) - val(rpr, "sz", size) - val(rpr, "szCs", size) - for key, xml in (("bold", "b"), ("italic", "i")): - existing = rpr.find(W + xml) - inline_on = existing is not None and existing.get(W + "val", "1") not in ("0", "false", "off") - val(rpr, xml, int(rule[key] or (preserve_emphasis and inline_on))) - val(rpr, xml + "Cs", int(rule[key] or (preserve_emphasis and inline_on))) - color = child(rpr, "color") - color.attrib.clear() - color.set(W + "val", str(rule["font_color"]).lstrip("#")) - val(rpr, "spacing", round(number(rule["letter_spacing"]) * 20)) + if 'english_font_family' in rule: + for key in ("ascii", "hAnsi", "cs"): + fonts.set(W + key, str(rule["english_font_family"])) + if 'chinese_font_family' in rule: fonts.set(W + "eastAsia", str(rule['chinese_font_family'])) + if 'font_size' in rule: + size = max(1, round(font_points(rule) * 2)) + val(rpr, "sz", size) + val(rpr, "szCs", size) + for key, xml in (("bold", "b"), ("italic", "i"), ('strike', 'strike')): + if key in rule: + val(rpr, xml, int(rule[key])) + if key != 'strike': val(rpr, xml + 'Cs', int(rule[key])) + if 'font_color' in rule: + color = child(rpr, "color") + color.attrib.clear() + color.set(W + "val", str(rule["font_color"]).lstrip("#")) + if 'letter_spacing' in rule: val(rpr, "spacing", round(number(rule["letter_spacing"]) * 20)) + if 'underline' in rule: val(rpr, 'u', 'single' if rule['underline'] else 'none') + if 'background_color' in rule: + shade = child(rpr, 'shd') + shade.set(W + 'val', 'clear') + shade.set(W + 'fill', str(rule['background_color']).lstrip('#') if rule['background_color'] != 'transparent' else 'auto') def _paragraph_properties(ppr, rule): @@ -94,6 +104,10 @@ def _paragraph_properties(ppr, rule): ind.set(W + kind + "Chars", str(round(amount * 100))) # Override paragraph style inheritance, including Word's default grid snapping. val(ppr, "snapToGrid", 0) + if 'background_color' in rule: + shade = child(ppr, 'shd') + shade.set(W + 'val', 'clear') + shade.set(W + 'fill', str(rule['background_color']).lstrip('#') if rule['background_color'] != 'transparent' else 'auto') for key, xml in (("contextual_spacing", "contextualSpacing"), ("keep_with_next", "keepNext"), ("keep_lines_together", "keepLines"), ("page_break_before", "pageBreakBefore"), ("widow_control", "widowControl")): @@ -102,90 +116,5 @@ def _paragraph_properties(ppr, rule): def apply_docx_styles(path: Path, rules: dict | None = None, *, font_family: str = "", font_size_px: float = 16, preset: str = "default") -> None: - effective = resolved_rules(rules, font_family, font_size_px, preset) - with zipfile.ZipFile(path) as package: - 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) - document = ET.fromstring(payloads["word/document.xml"], parser) - styles = ET.fromstring(payloads["word/styles.xml"], parser) - style_map = {s.get(W + "styleId"): s for s in styles.findall(W + "style")} - - def style_chain(style_id): - visited = set() - while style_id in style_map and style_id not in visited: - visited.add(style_id) - style = style_map[style_id] - yield style - base = style.find(W + "basedOn") - style_id = base.get(W + "val") if base is not None else None - - def target_for(paragraph, style_id): - chain = list(style_chain(style_id)) - names = " ".join([style_id or ""] + [s.find(W + "name").get(W + "val", "") for s in chain if s.find(W + "name") is not None]).lower() - heading = re.search(r"heading\s*([1-6])", names) - if heading: - return "h" + heading[1] - if any(word in names for word in ("sourcecode", "source code", "code", "verbatim")): - return "code" - if any(a.tag == W + "tc" for a in paragraph.iterancestors()): - return "table" - if "list" in names or paragraph.find("w:pPr/w:numPr", NS) is not None or any(s.find("w:pPr/w:numPr", NS) is not None for s in chain): - return "list" - if any(word in names for word in ("quote", "quotation", "blockquote", "blocktext", "block text")): - return "blockquote" - return "paragraph" - - generated = {} - for paragraph in document.iter(W + "p"): - ppr = properties(paragraph, "pPr") - style_ref = ppr.find(W + "pStyle") - original_id = style_ref.get(W + "val", "Normal") if style_ref is not None else "Normal" - target = target_for(paragraph, original_id) - rule = effective[target] - # Preserve the source style chain (numbering, outline levels, table style). - # Share one style for all normal body variants so contextual spacing works. - key = (target, original_id if target != "paragraph" else "Normal") - if key not in generated: - identifier = f"MDHelper{len(generated) + 1}" - while identifier in style_map: - identifier += "x" - generated[key] = identifier - style = ET.SubElement(styles, W + "style", {W + "type": "paragraph", W + "styleId": identifier}) - val(style, "name", f"MDHelper {target} ({key[1]})") - if key[1] in style_map: - val(style, "basedOn", key[1]) - _paragraph_properties(child(style, "pPr"), rule) - _run_properties(child(style, "rPr"), rule) - val(ppr, "pStyle", generated[key]) - paragraph_rule = rule - level = ppr.find("w:numPr/w:ilvl", NS) - if target == "list" and level is not None and number(level.get(W + "val")) > 0: - # Retain nested list levels while applying the selected base indent. - paragraph_rule = dict(rule) - offset = number(level.get(W + "val")) * 36 - if rule["left_indent_unit"] == "em": - # A style's leftChars takes precedence over a direct left value; - # keep the coordinate system to override that inherited value. - paragraph_rule["left_indent_value"] = number(rule["left_indent_value"]) + offset / font_points(rule) - else: - paragraph_rule["left_indent_value"] = length_points(rule["left_indent_value"], rule["left_indent_unit"], font_points(rule)) + offset - paragraph_rule["left_indent_unit"] = "pt" - _paragraph_properties(ppr, paragraph_rule) - for run in paragraph.iter(W + "r"): - rpr = properties(run, "rPr") - run_style = rpr.find(W + "rStyle") - run_id = run_style.get(W + "val", "") if run_style is not None else "" - # Character-level code uses the code font settings; ordinary emphasis - # and hyperlinks retain their semantic tags and relationships. - run_rule = dict(rule) - if "code" in run_id.lower() or "verbatim" in run_id.lower(): - for field in ("chinese_font_family", "english_font_family", "font_size", "font_size_unit"): - run_rule[field] = effective["code"][field] - _run_properties(rpr, run_rule, preserve_emphasis=True) - for filename, root in (("word/document.xml", document), ("word/styles.xml", styles)): - _order_properties(root) - payloads[filename] = ET.tostring(root, encoding="UTF-8", xml_declaration=True, standalone=True) - with zipfile.ZipFile(path, "w", compression=zipfile.ZIP_DEFLATED) as package: - for info, _ in entries: - package.writestr(info, payloads[info.filename]) + from .docx_semantic import apply_semantic_styles + apply_semantic_styles(path, rules, font_family=font_family, font_size_px=font_size_px, preset=preset) diff --git a/mdhelper/main_window.py b/mdhelper/main_window.py index 838e94e..951c5b6 100644 --- a/mdhelper/main_window.py +++ b/mdhelper/main_window.py @@ -1174,7 +1174,7 @@ class MainWindow(QMainWindow): style = self.custom_document_styles.get(style_id, {}) if isinstance(style.get("rules"), dict) or "extra_css" in style: if style.get("css_sync_version") == 1: - return render_css(str(style.get("css") or ""), style.get("rules") or {}) + return render_css(str(style.get("css") or ""), style.get("rules") or {}, self.document_font_family, self.document_font_size) return build_document_style_css( style.get("rules") if isinstance(style.get("rules"), dict) else {}, str(style.get("extra_css") or ""), diff --git a/mdhelper/style_catalog.py b/mdhelper/style_catalog.py index 39f6b4e..ad0e95d 100644 --- a/mdhelper/style_catalog.py +++ b/mdhelper/style_catalog.py @@ -86,9 +86,11 @@ def explicit_rules(rules): if base and CATALOG[key].kind == 'character': inherited = {**CHARACTER_DEFAULTS.get(base, {}), **inherited} if key in ('table_head', 'table_cell') and not base: - inherited.update({k: v for k, v in rules.get('table', {}).items() if k not in {'border_color', 'border_width', 'cell_padding'}}) + 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 {'border_color', 'border_width', 'cell_padding'}}) if key == 'inline_code' and not base: - inherited.update({k: v for k, v in rules.get('code', {}).items() if k in CHARACTER_FIELDS}) + legacy = rules.get('code') if isinstance(rules.get('code'), dict) else {} + 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} result[key] = inherited diff --git a/mdhelper/style_dialog.py b/mdhelper/style_dialog.py index 98f9b5a..b2adfec 100644 --- a/mdhelper/style_dialog.py +++ b/mdhelper/style_dialog.py @@ -393,7 +393,8 @@ class DocumentStyleEditorDialog(QDialog): content = MarkdownRenderer(root).render_source(sample, root / '__style_preview__.md', theme=getattr(parent, 'theme', 'light'), document_font_family=getattr(parent, 'document_font_family', ''), document_font_size=getattr(parent, 'document_font_size', 16), - document_style_css=render_css(self.extra_css_edit.toPlainText(), self.rules)) + document_style_css=render_css(self.extra_css_edit.toPlainText(), self.rules, + getattr(parent, 'document_font_family', ''), getattr(parent, 'document_font_size', 16))) self.actual_preview.setHtml(content) def closeEvent(self, event): @@ -451,8 +452,8 @@ class DocumentStyleEditorDialog(QDialog): self._select(self.based_on_box, parent_style(key, self.rules)) character = CATALOG[self._current_target].kind == 'character' for row in range(self.paragraph_row_start, self.paragraph_row_end): self.form.setRowVisible(row, not character) - self.form.setRowVisible(self.border_row, not character) - self.form.setRowVisible(self.padding_row, not character) + self.form.setRowVisible(self.border_row, self._current_target == 'table') + self.form.setRowVisible(self.padding_row, self._current_target == 'table') self.form.setRowVisible(self.marker_row, self._current_target.startswith('list')) self.form.setRowVisible(self.level_row, self._current_target.startswith('list')) self.background_edit.setText(rule.get('background_color', '')) diff --git a/mdhelper/style_sync.py b/mdhelper/style_sync.py index ae9ab31..ac746ab 100644 --- a/mdhelper/style_sync.py +++ b/mdhelper/style_sync.py @@ -290,6 +290,14 @@ class _CoreRuleReader: self.read('text-indent', self.indent) self.pagination() self.choice('--mdhelper-contextual-spacing', 'contextual_spacing', {'true': True, 'false': False}) + from .style_catalog import CATALOG, CHARACTER_FIELDS + unsupported = set() + if self.target != 'table': unsupported.update(('border_color', 'border_width', 'cell_padding')) + if not self.target.startswith('list'): unsupported.update(('list_marker', 'level_indent')) + if CATALOG[self.target].kind == 'character': unsupported.update(set(self.rule) - CHARACTER_FIELDS) + for field in sorted(unsupported & self.rule.keys()): + self.rule.pop(field) + self.result.notes.append(f'{LABELS[self.target]}的 {field} 仅保留为 CSS(不适用于该 Word 样式类型)') return self.rule def decoration(self, value): @@ -520,10 +528,15 @@ def patch_core(source: str, target: str, before: dict, after: dict, *, reset=Fal return result -def render_css(source: str, rules: dict) -> str: +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 + from .style_catalog import explicit_rules, normalize_metadata, CATALOG inherited = explicit_rules(rules) + 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] 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) @@ -540,7 +553,8 @@ def normalize_payload(payload: dict, fallback_name="自定义样式", font_size_ source = source_from_payload(payload) result = analyze_css(source, font_size_px) from .style_catalog import normalize_metadata - metadata = normalize_metadata((payload.get('rules') or {}).get('_metadata')) + supplied_rules = payload.get('rules') if isinstance(payload.get('rules'), dict) else {} + metadata = normalize_metadata(supplied_rules.get('_metadata')) if metadata: result.rules['_metadata'] = metadata return {"name": str(payload.get("name") or fallback_name).strip() or fallback_name, diff --git a/tests/docx_assertions.py b/tests/docx_assertions.py new file mode 100644 index 0000000..1f078f3 --- /dev/null +++ b/tests/docx_assertions.py @@ -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 diff --git a/tests/test_document_style.py b/tests/test_document_style.py index 12f6f06..b1325cf 100644 --- a/tests/test_document_style.py +++ b/tests/test_document_style.py @@ -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 diff --git a/tests/test_export_improvements.py b/tests/test_export_improvements.py index 6b42468..3f54c2c 100644 --- a/tests/test_export_improvements.py +++ b/tests/test_export_improvements.py @@ -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]) diff --git a/tests/test_markdown_compat.py b/tests/test_markdown_compat.py index 3c5433f..30d7adb 100644 --- a/tests/test_markdown_compat.py +++ b/tests/test_markdown_compat.py @@ -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)) diff --git a/tests/test_semantic_style_controls.py b/tests/test_semantic_style_controls.py index c6383c1..2f37ecb 100644 --- a/tests/test_semantic_style_controls.py +++ b/tests/test_semantic_style_controls.py @@ -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: diff --git a/tests/test_style_sync.py b/tests/test_style_sync.py index 8b1f81c..281d655 100644 --- a/tests/test_style_sync.py +++ b/tests/test_style_sync.py @@ -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() diff --git a/tests/test_word_named_styles.py b/tests/test_word_named_styles.py new file mode 100644 index 0000000..01e06b8 --- /dev/null +++ b/tests/test_word_named_styles.py @@ -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'] diff --git a/tests/word_styles_smoke.ps1 b/tests/word_styles_smoke.ps1 new file mode 100644 index 0000000..ab7facb --- /dev/null +++ b/tests/word_styles_smoke.ps1 @@ -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 +}