From 7f9e7ff01b646e9040b4f5ceaf155e0f78c3c4e1 Mon Sep 17 00:00:00 2001 From: shen Date: Thu, 29 Oct 2026 14:50:16 +0800 Subject: [PATCH] feat: complete typography settings and preserve Word styles --- README.md | 5 +- docs/user_manual.md | 18 +- mdhelper/__init__.py | 2 +- mdhelper/document_style.py | 199 +++++++++++ mdhelper/docx_exporter.py | 69 +++- mdhelper/docx_style.py | 185 ++++++++++ mdhelper/main_window.py | 9 +- mdhelper/resources/reader.css | 2 + mdhelper/style_dialog.py | 631 ++++++++++++++++------------------ tests/test_document_style.py | 179 ++++++++++ tests/test_renderer.py | 2 +- 11 files changed, 934 insertions(+), 367 deletions(-) create mode 100644 mdhelper/document_style.py create mode 100644 mdhelper/docx_style.py create mode 100644 tests/test_document_style.py diff --git a/README.md b/README.md index 746ddf0..bdffea8 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # MDHelper -当前版本:`0.2.0` +当前版本:`0.2.1` MDHelper 是一个本地 Markdown / 代码文档阅读器,使用 PySide6 构建桌面窗口,用 Qt WebEngine 展示由 Markdown 转换得到的 HTML 页面。它面向本地项目文档、技术手册、源码说明和离线帮助文件,重点是离线可用、多标签阅读、全文搜索、样式管理和导出。 @@ -19,6 +19,7 @@ MDHelper 是一个本地 Markdown / 代码文档阅读器,使用 PySide6 构 - 自动刷新当前文档、已打开文档和引用资源;外部修改后会重新读取并渲染。 - 可配置主题颜色、主题背景、正文字号倍率、鼠标滚轮速度、纸张宽度、自动刷新策略和非预览文件打开策略。 - 提供“样式”菜单,支持内置文档样式和自定义样式文件,样式可配置字体、缩进、行距、段前段后间距等。 +- 图形样式支持磅值/中文字号、字体颜色、字符间距、对齐、左右和特殊缩进、同样式段落间距及分页控制;三个 DOCX 导出引擎均保留这些设置。高级 CSS 仅用于阅读器及 HTML/PDF。 - 导出支持 PDF、HTML、DOCX、MHTML;DOCX 可选择 `pandoc` 或 `python-docx` 相关实现。 - 图片点击放大,支持缩放、旋转、适应窗口、原始大小、保存图片和在文件夹中显示。 - 表格支持横向滚动和一键复制。 @@ -115,7 +116,7 @@ MDHelper 是一个本地 Markdown / 代码文档阅读器,使用 PySide6 构 首次缺少 Inno Setup 时会从官方来源下载、校验发布者签名并安装到 `pack\.tools`;后续构建复用。 需要可用的 64 位 Python 3.10+;兼容当前项目的两种 `mdhelper_env` 目录布局。 -安装程序位于 `pack\output\MDHelper-Setup-0.2.0-x64.exe`(版本号自动读取),同目录包含 SHA256 校验文件。 +安装程序位于 `pack\output\MDHelper-Setup-0.2.1-x64.exe`(版本号自动读取),同目录包含 SHA256 校验文件。 默认按当前用户安装,提供开始菜单入口、可选桌面快捷方式,以及 Windows 卸载入口。 程序运行时无需单独安装 Python 或 Pandoc。 diff --git a/docs/user_manual.md b/docs/user_manual.md index 5db4bd6..3da23ce 100644 --- a/docs/user_manual.md +++ b/docs/user_manual.md @@ -2,7 +2,7 @@ MDHelper 是一个本地 Markdown / 代码文档阅读器,适合阅读项目说明、技术手册、源码旁文档和离线帮助文件。它使用 PySide6 提供桌面窗口,用 Qt WebEngine 渲染 Markdown 转换后的 HTML 页面,并在本地完成全文搜索、样式管理、导出和自动刷新。 -当前版本:`0.2.0` +当前版本:`0.2.1` ## 1. 适用场景 @@ -135,10 +135,14 @@ Markdown 支持: - 正文段落、一级到六级标题、列表项、引用、代码块、表格。 - 中文字体和英文字体分开设置。 -- 字号、加粗、斜体。 -- 行间距:倍数或磅。 -- 段前 / 段后间距:倍数或磅。 -- 首行缩进和悬挂缩进:按字符设置。 +- 字号支持磅(pt)、像素(px)和中文常用字号,例如五号 10.5 磅;可设置加粗、斜体、字体颜色和字符间距。 +- 对齐支持左对齐、居中、右对齐和两端对齐。 +- 行距支持单倍、1.5 倍、双倍、多倍、固定值和最小值。 +- 段前 / 段后间距支持磅、字符(em)或行,可设置同样式段落间不添加间距。 +- 左右缩进支持字符、磅或厘米;特殊缩进可选择无、首行或悬挂,首行与悬挂互斥。 +- 分页支持与下段同页、段中不分页、段前分页和孤行控制。 + +“继承”沿用当前文档默认值;数字 0 表示明确清零。复选框方块表示继承、勾选表示开启、空白表示关闭。设置窗口下方提供实时预览;分页效果以 Word 为准。旧样式文件会自动兼容原有的像素字号、字符间距和缩进。 纸张宽度是全局阅读设置,内置样式不再写死正文宽度,会跟随纸张宽度变化。 @@ -190,6 +194,10 @@ PDF 导出前会显示设置窗口,可分别设置上、下、左、右页边 DOCX 导出可选择 `pandoc` 或 `python-docx` 相关实现。正式安装版已包含 Pandoc,无需用户另行下载或配置 PATH。导出的 HTML 与阅读页一样不包含阅读进度控件。 +Pandoc、python-docx 和内置基础导出均保留图形设置中的字体、字号、颜色、字符间距、对齐、缩进、段间距、行距和分页选项。正文、各级标题、列表、引用、代码和表格分别应用对应设置;Markdown 中显式加粗、斜体的局部文本仍保留强调。Word 字号按其支持的半磅精度写入;自动颜色使用 Word 自动文字颜色。 + +高级 CSS 仅影响阅读器及 HTML/PDF,不能转换为 Word 样式。阅读器是连续页面,固定值/最小值行距及分页效果可能与 Word 显示不同;导出文件分别保留 Word 的固定值、最小值和分页属性。三个引擎的表格、复杂 Markdown、图片或公式支持范围仍按各自能力处理。 + ## 13. 配置与迁移 MDHelper 会保存: diff --git a/mdhelper/__init__.py b/mdhelper/__init__.py index eeec86c..5fdc3fb 100644 --- a/mdhelper/__init__.py +++ b/mdhelper/__init__.py @@ -1,3 +1,3 @@ """MDHelper package.""" -__version__ = "0.2.0" +__version__ = "0.2.1" diff --git a/mdhelper/document_style.py b/mdhelper/document_style.py new file mode 100644 index 0000000..90ee650 --- /dev/null +++ b/mdhelper/document_style.py @@ -0,0 +1,199 @@ +"""Shared, JSON-serializable typography rules for the reader and Word export. + +Missing keys mean inherit. Zero and False are explicit values. Legacy files +used pixels for font size and em for paragraph spacing labelled 'multiple'. +""" +from __future__ import annotations + +import math +import re +from typing import Any + +STYLE_TARGETS = ( + ("paragraph", "正文段落", ".reader p:not(:where(li p, blockquote p, .admonition p, th p, td p))"), + *((f"h{i}", f"{label}级标题", f".reader h{i}") for i, label in enumerate("一二三四五六", 1)), + ("list", "列表项", ".reader li"), + ("blockquote", "引用段落", ".reader blockquote p, .reader .admonition p"), + ("code", "代码块", ".reader pre, .reader code"), + ("table", "表格", ".reader table, .reader th, .reader td"), +) +BOOL_FIELDS = ("bold", "italic", "keep_with_next", "keep_lines_together", "page_break_before", "widow_control", "contextual_spacing") + + +def number(value: object, fallback: float = 0) -> float: + try: + result = float(value) + return result if math.isfinite(result) else fallback + except (TypeError, ValueError): + return fallback + + +def normalize_rule(value: object) -> dict[str, Any]: + if not isinstance(value, dict): + return {} + rule = dict(value) + if "font_family" in rule and "chinese_font_family" not in rule: + rule["chinese_font_family"] = rule["font_family"] + for key in ("font_family", "first_line_indent_chars", "first_line_indent", "hanging_indent_chars", "hanging_indent", "line_height", "space_before", "space_after"): + rule.pop(key, None) + if "indent_mode" not in value: + first = number(value.get("first_line_indent_chars", value.get("first_line_indent"))) + hanging = number(value.get("hanging_indent_chars", value.get("hanging_indent"))) + if hanging or first: + rule.update(indent_mode="hanging" if hanging else "first", indent_value=hanging or first) + if hanging and "left_indent_value" not in rule: + # Older styles used padding for hanging indents. Migrate that + # offset to Word's left-indent coordinate without moving text. + rule.update(left_indent_value=hanging, left_indent_unit="em") + if "line_height" in value and "line_height_value" not in value: + rule["line_height_value"] = value["line_height"] + if "line_height_value" in rule and "line_spacing_mode" not in rule: + rule["line_spacing_mode"] = "exact" if rule.get("line_height_unit") == "pt" else "multiple" + for field in ("space_before", "space_after"): + if field in value and field + "_value" not in value: + rule[field + "_value"] = value[field] + if field + "_value" in rule: + unit = rule.get(field + "_unit", "multiple") + rule[field + "_unit"] = "em" if unit == "multiple" else unit + for key in BOOL_FIELDS: + if key in rule and not isinstance(rule[key], bool): + rule.pop(key) + if "font_color" in rule and not re.fullmatch(r"auto|#[0-9a-fA-F]{6}", str(rule["font_color"])): + rule.pop("font_color") + for key, allowed in {"alignment": {"left", "center", "right", "justify"}, + "indent_mode": {"none", "first", "hanging"}, + "line_spacing_mode": {"multiple", "exact", "at_least"}}.items(): + if key in rule and rule[key] not in allowed: + rule.pop(key) + return rule + + +def font_points(rule: dict, default: float = 12) -> float: + size = number(rule.get("font_size")) + return size * (0.75 if rule.get("font_size_unit", "px") == "px" else 1) if size > 0 else default + + +def length_points(value: object, unit: str, font_pt: float, line_pt: float | None = None) -> float: + return number(value) * {"pt": 1, "px": .75, "cm": 72 / 2.54, "em": font_pt, "multiple": font_pt, "line": line_pt or font_pt}.get(unit, 1) + + +def line_points(rule: dict, font_pt: float) -> float: + val = number(rule.get("line_height_value"), 1.72) + mode = rule.get("line_spacing_mode", "multiple") + if mode == "at_least": + return max(val, font_pt * 1.2) + return val if mode == "exact" else font_pt * val + + +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.""" + 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, + space_before_value=.74, space_before_unit="em", space_after_value=.74, space_after_unit="em", + alignment="left", left_indent_value=0, left_indent_unit="em", right_indent_value=0, right_indent_unit="em", + indent_mode="none", indent_value=0, letter_spacing=0, contextual_spacing=False, + keep_with_next=False, keep_lines_together=False, page_break_before=False, widow_control=True) + if preset == "compact": + base.update(line_height_value=1.58, space_before_value=.42, space_after_value=.42) + elif preset == "serif": + base.update(chinese_font_family="SimSun", english_font_family="Georgia", line_height_value=1.82) + elif preset in {"wide", "focus"}: + base["line_height_value"] = 1.65 if preset == "wide" else 1.78 + result = {} + for target, _, _ in STYLE_TARGETS: + rule = dict(base) + if target.startswith("h"): + level = int(target[1:]) + scale = [2.05, 1.48, 1.2, 1, .83, .67][level - 1] + if preset == "compact" and level == 1: + scale = 1.78 + rule.update(font_size=font_size_px * scale, bold=True, line_height_value=1.32, + space_before_value=0 if level == 1 else 1.35, space_after_value=.55, keep_with_next=True) + if preset == "focus" and level == 1: + rule["alignment"] = "center" + elif target == "code": + rule.update(english_font_family="Consolas", font_size=font_size_px * .95, space_before_value=0, space_after_value=0) + elif target == "blockquote": + rule.update(left_indent_value=1, right_indent_value=1) + elif target == "list": + rule.update(left_indent_value=2, indent_mode="hanging", indent_value=1) + elif target == "table": + rule.update(space_before_value=0, space_after_value=0) + rule.update(normalize_rule((rules or {}).get(target, {}))) + result[target] = rule + return result + + +def fmt(value: object) -> str: + return f"{number(value):.4f}".rstrip("0").rstrip(".") + + +def css_length(value: object, unit: str) -> str: + return fmt(value) + {"pt": "pt", "cm": "cm", "px": "px", "em": "em", "multiple": "em", "line": "lh"}.get(unit, "em") + + +def css_declarations(value: dict) -> list[str]: + r = normalize_rule(value) + out = [] + fonts = [r.get("english_font_family"), r.get("chinese_font_family")] + fonts = list(dict.fromkeys(str(f).replace("\\", "\\\\").replace('"', '\\"') for f in fonts if f)) + if fonts: + out.append("font-family: " + ", ".join(f'"{f}"' for f in fonts) + ", sans-serif;") + if number(r.get("font_size")) > 0: + out.append(f"font-size: {css_length(r['font_size'], r.get('font_size_unit', 'px'))};") + for key, prop, yes, no in (("bold", "font-weight", "700", "400"), ("italic", "font-style", "italic", "normal")): + if key in r: + out.append(f"{prop}: {yes if r[key] else no};") + if "font_color" in r: + out.append(f"color: {r['font_color'] if r['font_color'] != 'auto' else 'var(--reader-text-color, #23272f)'};") + if "letter_spacing" in r: + out.append(f"letter-spacing: {fmt(r['letter_spacing'])}pt;") + if r.get("alignment") in {"left", "center", "right", "justify"}: + out.append(f"text-align: {r['alignment']};") + if number(r.get("line_height_value")) > 0: + mode = r.get("line_spacing_mode", "multiple") + # CSS line boxes naturally expand for taller inline content (Word atLeast). + out.append(f"line-height: {fmt(r['line_height_value'])}{'' if mode == 'multiple' else 'pt'};") + for side in ("left", "right"): + if side + "_indent_value" in r: + out.append(f"margin-{side}: {css_length(r[side + '_indent_value'], r.get(side + '_indent_unit', 'em'))};") + mode, indent = r.get("indent_mode"), number(r.get("indent_value")) + if mode in {"none", "first", "hanging"}: + out.append(f"text-indent: {fmt(-indent if mode == 'hanging' else indent if mode == 'first' else 0)}em;") + out.append("padding-left: 0em;") + for field, side in (("space_before", "top"), ("space_after", "bottom")): + if field + "_value" in r: + out.append(f"margin-{side}: {css_length(r[field + '_value'], r.get(field + '_unit', 'pt'))};") + for field, prop, yes in (("keep_with_next", "break-after", "avoid-page"), ("keep_lines_together", "break-inside", "avoid-page"), ("page_break_before", "break-before", "page")): + if field in r: + out.append(f"{prop}: {yes if r[field] else 'auto'};") + if "widow_control" in r: + out.extend(f"{prop}: {2 if r['widow_control'] else 1};" for prop in ("widows", "orphans")) + return out + + +def build_document_style_css(rules: dict | None, extra_css: str = "") -> str: + parts = [] + rules = rules if isinstance(rules, dict) else {} + p = normalize_rule(rules.get("paragraph")) + if number(p.get("font_size")) > 0: + parts.append(f".reader {{ --reader-math-font-size: {css_length(p['font_size'], p.get('font_size_unit', 'px'))}; }}") + for target, _, selector in STYLE_TARGETS: + rule = normalize_rule(rules.get(target)) + declarations = css_declarations(rule) + if declarations: + parts.append(selector + " {\n " + "\n ".join(declarations) + "\n}") + if target == "list": + # Loose Markdown lists contain p elements; spacing belongs to li. + parts.append(".reader li > p { margin: 0; text-indent: inherit; }") + if rule.get("contextual_spacing"): + # Match adjacent elements of the same paragraph type, not p + h1. + 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"))} + 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(): + parts.append(extra_css.strip()) + return "\n\n".join(parts) diff --git a/mdhelper/docx_exporter.py b/mdhelper/docx_exporter.py index 93bc063..0e3ef26 100644 --- a/mdhelper/docx_exporter.py +++ b/mdhelper/docx_exporter.py @@ -49,12 +49,22 @@ def export_markdown_to_docx( output_path: Path, engine: str = "builtin", source_path: Path | None = None, + style_rules: dict | None = None, + document_font_family: str = "", + document_font_size: float = 16, + preset: str = "default", ) -> Path: + from .docx_style import apply_docx_styles + if engine == "pandoc": - return export_markdown_to_docx_pandoc(source, output_path, source_path=source_path) - if engine == "python-docx": - return export_markdown_to_docx_python_docx(source, output_path) - return export_markdown_to_docx_builtin(source, output_path) + result = export_markdown_to_docx_pandoc(source, output_path, source_path=source_path) + elif engine == "python-docx": + result = export_markdown_to_docx_python_docx(source, output_path) + else: + result = export_markdown_to_docx_builtin(source, output_path) + apply_docx_styles(result, style_rules, font_family=document_font_family, + font_size_px=document_font_size, preset=preset) + return result def export_markdown_to_docx_builtin(source: str, output_path: Path) -> Path: @@ -70,10 +80,12 @@ def export_markdown_to_docx_builtin(source: str, output_path: Path) -> Path: 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) return output_path def export_markdown_to_docx_pandoc(source: str, output_path: Path, source_path: Path | None = None) -> Path: + output_path = output_path.resolve() if output_path.suffix.lower() != ".docx": output_path = output_path.with_suffix(".docx") output_path.parent.mkdir(parents=True, exist_ok=True) @@ -82,13 +94,13 @@ def export_markdown_to_docx_pandoc(source: str, output_path: Path, source_path: if pandoc_path is None: raise DocxExportError("未找到程序内置的 Pandoc,当前 MDHelper 安装包可能不完整,请重新获取完整版本。") - temporary_path: Path | None = None - input_path = source_path if source_path is not None and source_path.exists() else None - if input_path is None: - with tempfile.NamedTemporaryFile("w", suffix=".md", encoding="utf-8", delete=False) as handle: - handle.write(source) - temporary_path = Path(handle.name) - input_path = temporary_path + # Export the current editor text, including unsaved edits. Retain the source + # directory only for resolving linked images and other local resources. + with tempfile.NamedTemporaryFile("w", suffix=".md", encoding="utf-8", delete=False) as handle: + handle.write(source) + temporary_path = Path(handle.name) + input_path = temporary_path + resource_directory = source_path.resolve().parent if source_path is not None else input_path.parent command = [str(pandoc_path), str(input_path), "-o", str(output_path), "--standalone"] run_options: dict[str, object] = {} @@ -97,7 +109,7 @@ def export_markdown_to_docx_pandoc(source: str, output_path: Path, source_path: try: result = subprocess.run( command, - cwd=str(input_path.parent), + cwd=str(resource_directory), capture_output=True, text=True, timeout=120, @@ -128,6 +140,7 @@ def export_markdown_to_docx_python_docx(source: str, output_path: Path) -> Path: from docx import Document from docx.oxml.ns import qn from docx.shared import Pt + from docx.enum.style import WD_STYLE_TYPE except ImportError as exc: raise DocxExportError("未找到 python-docx,请先安装 python-docx。") from exc @@ -136,6 +149,7 @@ def export_markdown_to_docx_python_docx(source: str, output_path: Path) -> Path: normal.font.name = "Microsoft YaHei" normal.font.size = Pt(11) 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): if isinstance(block, TableBlock): @@ -160,7 +174,12 @@ def _add_python_docx_paragraph(document: object, block: ParagraphBlock) -> None: elif block.list_kind == "number": style = "List Number" elif block.style == "Code": - style = None + from docx.enum.style import WD_STYLE_TYPE + if "MDHelper Code" not in document.styles: + document.styles.add_style("MDHelper Code", WD_STYLE_TYPE.PARAGRAPH) + style = "MDHelper Code" + elif block.quote_depth: + style = "Quote" paragraph = document.add_paragraph(style=style) if block.quote_depth: @@ -171,9 +190,13 @@ def _add_python_docx_paragraph(document: object, block: ParagraphBlock) -> None: if part_index: paragraph.add_run().add_break() run = paragraph.add_run(part) - run.bold = bool(run_style.get("bold")) - run.italic = bool(run_style.get("italic")) + 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) @@ -191,9 +214,12 @@ def _add_python_docx_table(document: object, block: TableBlock) -> None: paragraph = cell.paragraphs[0] for text, run_style in runs: run = paragraph.add_run(text) - run.bold = bool(run_style.get("bold") or row_index == 0) - run.italic = bool(run_style.get("italic")) + 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) @@ -348,6 +374,7 @@ def _block_xml(block: ParagraphBlock | TableBlock) -> str: 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('') @@ -407,6 +434,13 @@ PACKAGE_RELS_XML = """ """ +DOCUMENT_RELS_XML = """ + + + + +""" + SETTINGS_XML = f""" @@ -449,6 +483,7 @@ STYLES_XML = f""" + diff --git a/mdhelper/docx_style.py b/mdhelper/docx_style.py new file mode 100644 index 0000000..15c50dd --- /dev/null +++ b/mdhelper/docx_style.py @@ -0,0 +1,185 @@ +"""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 + +W = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}" +NS = {"w": W[1:-1]} + + +def child(parent, name): + element = parent.find(W + name) + if element is None: + element = ET.SubElement(parent, W + name) + return element + + +def val(parent, name, value): + child(parent, name).set(W + "val", str(value)) + + +def properties(parent, name): + element = parent.find(W + name) + if element is None: + element = ET.Element(W + name) + parent.insert(0, element) + return element + + +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 = { + "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", + } + for name, order in orders.items(): + ranks = {W + tag: index for index, tag in enumerate(order.split())} + for element in root.iter(W + name): + element[:] = sorted(element, key=lambda e: ranks.get(e.tag, len(ranks))) + + +def _run_properties(rpr, rule, preserve_emphasis=False): + fonts = child(rpr, "rFonts") + # Explicit font selections must override the engine's theme fonts. + for attr in list(fonts.attrib): + 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)) + + +def _paragraph_properties(ppr, rule): + points = font_points(rule) + val(ppr, "jc", "both" if rule["alignment"] == "justify" else rule["alignment"]) + spacing = child(ppr, "spacing") + spacing.attrib.clear() + for side in ("before", "after"): + unit = rule[f"space_{side}_unit"] + amount = number(rule[f"space_{side}_value"]) + spacing.set(W + side, str(round(length_points(amount, unit, points, line_points(rule, points)) * 20))) + if unit == "line": + spacing.set(W + side + "Lines", str(round(amount * 100))) + mode = rule["line_spacing_mode"] + spacing.set(W + "line", str(round(number(rule["line_height_value"]) * (240 if mode == "multiple" else 20)))) + spacing.set(W + "lineRule", {"multiple": "auto", "exact": "exact", "at_least": "atLeast"}[mode]) + ind = child(ppr, "ind") + ind.attrib.clear() + for side in ("left", "right"): + unit, amount = rule[f"{side}_indent_unit"], number(rule[f"{side}_indent_value"]) + ind.set(W + side, str(round(length_points(amount, unit, points) * 20))) + if unit == "em": + ind.set(W + side + "Chars", str(round(amount * 100))) + kind = "hanging" if rule["indent_mode"] == "hanging" else "firstLine" + amount = number(rule["indent_value"]) if rule["indent_mode"] != "none" else 0 + ind.set(W + kind, str(round(amount * points * 20))) + ind.set(W + kind + "Chars", str(round(amount * 100))) + # Override paragraph style inheritance, including Word's default grid snapping. + val(ppr, "snapToGrid", 0) + for key, xml in (("contextual_spacing", "contextualSpacing"), ("keep_with_next", "keepNext"), + ("keep_lines_together", "keepLines"), ("page_break_before", "pageBreakBefore"), + ("widow_control", "widowControl")): + val(ppr, xml, int(rule[key])) + + +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) + paragraph_rule["left_indent_value"] = length_points(rule["left_indent_value"], rule["left_indent_unit"], font_points(rule)) + number(level.get(W + "val")) * 36 + 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]) diff --git a/mdhelper/main_window.py b/mdhelper/main_window.py index c915b72..3717aa6 100644 --- a/mdhelper/main_window.py +++ b/mdhelper/main_window.py @@ -3625,7 +3625,14 @@ class MainWindow(QMainWindow): output_path = output_path.with_suffix(".docx") try: source = self.current_file.read_text(encoding="utf-8") - export_markdown_to_docx(source, output_path, engine=engine, source_path=self.current_file) + style = self.custom_document_styles.get(self.document_style_id, {}) + export_markdown_to_docx( + source, output_path, engine=engine, source_path=self.current_file, + style_rules=style.get("rules", {}), + document_font_family=self.document_font_family, + document_font_size=self.document_font_size, + preset=self.document_style_id, + ) except (OSError, zipfile.BadZipFile, DocxExportError) as exc: LOGGER.exception("Failed to export DOCX: %s", output_path) QMessageBox.warning(self, "导出失败", f"无法写入 DOCX 文件:\n{output_path}\n\n{exc}") diff --git a/mdhelper/resources/reader.css b/mdhelper/resources/reader.css index 4e93ee9..ffdf9e7 100644 --- a/mdhelper/resources/reader.css +++ b/mdhelper/resources/reader.css @@ -7,6 +7,7 @@ html[data-theme="dark"] { } body { + --reader-text-color: #23272f; margin: 0; background: #f6f7f9; color: #23272f; @@ -16,6 +17,7 @@ body { } html[data-theme="dark"] body { + --reader-text-color: #e4e8ef; background: #17191f; color: #e4e8ef; } diff --git a/mdhelper/style_dialog.py b/mdhelper/style_dialog.py index 795996b..3304f67 100644 --- a/mdhelper/style_dialog.py +++ b/mdhelper/style_dialog.py @@ -2,144 +2,39 @@ from __future__ import annotations import ctypes import os +import re from copy import deepcopy from typing import Any from PySide6.QtCore import Qt -from PySide6.QtGui import QFont +from PySide6.QtGui import QFont, QColor, QTextBlockFormat, QTextCharFormat, QTextCursor from PySide6.QtWidgets import ( QCheckBox, QComboBox, + QColorDialog, QDialog, QDialogButtonBox, QDoubleSpinBox, - QFrame, QFontComboBox, QFormLayout, - QGroupBox, QHBoxLayout, QLabel, QLineEdit, QListWidget, QListWidgetItem, QPushButton, - QSpinBox, + QScrollArea, QTabWidget, QTextEdit, QVBoxLayout, QWidget, ) - -STYLE_TARGETS = ( - ("paragraph", "正文段落", ".reader p"), - ("h1", "一级标题", ".reader h1"), - ("h2", "二级标题", ".reader h2"), - ("h3", "三级标题", ".reader h3"), - ("h4", "四级标题", ".reader h4"), - ("h5", "五级标题", ".reader h5"), - ("h6", "六级标题", ".reader h6"), - ("list", "列表项", ".reader li"), - ("blockquote", "引用段落", ".reader blockquote, .reader blockquote p, .reader .admonition, .reader .admonition p"), - ("code", "代码块", ".reader pre, .reader code"), - ("table", "表格", ".reader table"), -) -DEFAULT_CHINESE_FONT = "宋体" -DEFAULT_ENGLISH_FONT = "Times New Roman" +from .document_style import (STYLE_TARGETS, normalize_rule, resolved_rules, + font_points, length_points, line_points, number) -def build_document_style_css(rules: dict[str, dict[str, Any]] | None, extra_css: str = "") -> str: - parts: list[str] = [] - normalized_rules = rules if isinstance(rules, dict) else {} - paragraph_rule = normalized_rules.get("paragraph", {}) - paragraph_font_size = _positive_float(paragraph_rule.get("font_size")) if isinstance(paragraph_rule, dict) else 0.0 - if paragraph_font_size > 0: - parts.append(f".reader {{\n --reader-math-font-size: {_format_number(paragraph_font_size)}px;\n}}") - selector_by_target = {target_id: selector for target_id, _label, selector in STYLE_TARGETS} - for target_id, selector in selector_by_target.items(): - rule = normalized_rules.get(target_id, {}) - declarations = _css_declarations(rule) - if declarations: - parts.append(f"{selector} {{\n" + "\n".join(f" {declaration}" for declaration in declarations) + "\n}") - extra = extra_css.strip() - if extra: - parts.append(extra) - return "\n\n".join(parts).strip() - - -def _css_declarations(rule: dict[str, Any]) -> list[str]: - declarations: list[str] = [] - font_declaration = _font_family_declaration(rule) - if font_declaration: - declarations.append(font_declaration) - - font_size = _positive_float(rule.get("font_size")) - if font_size > 0: - declarations.append(f"font-size: {_format_number(font_size)}px;") - - if bool(rule.get("bold")): - declarations.append("font-weight: 700;") - if bool(rule.get("italic")): - declarations.append("font-style: italic;") - - line_height = _positive_float(rule.get("line_height_value", rule.get("line_height"))) - if line_height > 0: - declarations.append(f"line-height: {_css_length_or_multiple(line_height, str(rule.get('line_height_unit') or 'multiple'))};") - - first_line_indent = _positive_float(rule.get("first_line_indent_chars", rule.get("first_line_indent"))) - hanging_indent = _positive_float(rule.get("hanging_indent_chars", rule.get("hanging_indent"))) - if hanging_indent > 0: - declarations.append(f"padding-left: {_format_number(hanging_indent)}em;") - declarations.append(f"text-indent: -{_format_number(hanging_indent)}em;") - elif first_line_indent > 0: - declarations.append(f"text-indent: {_format_number(first_line_indent)}em;") - - space_before = _positive_float(rule.get("space_before_value", rule.get("space_before"))) - if space_before > 0: - unit = str(rule.get("space_before_unit") or "multiple") - declarations.append(f"margin-top: {_css_length_or_multiple(space_before, unit, multiple_unit='em')};") - space_after = _positive_float(rule.get("space_after_value", rule.get("space_after"))) - if space_after > 0: - unit = str(rule.get("space_after_unit") or "multiple") - declarations.append(f"margin-bottom: {_css_length_or_multiple(space_after, unit, multiple_unit='em')};") - return declarations - - -def _font_family_declaration(rule: dict[str, Any]) -> str: - english_font = str(rule.get("english_font_family") or "").strip() - chinese_font = str(rule.get("chinese_font_family") or rule.get("font_family") or "").strip() - fonts = [font for font in (english_font, chinese_font, "Microsoft YaHei UI", "Arial", "sans-serif") if font] - unique_fonts: list[str] = [] - for font in fonts: - if font not in unique_fonts: - unique_fonts.append(font) - if not english_font and not chinese_font: - return "" - css_fonts = [ - font if font in {"serif", "sans-serif", "monospace"} else f'"{font.replace("\\", "\\\\").replace("\"", "\\\"")}"' - for font in unique_fonts - ] - return f"font-family: {', '.join(css_fonts)};" - - -def _css_length_or_multiple(value: float, unit: str, multiple_unit: str = "") -> str: - formatted = _format_number(value) - if unit == "pt": - return f"{formatted}pt" - if multiple_unit: - return f"{formatted}{multiple_unit}" - return formatted - - -def _positive_float(value: object) -> float: - try: - return max(0.0, float(value)) - except (TypeError, ValueError): - return 0.0 - - -def _format_number(value: float) -> str: - return f"{value:.2f}".rstrip("0").rstrip(".") +from .document_style import build_document_style_css class DocumentStyleEditorDialog(QDialog): @@ -151,8 +46,8 @@ class DocumentStyleEditorDialog(QDialog): ) -> None: super().__init__(parent) self.setWindowTitle("文档样式") - self.setMinimumSize(565, 620) - self.resize(565, 620) + self.setMinimumSize(800, 640) + self.resize(960, 780) source = style or {} self.rules: dict[str, dict[str, Any]] = deepcopy(source.get("rules", {})) if isinstance(source.get("rules"), dict) else {} self._current_target = STYLE_TARGETS[0][0] @@ -171,15 +66,16 @@ class DocumentStyleEditorDialog(QDialog): name_row.addStretch(1) self.tabs = QTabWidget() - self.tabs.setMaximumWidth(535) + self.tabs.setMinimumWidth(750) self.tabs.addTab(self._build_visual_tab(), "图形设置") - self.tabs.addTab(self._build_advanced_tab(str(source.get("extra_css") or source.get("css") or "")), "高级 CSS") + extra_css = source.get("extra_css", "" if source.get("rules") else source.get("css", "")) + self.tabs.addTab(self._build_advanced_tab(str(extra_css or "")), "高级 CSS") buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel) buttons.accepted.connect(self.accept) buttons.rejected.connect(self.reject) button_row = QWidget() - button_row.setMaximumWidth(535) + button_row.setMinimumWidth(750) button_layout = QHBoxLayout(button_row) button_layout.setContentsMargins(0, 0, 0, 0) button_layout.addStretch(1) @@ -461,250 +357,305 @@ class DocumentStyleEditorDialog(QDialog): "css": build_document_style_css(self.rules, extra_css), } + @staticmethod + def _combo(items: list[tuple[str, object]]) -> QComboBox: + box = QComboBox() + for label, value in items: + box.addItem(label, value) + return box + + @staticmethod + def _spin(maximum: float = 200, inherit: bool = True) -> QDoubleSpinBox: + box = QDoubleSpinBox() + box.setDecimals(2) + box.setRange(-1 if inherit else 0, maximum) + box.setSingleStep(0.5) + if inherit: + box.setSpecialValueText("继承") + box.setValue(-1) + return box + + @staticmethod + def _row(*widgets: QWidget) -> QWidget: + row = QWidget() + layout = QHBoxLayout(row) + layout.setContentsMargins(0, 0, 0, 0) + for widget in widgets: + layout.addWidget(widget) + return row + def _build_visual_tab(self) -> QWidget: - tab = QWidget() - layout = QHBoxLayout(tab) - layout.setContentsMargins(10, 10, 10, 10) - layout.setSpacing(14) - + page = QWidget() + layout = QHBoxLayout(page) self.target_list = QListWidget() - self.target_list.setObjectName("styleTargetList") - self.target_list.setFixedWidth(156) - for target_id, label, _selector in STYLE_TARGETS: + self.target_list.setFixedWidth(115) + for key, label, _ in STYLE_TARGETS: item = QListWidgetItem(label) - item.setData(Qt.ItemDataRole.UserRole, target_id) + item.setData(Qt.ItemDataRole.UserRole, key) self.target_list.addItem(item) - self.target_list.currentRowChanged.connect(self._change_target) - layout.addWidget(self.target_list) - - content = QWidget() - content.setObjectName("styleEditorContent") - content.setMaximumWidth(500) - content_layout = QVBoxLayout(content) - content_layout.setContentsMargins(0, 0, 0, 0) - content_layout.setSpacing(12) - - self.chinese_font_combo = QFontComboBox() - self.chinese_font_combo.setCurrentFont(QFont(DEFAULT_CHINESE_FONT)) - self.chinese_font_combo.setMinimumWidth(220) - self.chinese_font_combo.setMaximumWidth(315) - self.chinese_font_combo.currentFontChanged.connect(self._store_and_refresh) - - self.english_font_combo = QFontComboBox() - self.english_font_combo.setCurrentFont(QFont(DEFAULT_ENGLISH_FONT)) - self.english_font_combo.setMinimumWidth(220) - self.english_font_combo.setMaximumWidth(315) - self.english_font_combo.currentFontChanged.connect(self._store_and_refresh) - - self.font_size_spin = QSpinBox() - self.font_size_spin.setRange(0, 96) - self.font_size_spin.setSpecialValueText("继承") - self.font_size_spin.setSuffix(" px") - self.font_size_spin.setMaximumWidth(150) - self.font_size_spin.valueChanged.connect(self._store_and_refresh) - - self.bold_checkbox = QCheckBox("加粗") - self.bold_checkbox.toggled.connect(self._store_and_refresh) - self.italic_checkbox = QCheckBox("斜体") - self.italic_checkbox.toggled.connect(self._store_and_refresh) - - font_style_row = QHBoxLayout() - font_style_row.addWidget(self.bold_checkbox) - font_style_row.addWidget(self.italic_checkbox) - font_style_row.addStretch(1) - - font_form = QFormLayout() - font_form.setContentsMargins(10, 12, 10, 10) - font_form.setHorizontalSpacing(12) - font_form.setVerticalSpacing(9) - font_form.addRow("中文字体", self.chinese_font_combo) - font_form.addRow("英文字体", self.english_font_combo) - font_form.addRow("字号", self.font_size_spin) - font_form.addRow("字形", font_style_row) - font_group = QGroupBox("字体") - font_group.setObjectName("styleSection") - font_group.setMaximumWidth(500) - font_group.setLayout(font_form) - - self.line_height_spin = self._number_spin(0.0, 200.0, "继承") - self.line_height_spin.setSingleStep(0.05) - self.line_height_spin.setMaximumWidth(150) - self.line_height_spin.valueChanged.connect(self._store_and_refresh) - self.line_height_unit_combo = self._unit_combo((("倍", "multiple"), ("磅", "pt"))) - self.line_height_unit_combo.currentIndexChanged.connect(self._store_and_refresh) - self.first_indent_spin = self._number_spin(0.0, 20.0, "无") - self.first_indent_spin.setSuffix(" 字符") - self.first_indent_spin.setMaximumWidth(170) - self.first_indent_spin.valueChanged.connect(self._store_and_refresh) - self.hanging_indent_spin = self._number_spin(0.0, 20.0, "无") - self.hanging_indent_spin.setSuffix(" 字符") - self.hanging_indent_spin.setMaximumWidth(170) - self.hanging_indent_spin.valueChanged.connect(self._store_and_refresh) - self.space_before_spin = self._number_spin(0.0, 200.0, "无") - self.space_before_spin.setMaximumWidth(150) - self.space_before_spin.valueChanged.connect(self._store_and_refresh) - self.space_before_unit_combo = self._unit_combo((("倍", "multiple"), ("磅", "pt"))) - self.space_before_unit_combo.currentIndexChanged.connect(self._store_and_refresh) - self.space_after_spin = self._number_spin(0.0, 200.0, "无") - self.space_after_spin.setMaximumWidth(150) - self.space_after_spin.valueChanged.connect(self._store_and_refresh) - self.space_after_unit_combo = self._unit_combo((("倍", "multiple"), ("磅", "pt"))) - self.space_after_unit_combo.currentIndexChanged.connect(self._store_and_refresh) - - reset_button = QPushButton("重置当前对象") - reset_button.setObjectName("styleResetButton") - reset_button.setMaximumWidth(128) - reset_button.clicked.connect(self._reset_current_target) - reset_row = QHBoxLayout() - reset_row.setContentsMargins(0, 0, 0, 0) - reset_row.addStretch(1) - reset_row.addWidget(reset_button) - - paragraph_form = QFormLayout() - paragraph_form.setContentsMargins(10, 12, 10, 10) - paragraph_form.setHorizontalSpacing(12) - paragraph_form.setVerticalSpacing(9) - paragraph_form.addRow("行间距", self._measurement_row(self.line_height_spin, self.line_height_unit_combo)) - paragraph_form.addRow("首行缩进", self.first_indent_spin) - paragraph_form.addRow("悬挂缩进", self.hanging_indent_spin) - paragraph_form.addRow("段前间距", self._measurement_row(self.space_before_spin, self.space_before_unit_combo)) - paragraph_form.addRow("段后间距", self._measurement_row(self.space_after_spin, self.space_after_unit_combo)) - paragraph_form.addRow("", reset_row) - paragraph_group = QGroupBox("段落") - paragraph_group.setObjectName("styleSection") - paragraph_group.setMaximumWidth(500) - paragraph_group.setLayout(paragraph_form) - - preview = QFrame() - preview.setObjectName("stylePreview") - preview.setMaximumWidth(500) - preview_layout = QVBoxLayout(preview) - preview_layout.setContentsMargins(14, 12, 14, 12) - preview_layout.setSpacing(6) - preview_title = QLabel("预览") - preview_title.setObjectName("stylePreviewTitle") - preview_text = QLabel("标题示例\n正文段落示例 Aa 123,查看字体、缩进和段落间距的整体感觉。") - preview_text.setObjectName("stylePreviewText") - preview_text.setWordWrap(True) - preview_layout.addWidget(preview_title) - preview_layout.addWidget(preview_text) - - content_layout.addWidget(font_group) - content_layout.addWidget(paragraph_group) - content_layout.addWidget(preview) - content_layout.addStretch(1) - layout.addWidget(content) - layout.addStretch(1) - previous_loading = self._loading - self._loading = True self.target_list.setCurrentRow(0) - self._loading = previous_loading - return tab + layout.addWidget(self.target_list) + panel = QWidget() + form = QFormLayout(panel) + form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow) + self.font_combo = QFontComboBox() + self.chinese_font_combo = self.font_combo + self.english_font_combo = QFontComboBox() + for box in (self.font_combo, self.english_font_combo): + box.insertItem(0, "继承") + box.setMaximumWidth(315) + form.addRow("中文字体", self.font_combo) + form.addRow("西文字体", self.english_font_combo) + self.font_size_spin = self._spin(200) + self.font_size_unit_combo = self._combo([("磅(pt)", "pt"), ("像素(px)", "px")]) + self.font_size_preset_combo = self._combo([("常用字号…", None), ("初号 42 磅", 42), ("小初 36 磅", 36), + ("一号 26 磅", 26), ("小一 24 磅", 24), ("二号 22 磅", 22), ("小二 18 磅", 18), + ("三号 16 磅", 16), ("小三 15 磅", 15), ("四号 14 磅", 14), ("小四 12 磅", 12), + ("五号 10.5 磅", 10.5), ("小五 9 磅", 9), ("六号 7.5 磅", 7.5)]) + form.addRow("字号", self._row(self.font_size_spin, self.font_size_unit_combo, self.font_size_preset_combo)) + self.bool_boxes = {} + for key, label in [("bold", "加粗"), ("italic", "斜体"), ("contextual_spacing", "同样式段落间不添加间距"), + ("keep_with_next", "与下段同页"), ("keep_lines_together", "段中不分页"), + ("page_break_before", "段前分页"), ("widow_control", "孤行控制")]: + box = QCheckBox(label) + box.setTristate(True) + box.setToolTip("方块:继承;勾选:开启;空白:关闭") + self.bool_boxes[key] = box + self.bold_checkbox = self.bool_boxes["bold"] + self.italic_checkbox = self.bool_boxes["italic"] + form.addRow("字形", self._row(self.bold_checkbox, self.italic_checkbox)) + self.color_combo = self._combo([("继承", None), ("自动(随主题)", "auto"), ("自定义…", "custom")]) + self.color_button = QPushButton("#23272f") + self.color_button.clicked.connect(self._choose_color) + form.addRow("字体颜色", self._row(self.color_combo, self.color_button)) + self.character_spacing_combo = self._combo([("继承", None), ("标准", 0), ("加宽", 1), ("紧缩", -1)]) + self.character_spacing_spin = self._spin(100, False) + self.character_spacing_spin.setSuffix(" 磅") + form.addRow("字符间距", self._row(self.character_spacing_combo, self.character_spacing_spin)) + self.alignment_combo = self._combo([("继承", None), ("左对齐", "left"), ("居中", "center"), ("右对齐", "right"), ("两端对齐", "justify")]) + form.addRow("对齐方式", self.alignment_combo) + for side, label in (("left", "左缩进"), ("right", "右缩进")): + spin = self._spin() + unit = self._combo([("字符", "em"), ("磅", "pt"), ("厘米", "cm")]) + setattr(self, f"{side}_indent_spin", spin) + setattr(self, f"{side}_indent_unit_combo", unit) + form.addRow(label, self._row(spin, unit)) + self.indent_mode_combo = self._combo([("继承", None), ("无", "none"), ("首行缩进", "first"), ("悬挂缩进", "hanging")]) + self.indent_spin = self._spin(100, False) + self.indent_spin.setSuffix(" 字符") + form.addRow("特殊缩进", self._row(self.indent_mode_combo, self.indent_spin)) + self.line_height_mode_combo = self._combo([("继承", None), ("单倍", "single"), ("1.5 倍", "one_half"), + ("双倍", "double"), ("多倍", "multiple"), ("固定值(磅)", "exact"), ("最小值(磅)", "at_least")]) + self.line_height_spin = self._spin(500, False) + self.line_height_spin.setMinimum(0.1) + form.addRow("行距", self._row(self.line_height_mode_combo, self.line_height_spin)) + for side, label in (("before", "段前间距"), ("after", "段后间距")): + spin = self._spin(1000) + unit = self._combo([("磅", "pt"), ("字符(em)", "em"), ("行", "line")]) + setattr(self, f"space_{side}_spin", spin) + setattr(self, f"space_{side}_unit_combo", unit) + form.addRow(label, self._row(spin, unit)) + form.addRow("段落间距", self.bool_boxes["contextual_spacing"]) + form.addRow("换行与分页", self._row(self.bool_boxes["keep_with_next"], self.bool_boxes["keep_lines_together"])) + form.addRow("", self._row(self.bool_boxes["page_break_before"], self.bool_boxes["widow_control"])) + note = QLabel("“继承”沿用文档默认样式;0 表示清零。复选框方块表示继承。") + note.setWordWrap(True) + form.addRow(note) + reset = QPushButton("重置当前对象") + reset.setObjectName("styleResetButton") + reset.setMaximumWidth(128) + reset.clicked.connect(self._reset_current_rule) + form.addRow(reset) + scroll = QScrollArea() + scroll.setWidgetResizable(True) + scroll.setWidget(panel) + right = QVBoxLayout() + right.addWidget(scroll, 1) + right.addWidget(QLabel("实时预览(分页效果请以导出的 Word 为准)")) + self.preview = QTextEdit() + self.preview.setReadOnly(True) + self.preview.setMinimumHeight(125) + self.preview.setMaximumHeight(165) + self.preview.setStyleSheet("QTextEdit { background: white; color: #23272f; }") + right.addWidget(self.preview) + layout.addLayout(right, 1) + for widget in panel.findChildren(QComboBox): + if widget is not self.font_size_preset_combo: + widget.currentIndexChanged.connect(self._store_and_refresh) + if widget.isEditable(): + widget.editTextChanged.connect(self._store_and_refresh) + for widget in panel.findChildren(QDoubleSpinBox): + widget.valueChanged.connect(self._store_and_refresh) + for widget in self.bool_boxes.values(): + widget.checkStateChanged.connect(self._store_and_refresh) + self.font_size_preset_combo.currentIndexChanged.connect(self._apply_size_preset) + self.target_list.currentItemChanged.connect(self._change_target) + return page def _build_advanced_tab(self, css: str) -> QWidget: - tab = QWidget() + page = QWidget() + layout = QVBoxLayout(page) + label = QLabel("高级 CSS 仅用于阅读器及 HTML/PDF。导出 Word 保留“图形设置”中的字体和段落选项。") + label.setWordWrap(True) + layout.addWidget(label) self.extra_css_edit = QTextEdit() self.extra_css_edit.setAcceptRichText(False) self.extra_css_edit.setPlainText(css) - self.extra_css_edit.setPlaceholderText("可选:补充 CSS,会叠加到图形设置生成的样式之后。") - layout = QVBoxLayout(tab) - layout.addWidget(QLabel("附加 CSS")) - layout.addWidget(self.extra_css_edit, 1) - return tab + layout.addWidget(self.extra_css_edit) + return page - def _number_spin(self, minimum: float, maximum: float, special_text: str) -> QDoubleSpinBox: - spin = QDoubleSpinBox() - spin.setRange(minimum, maximum) - spin.setDecimals(2) - spin.setSingleStep(0.1) - spin.setSpecialValueText(special_text) - return spin + def _choose_color(self) -> None: + color = QColorDialog.getColor(QColor(self.color_button.text()), self, "字体颜色") + if color.isValid(): + self.color_button.setText(color.name()) + self.color_combo.setCurrentIndex(2) + self._store_and_refresh() - def _unit_combo(self, items: tuple[tuple[str, str], ...]) -> QComboBox: - combo = QComboBox() - combo.setFixedWidth(58) - for label, value in items: - combo.addItem(label, value) - return combo + def _apply_size_preset(self, *_: object) -> None: + value = self.font_size_preset_combo.currentData() + if value is not None: + self._loading = True + self.font_size_spin.setValue(value) + self.font_size_unit_combo.setCurrentIndex(0) + self.font_size_preset_combo.setCurrentIndex(0) + self._loading = False + self._store_and_refresh() - def _measurement_row(self, spin: QDoubleSpinBox, unit_combo: QComboBox) -> QHBoxLayout: - row = QHBoxLayout() - row.setContentsMargins(0, 0, 0, 0) - row.setSpacing(6) - row.addWidget(spin) - row.addWidget(unit_combo) - row.addStretch(1) - return row + @staticmethod + def _select(box: QComboBox, value: object) -> None: + index = box.findData(value) + box.setCurrentIndex(max(0, index)) - def _change_target(self, row: int = -1) -> None: - if self._loading: - return - del row - self._store_current_rule() - item = self.target_list.currentItem() - if item is None: - return - self._current_target = str(item.data(Qt.ItemDataRole.UserRole) or STYLE_TARGETS[0][0]) - self._load_rule_to_widgets(self.rules.get(self._current_target, {})) + def _load_rule_to_widgets(self, rule: dict[str, Any]) -> None: + self._loading = True + rule = normalize_rule(rule) + for key, box in (("chinese_font_family", self.font_combo), ("english_font_family", self.english_font_combo)): + box.setCurrentText(str(rule.get(key) or "继承")) + self.font_size_spin.setValue(number(rule.get("font_size"), -1)) + self._select(self.font_size_unit_combo, rule.get("font_size_unit", "px" if "font_size" in rule else "pt")) + for key, box in self.bool_boxes.items(): + box.setCheckState(Qt.CheckState.PartiallyChecked if key not in rule else + Qt.CheckState.Checked if rule[key] else Qt.CheckState.Unchecked) + color = rule.get("font_color") + self._select(self.color_combo, "custom" if str(color).startswith("#") else color) + self.color_button.setText(str(color) if str(color).startswith("#") else "#23272f") + spacing = rule.get("letter_spacing") + self._select(self.character_spacing_combo, None if spacing is None else (1 if number(spacing) > 0 else -1 if number(spacing) < 0 else 0)) + self.character_spacing_spin.setValue(abs(number(spacing))) + self._select(self.alignment_combo, rule.get("alignment")) + for side in ("left", "right"): + getattr(self, f"{side}_indent_spin").setValue(number(rule.get(f"{side}_indent_value"), -1)) + self._select(getattr(self, f"{side}_indent_unit_combo"), rule.get(f"{side}_indent_unit", "em")) + self._select(self.indent_mode_combo, rule.get("indent_mode")) + self.indent_spin.setValue(number(rule.get("indent_value"))) + mode, value = rule.get("line_spacing_mode"), number(rule.get("line_height_value"), 1) + if mode == "multiple": + mode = {1: "single", 1.5: "one_half", 2: "double"}.get(value, "multiple") + self._select(self.line_height_mode_combo, mode) + self.line_height_spin.setValue(value) + for side in ("before", "after"): + getattr(self, f"space_{side}_spin").setValue(number(rule.get(f"space_{side}_value"), -1)) + self._select(getattr(self, f"space_{side}_unit_combo"), rule.get(f"space_{side}_unit", "pt")) + self._loading = False + self._refresh_preview() def _store_current_rule(self) -> None: - rule: dict[str, object] = {} - rule["chinese_font_family"] = self.chinese_font_combo.currentFont().family() or DEFAULT_CHINESE_FONT - rule["english_font_family"] = self.english_font_combo.currentFont().family() or DEFAULT_ENGLISH_FONT - if self.font_size_spin.value() > 0: - rule["font_size"] = self.font_size_spin.value() - if self.bold_checkbox.isChecked(): - rule["bold"] = True - if self.italic_checkbox.isChecked(): - rule["italic"] = True - if self.line_height_spin.value() > 0: - rule["line_height_value"] = self.line_height_spin.value() - rule["line_height_unit"] = str(self.line_height_unit_combo.currentData() or "multiple") - if self.first_indent_spin.value() > 0: - rule["first_line_indent_chars"] = self.first_indent_spin.value() - if self.hanging_indent_spin.value() > 0: - rule["hanging_indent_chars"] = self.hanging_indent_spin.value() - if self.space_before_spin.value() > 0: - rule["space_before_value"] = self.space_before_spin.value() - rule["space_before_unit"] = str(self.space_before_unit_combo.currentData() or "multiple") - if self.space_after_spin.value() > 0: - rule["space_after_value"] = self.space_after_spin.value() - rule["space_after_unit"] = str(self.space_after_unit_combo.currentData() or "multiple") + if self._loading: + return + rule = normalize_rule(self.rules.get(self._current_target, {})) + def put(key: str, value: object) -> None: + if value is None: + rule.pop(key, None) + else: + rule[key] = value + for key, box in (("chinese_font_family", self.font_combo), ("english_font_family", self.english_font_combo)): + put(key, box.currentText() if box.currentText() != "继承" else None) + size = self.font_size_spin.value() + put("font_size", size if size > 0 else None) + put("font_size_unit", self.font_size_unit_combo.currentData() if size > 0 else None) + for key, box in self.bool_boxes.items(): + put(key, None if box.checkState() == Qt.CheckState.PartiallyChecked else box.isChecked()) + color = self.color_combo.currentData() + put("font_color", self.color_button.text() if color == "custom" else color) + direction = self.character_spacing_combo.currentData() + put("letter_spacing", None if direction is None else direction * self.character_spacing_spin.value()) + put("alignment", self.alignment_combo.currentData()) + for side in ("left", "right", "space_before", "space_after"): + prefix = f"{side}_indent" if side in ("left", "right") else side + value = getattr(self, f"{prefix}_spin").value() + put(f"{prefix}_value", value if value >= 0 else None) + put(f"{prefix}_unit", getattr(self, f"{prefix}_unit_combo").currentData() if value >= 0 else None) + mode = self.indent_mode_combo.currentData() + put("indent_mode", mode) + put("indent_value", None if mode is None else 0 if mode == "none" else self.indent_spin.value()) + mode = self.line_height_mode_combo.currentData() + preset = {"single": 1, "one_half": 1.5, "double": 2} + put("line_spacing_mode", "multiple" if mode in preset else mode) + put("line_height_value", None if mode is None else preset.get(mode, self.line_height_spin.value())) + rule.pop("line_height_unit", None) if rule: self.rules[self._current_target] = rule else: self.rules.pop(self._current_target, None) - def _load_rule_to_widgets(self, rule: dict[str, Any]) -> None: - self._loading = True - chinese_family = str(rule.get("chinese_font_family") or rule.get("font_family") or DEFAULT_CHINESE_FONT) - english_family = str(rule.get("english_font_family") or DEFAULT_ENGLISH_FONT) - self.chinese_font_combo.setCurrentFont(QFont(chinese_family)) - self.english_font_combo.setCurrentFont(QFont(english_family)) - self.font_size_spin.setValue(int(_positive_float(rule.get("font_size")))) - self.bold_checkbox.setChecked(bool(rule.get("bold"))) - self.italic_checkbox.setChecked(bool(rule.get("italic"))) - self.line_height_spin.setValue(_positive_float(rule.get("line_height_value", rule.get("line_height")))) - self._set_combo_data(self.line_height_unit_combo, str(rule.get("line_height_unit") or "multiple")) - self.first_indent_spin.setValue(_positive_float(rule.get("first_line_indent_chars", rule.get("first_line_indent")))) - self.hanging_indent_spin.setValue(_positive_float(rule.get("hanging_indent_chars", rule.get("hanging_indent")))) - self.space_before_spin.setValue(_positive_float(rule.get("space_before_value", rule.get("space_before")))) - self._set_combo_data(self.space_before_unit_combo, str(rule.get("space_before_unit") or "multiple")) - self.space_after_spin.setValue(_positive_float(rule.get("space_after_value", rule.get("space_after")))) - self._set_combo_data(self.space_after_unit_combo, str(rule.get("space_after_unit") or "multiple")) - self._loading = False + def _change_target(self, current: QListWidgetItem, previous: QListWidgetItem | None) -> None: + self._store_current_rule() + self._current_target = current.data(Qt.ItemDataRole.UserRole) + self._load_rule_to_widgets(self.rules.get(self._current_target, {})) - def _sync_font_enabled(self) -> None: - return - - def _set_combo_data(self, combo: QComboBox, value: str) -> None: - index = combo.findData(value) - combo.setCurrentIndex(max(0, index)) - - def _store_and_refresh(self) -> None: - if not self._loading: - self._store_current_rule() - - def _reset_current_target(self) -> None: + def _reset_current_rule(self) -> None: self.rules.pop(self._current_target, None) self._load_rule_to_widgets({}) + + def _store_and_refresh(self, *_: object) -> None: + if not self._loading: + self._store_current_rule() + self._refresh_preview() + + def _refresh_preview(self) -> None: + self.indent_spin.setEnabled(self.indent_mode_combo.currentData() in ("first", "hanging")) + self.line_height_spin.setEnabled(self.line_height_mode_combo.currentData() in ("multiple", "exact", "at_least")) + self.character_spacing_spin.setEnabled(self.character_spacing_combo.currentData() in (-1, 1)) + self.color_button.setEnabled(self.color_combo.currentData() == "custom") + parent = self.parent() + rule = resolved_rules(self.rules, getattr(parent, "document_font_family", ""), + getattr(parent, "document_font_size", 16))[self._current_target] + points = font_points(rule) + block = QTextBlockFormat() + block.setAlignment({"left": Qt.AlignmentFlag.AlignLeft, "center": Qt.AlignmentFlag.AlignHCenter, + "right": Qt.AlignmentFlag.AlignRight, "justify": Qt.AlignmentFlag.AlignJustify}[rule["alignment"]]) + # QTextDocument distances are logical pixels; Word values are points. + scale = 96 / 72 + for side, setter in (("left", block.setLeftMargin), ("right", block.setRightMargin)): + setter(length_points(rule[f"{side}_indent_value"], rule[f"{side}_indent_unit"], points) * scale) + indent = number(rule["indent_value"]) * points * scale + block.setTextIndent(indent if rule["indent_mode"] == "first" else -indent if rule["indent_mode"] == "hanging" else 0) + mode = rule["line_spacing_mode"] + block.setLineHeight(number(rule["line_height_value"]) * (100 if mode == "multiple" else scale), + {"multiple": 1, "exact": 2, "at_least": 3}[mode]) + for side, setter in (("before", block.setTopMargin), ("after", block.setBottomMargin)): + setter(length_points(rule[f"space_{side}_value"], rule[f"space_{side}_unit"], points, line_points(rule, points)) * scale) + self.preview.clear() + cursor = self.preview.textCursor() + for index, sample in enumerate(("中文段落预览:字体、缩进与行距会实时更新。English text 123. 这段示例用于查看排版效果。", "第二段示例:观察段落之间的间距。Preview the next paragraph.")): + current = QTextBlockFormat(block) + if rule["contextual_spacing"]: + if index == 0: + current.setBottomMargin(0) + else: + current.setTopMargin(0) + if index: + cursor.insertBlock(current) + else: + cursor.setBlockFormat(current) + for part in re.findall(r"[\x00-\x7f]+|[^\x00-\x7f]+", sample): + char = QTextCharFormat() + char.setFontFamilies([str(rule["english_font_family"] if part.isascii() else rule["chinese_font_family"])]) + char.setFontPointSize(points) + char.setFontWeight(QFont.Weight.Bold if rule["bold"] else QFont.Weight.Normal) + char.setFontItalic(rule["italic"]) + char.setForeground(QColor("#23272f" if rule["font_color"] == "auto" else rule["font_color"])) + char.setFontLetterSpacingType(QFont.SpacingType.AbsoluteSpacing) + char.setFontLetterSpacing(number(rule["letter_spacing"]) * scale) + cursor.insertText(part, char) + self.preview.moveCursor(QTextCursor.MoveOperation.Start) diff --git a/tests/test_document_style.py b/tests/test_document_style.py new file mode 100644 index 0000000..0292bc2 --- /dev/null +++ b/tests/test_document_style.py @@ -0,0 +1,179 @@ +from __future__ import annotations + +import os +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + +import zipfile +from pathlib import Path +from lxml import etree as ET +import pytest +from PySide6.QtCore import Qt +from PySide6.QtWidgets import QApplication + +from mdhelper.document_style import build_document_style_css, normalize_rule +from mdhelper.docx_exporter import export_markdown_to_docx +from mdhelper.style_dialog import DocumentStyleEditorDialog + +W = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}" +NS = {"w": W[1:-1]} +SOURCE = "# Heading 标题\n\nBody 正文 **bold** and *italic*.\n\nSecond 第二段。\n\n- List 列表\n\n> Quote 引用\n\n```\nCode 代码\n```\n\n| Table | 表头 |\n| --- | --- |\n| Cell | 单元格 |\n" +RULE = dict(chinese_font_family="宋体", english_font_family="Times New Roman", font_size=10.5, font_size_unit="pt", + bold=False, italic=False, font_color="#123456", letter_spacing=1.25, alignment="justify", + left_indent_value=1.5, left_indent_unit="cm", right_indent_value=6, right_indent_unit="pt", + indent_mode="first", indent_value=2, line_spacing_mode="exact", line_height_value=20, + space_before_value=0, space_before_unit="pt", space_after_value=0, space_after_unit="pt", + contextual_spacing=True, keep_with_next=True, keep_lines_together=True, page_break_before=False, widow_control=False) + + +def test_css_preserves_zero_and_explicit_false(): + css = build_document_style_css({"h2": RULE}) + for expected in ("font-weight: 400", "font-style: normal", "font-size: 10.5pt", "margin-top: 0pt", + "margin-bottom: 0pt", "text-indent: 2em", "text-align: justify", "letter-spacing: 1.25pt", + "line-height: 20pt", "break-before: auto", "widows: 1", "h2 + h2"): + assert expected in css + + +def test_contextual_spacing_stays_within_the_selected_target(): + css = build_document_style_css({"paragraph": {"contextual_spacing": True}, "blockquote": {"contextual_spacing": True}}) + assert ".reader p + p" not in css + assert ".reader blockquote > p + p" in css + + +def test_legacy_rule_migration_preserves_units_and_resolves_conflicting_indents(): + rule = normalize_rule(dict(font_size=18, first_line_indent_chars=2, hanging_indent_chars=1, + line_height_value=22, line_height_unit="pt", space_after_value=.6, space_after_unit="multiple")) + assert rule["indent_mode"] == "hanging" and rule["indent_value"] == 1 + assert rule["line_spacing_mode"] == "exact" and rule["space_after_unit"] == "em" + assert "font-size: 18px" in build_document_style_css({"paragraph": rule}) + + +@pytest.fixture +def app(): + return QApplication.instance() or QApplication([]) + + +def test_dialog_roundtrip_inherit_reset_and_live_preview(app): + dialog = DocumentStyleEditorDialog({"rules": {"paragraph": RULE}, "extra_css": ""}) + try: + assert dialog.style_payload()["rules"]["paragraph"] == RULE + assert dialog.preview.document().firstBlock().blockFormat().textIndent() > 0 + dialog.indent_mode_combo.setCurrentIndex(dialog.indent_mode_combo.findData("hanging")) + assert dialog.preview.document().firstBlock().blockFormat().textIndent() < 0 + dialog.space_after_spin.setValue(0) + dialog.bold_checkbox.setCheckState(Qt.CheckState.Unchecked) + saved = dialog.style_payload()["rules"]["paragraph"] + assert saved["bold"] is False and saved["space_after_value"] == 0 + dialog.target_list.setCurrentRow(2) + assert dialog.bold_checkbox.checkState() == Qt.CheckState.PartiallyChecked + dialog.target_list.setCurrentRow(0) + assert dialog.indent_mode_combo.currentData() == "hanging" + dialog._reset_current_rule() + assert dialog.style_payload()["rules"] == {} + finally: + dialog.close() + + +def test_dialog_legacy_px_and_no_duplicate_generated_css(app): + dialog = DocumentStyleEditorDialog({"rules": {"paragraph": {"font_size": 18}}, "css": ".reader p {font-size:18px}"}) + try: + assert dialog.font_size_unit_combo.currentData() == "px" + assert not dialog.extra_css_edit.toPlainText() + dialog.font_size_preset_combo.setCurrentIndex(dialog.font_size_preset_combo.findData(10.5)) + rule = dialog.style_payload()["rules"]["paragraph"] + assert rule["font_size"] == 10.5 and rule["font_size_unit"] == "pt" + finally: + dialog.close() + + +def read_xml(path): + with zipfile.ZipFile(path) as package: + return ET.fromstring(package.read("word/document.xml")), ET.fromstring(package.read("word/styles.xml")) + + +@pytest.mark.parametrize("engine", ["builtin", "python-docx", "pandoc"]) +def test_word_preserves_all_settings_and_content(tmp_path: Path, engine): + rules = {key: dict(RULE) for key in ("paragraph", "h1", "list", "blockquote", "code", "table")} + path = export_markdown_to_docx(SOURCE, tmp_path / f"{engine}.docx", engine=engine, style_rules=rules) + doc, styles = read_xml(path) + paragraphs = doc.findall(".//w:p", NS) + assert len(paragraphs) >= 10 + for p in paragraphs: + ppr = p.find(W + "pPr") + assert ppr.find(W + "jc").get(W + "val") == "both" + spacing = ppr.find(W + "spacing") + assert spacing.get(W + "before") == spacing.get(W + "after") == "0" + assert spacing.get(W + "line") == "400" and spacing.get(W + "lineRule") == "exact" + ind = ppr.find(W + "ind") + assert ind.get(W + "firstLineChars") == "200" and ind.get(W + "right") == "120" + assert ind.get(W + "left") == "850" + for name, value in (("keepNext", "1"), ("keepLines", "1"), ("contextualSpacing", "1"), ("pageBreakBefore", "0"), ("widowControl", "0")): + assert ppr.find(W + name).get(W + "val") == value + for run in p.findall(".//w:r", NS): + rpr = run.find(W + "rPr") + assert rpr.find(W + "rFonts").get(W + "eastAsia") == "宋体" + assert rpr.find(W + "rFonts").get(W + "ascii") == "Times New Roman" + assert rpr.find(W + "sz").get(W + "val") == "21" + assert rpr.find(W + "color").get(W + "val") == "123456" + assert rpr.find(W + "spacing").get(W + "val") == "25" + heading = paragraphs[0] + assert heading.find(".//w:rPr/w:b", NS).get(W + "val") == "0" + body = next(p for p in paragraphs if "Body" in "".join(p.itertext())) + bold_run = next(r for r in body.findall("w:r", NS) if "".join(r.itertext()) == "bold") + assert bold_run.find("w:rPr/w:b", NS).get(W + "val") == "1" + # Every assigned style exists in the styles part (including the basic exporter). + ids = {s.get(W + "styleId") for s in styles.findall(W + "style")} + assert all(p.find("w:pPr/w:pStyle", NS).get(W + "val") in ids for p in paragraphs) + from docx import Document + assert Document(str(path)).tables + + +@pytest.mark.parametrize("mode,value,expected", [("multiple", 1.5, ("360", "auto")), ("exact", 18, ("360", "exact")), ("at_least", 18, ("360", "atLeast"))]) +def test_word_line_modes_hanging_and_line_spacing_units(tmp_path, mode, value, expected): + rule = dict(RULE, line_spacing_mode=mode, line_height_value=value, indent_mode="hanging", indent_value=1.5, + space_after_value=.5, space_after_unit="line", page_break_before=True) + path = export_markdown_to_docx("段落", tmp_path / "modes.docx", style_rules={"paragraph": rule}) + doc, _ = read_xml(path) + ppr = doc.find(".//w:pPr", NS) + spacing = ppr.find(W + "spacing") + assert (spacing.get(W + "line"), spacing.get(W + "lineRule")) == expected + assert spacing.get(W + "afterLines") == "50" + ind = ppr.find(W + "ind") + assert ind.get(W + "hangingChars") == "150" and ind.get(W + "firstLine") is None + assert ind.get(W + "left") == "850" # Hanging does not change the chosen left indent. + assert ppr.find(W + "pageBreakBefore").get(W + "val") == "1" + + +@pytest.mark.parametrize("engine", ["builtin", "python-docx", "pandoc"]) +def test_word_targets_are_independent(tmp_path, engine): + rules = {key: {"font_color": color} for key, color in [("paragraph", "#111111"), ("h1", "#222222"), + ("list", "#333333"), ("blockquote", "#444444"), ("code", "#555555"), ("table", "#666666")]} + path = export_markdown_to_docx(SOURCE, tmp_path / "targets.docx", engine=engine, style_rules=rules) + doc, _ = read_xml(path) + for word, color in [("Body", "111111"), ("Heading", "222222"), ("List", "333333"), ("Quote", "444444"), ("Code", "555555"), ("Cell", "666666")]: + run = next(r for r in doc.iter(W + "r") if word in "".join(r.itertext())) + assert run.find("w:rPr/w:color", NS).get(W + "val") == color + + +def test_pandoc_exports_supplied_text_and_relative_destination(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + source = tmp_path / "original.md" + source.write_text("Old", encoding="utf-8") + result = export_markdown_to_docx("Updated", Path("output.docx"), engine="pandoc", source_path=source) + doc, _ = read_xml(result) + assert "Updated" in "".join(doc.itertext()) and "Old" not in "".join(doc.itertext()) + + +def test_pandoc_style_processing_preserves_math_links_and_numbering(tmp_path): + source = "[OpenAI](https://openai.com) and $x^2+y^2$.\n\n1. First\n2. Second\n\n - Nested\n" + 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")) + rels = package.read("word/_rels/document.xml.rels").decode() + assert xml.find(".//w:hyperlink", NS) is not None + assert "https://openai.com" in rels + assert xml.find(".//{http://schemas.openxmlformats.org/officeDocument/2006/math}oMath") is not None + assert xml.find(".//w:numPr", NS) is not None + assert "word/numbering.xml" in package.namelist() + levels = xml.findall(".//w:pPr[w:numPr]", NS) + nested = [p for p in levels if p.find("w:numPr/w:ilvl", NS).get(W + "val") == "1"] + assert nested and int(nested[0].find(W + "ind").get(W + "left")) > 720 diff --git a/tests/test_renderer.py b/tests/test_renderer.py index c9377d3..0f573e5 100644 --- a/tests/test_renderer.py +++ b/tests/test_renderer.py @@ -275,7 +275,7 @@ def test_document_style_builder_supports_word_like_paragraph_options() -> None: assert "margin-bottom: 0.6em;" in css assert ".reader h2" in css assert "font-weight: 700;" in css - assert "padding-left: 1.5em;" in css + assert "margin-left: 1.5em;" in css assert "text-indent: -1.5em;" in css assert ".reader blockquote p" in css assert ".reader .admonition p" in css