md2todocx 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,99 @@
1
+ Metadata-Version: 2.3
2
+ Name: md2todocx
3
+ Version: 0.1.0
4
+ Summary: Markdown 转 Word(.docx) 通用命令行工具,内置多套文档主题
5
+ Author: Your Name
6
+ Author-email: Your Name <you@example.com>
7
+ License: MIT
8
+ Classifier: Programming Language :: Python :: 3
9
+ Requires-Dist: markdown-it-py[linkify]>=4.3.0
10
+ Requires-Dist: python-docx>=1.2.0
11
+ Requires-Dist: mdit-py-plugins>=0.5
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+
15
+ # md2docx
16
+
17
+ Markdown 转 Word(.docx)通用命令行工具:内置 8 套文档主题、3 种页面版式,完整适配 Markdown 语法(表格、代码块、图片真实嵌入、超链接、脚注、任务列表、定义列表、数学公式等)。
18
+
19
+ ## 安装
20
+
21
+ ```bash
22
+ # 在任意目录用 uv 运行(本仓库内)
23
+ uv run md2todocx --help
24
+
25
+ # 或以工具方式安装
26
+ uv tool install --editable .
27
+ ```
28
+
29
+ 依赖:Python ≥ 3.10,`markdown-it-py[linkify]`、`python-docx`、`mdit-py-plugins`。
30
+
31
+ ## 用法
32
+
33
+ ```bash
34
+ md2todocx FILES... [-o OUT] [--theme T] [--page P] [--title S] [--subtitle S]
35
+ [--toc] [--cover] [--no-footer] [--split]
36
+ ```
37
+
38
+ - `FILES`:一个或多个 Markdown 文件。多文件默认**合并**为一份 docx(第 2 个及以后的文件若以 `#` H1 开头则从新页起页);`--split` 时按文件分别输出。
39
+ - `-o/--output`:输出路径,默认与首个输入文件同名 `.docx`。
40
+ - `--theme`:`business`(商务蓝,默认)/ `minimal`(极简黑白)/ `academic`(学术宋体)/ `forest`(墨绿商务)/ `ocean`(海洋蓝青)/ `sunset`(暖橙)/ `violet`(科技紫)/ `plum`(勃艮第红)。
41
+ - `--page`:`a4-portrait`(A4 竖版,默认)/ `a4-landscape`(A4 横版)/ `widescreen`(宽屏电子档)。
42
+ - `--title` / `--subtitle`:提供任一则自动生成封面;合并多文件时封面自动列出输入文件名。
43
+ - `--toc`:插入 Word 目录域(打开文档后自动刷新;未刷新可全选按 F9)。
44
+ - `--cover`:无标题也强制生成封面。
45
+ - `--no-footer`:不添加「第 X 页 / 共 Y 页」页脚。
46
+ - 退出码:成功 `0`;输出写入失败 `1`;参数冲突、全部文件缺失或文件无法解码为 `2`;部分文件缺失仅警告继续。
47
+ - 文件编码:UTF-8 优先,GBK 自动降级解码;均失败时给出中文错误提示。
48
+
49
+ ## 示例
50
+
51
+ ```bash
52
+ # 单文件,A4 竖版,商务蓝主题
53
+ md2todocx 笔记.md
54
+
55
+ # 多文件合并 + 目录 + 封面(宽屏,适合电子档阅读)
56
+ md2todocx 01-功能.md 02-设计.md 03-UI.md --theme business --page widescreen \
57
+ --title "项目说明书" --toc -o 说明书.docx
58
+
59
+ # 学术风、每个文件单独输出
60
+ md2todocx chapters/*.md --theme academic --split
61
+ ```
62
+
63
+ ## Markdown 语法支持
64
+
65
+ | 语法 | 渲染方式 |
66
+ |------|----------|
67
+ | 标题 1–6 | Word Heading 1–6 样式(可生成目录) |
68
+ | 粗体/斜体/删除线/行内代码 | 原生 Word 格式,行内代码等宽 + 浅底纹 |
69
+ | 有序/无序/嵌套列表 | 有序列表逐列表独立计数 |
70
+ | 任务列表 `- [ ]` / `- [x]` | ☐ / ☑ |
71
+ | 表格 | 全宽、表头底纹、跨页重复表头 |
72
+ | 代码块 | 1×1 底纹表格承载,等宽字体 |
73
+ | 引用块 / 分隔线 / 硬换行 | 缩进 + 左竖线 / 底边框线 |
74
+ | 超链接与自动链接 | 真实 Word 超链接(主题色 + 下划线) |
75
+ | 图片 `![alt](path)` | 本地图片真实嵌入(超宽自动缩放,alt 作图注);缺失/远程图片降级为占位文字 |
76
+ | 脚注 `[^1]` | 正文上标编号 + 文末「注释」小节 |
77
+ | 定义列表 | 术语加粗、定义缩进 |
78
+ | 数学 `$…$` / `$$…$$` | 等宽文本降级展示(非原生公式) |
79
+ | HTML | `<br>` 换行;其余标签剥离保留文本 |
80
+
81
+ ## 项目结构
82
+
83
+ ```
84
+ src/md2docx/
85
+ cli.py 命令行入口
86
+ docbuild.py 文档组装(样式/封面/目录/页脚/多文件合并)
87
+ renderer.py Markdown token → docx 渲染器
88
+ oxml.py OOXML 底层工具
89
+ theme.py 主题与页面版式预设
90
+ tests/ pytest 测试 + 全语法样例 sample.md
91
+ ```
92
+
93
+ ## 开发
94
+
95
+ ```bash
96
+ uv sync
97
+ uv run pytest # 全量测试
98
+ uv run ruff check . # Lint
99
+ ```
@@ -0,0 +1,85 @@
1
+ # md2docx
2
+
3
+ Markdown 转 Word(.docx)通用命令行工具:内置 8 套文档主题、3 种页面版式,完整适配 Markdown 语法(表格、代码块、图片真实嵌入、超链接、脚注、任务列表、定义列表、数学公式等)。
4
+
5
+ ## 安装
6
+
7
+ ```bash
8
+ # 在任意目录用 uv 运行(本仓库内)
9
+ uv run md2todocx --help
10
+
11
+ # 或以工具方式安装
12
+ uv tool install --editable .
13
+ ```
14
+
15
+ 依赖:Python ≥ 3.10,`markdown-it-py[linkify]`、`python-docx`、`mdit-py-plugins`。
16
+
17
+ ## 用法
18
+
19
+ ```bash
20
+ md2todocx FILES... [-o OUT] [--theme T] [--page P] [--title S] [--subtitle S]
21
+ [--toc] [--cover] [--no-footer] [--split]
22
+ ```
23
+
24
+ - `FILES`:一个或多个 Markdown 文件。多文件默认**合并**为一份 docx(第 2 个及以后的文件若以 `#` H1 开头则从新页起页);`--split` 时按文件分别输出。
25
+ - `-o/--output`:输出路径,默认与首个输入文件同名 `.docx`。
26
+ - `--theme`:`business`(商务蓝,默认)/ `minimal`(极简黑白)/ `academic`(学术宋体)/ `forest`(墨绿商务)/ `ocean`(海洋蓝青)/ `sunset`(暖橙)/ `violet`(科技紫)/ `plum`(勃艮第红)。
27
+ - `--page`:`a4-portrait`(A4 竖版,默认)/ `a4-landscape`(A4 横版)/ `widescreen`(宽屏电子档)。
28
+ - `--title` / `--subtitle`:提供任一则自动生成封面;合并多文件时封面自动列出输入文件名。
29
+ - `--toc`:插入 Word 目录域(打开文档后自动刷新;未刷新可全选按 F9)。
30
+ - `--cover`:无标题也强制生成封面。
31
+ - `--no-footer`:不添加「第 X 页 / 共 Y 页」页脚。
32
+ - 退出码:成功 `0`;输出写入失败 `1`;参数冲突、全部文件缺失或文件无法解码为 `2`;部分文件缺失仅警告继续。
33
+ - 文件编码:UTF-8 优先,GBK 自动降级解码;均失败时给出中文错误提示。
34
+
35
+ ## 示例
36
+
37
+ ```bash
38
+ # 单文件,A4 竖版,商务蓝主题
39
+ md2todocx 笔记.md
40
+
41
+ # 多文件合并 + 目录 + 封面(宽屏,适合电子档阅读)
42
+ md2todocx 01-功能.md 02-设计.md 03-UI.md --theme business --page widescreen \
43
+ --title "项目说明书" --toc -o 说明书.docx
44
+
45
+ # 学术风、每个文件单独输出
46
+ md2todocx chapters/*.md --theme academic --split
47
+ ```
48
+
49
+ ## Markdown 语法支持
50
+
51
+ | 语法 | 渲染方式 |
52
+ |------|----------|
53
+ | 标题 1–6 | Word Heading 1–6 样式(可生成目录) |
54
+ | 粗体/斜体/删除线/行内代码 | 原生 Word 格式,行内代码等宽 + 浅底纹 |
55
+ | 有序/无序/嵌套列表 | 有序列表逐列表独立计数 |
56
+ | 任务列表 `- [ ]` / `- [x]` | ☐ / ☑ |
57
+ | 表格 | 全宽、表头底纹、跨页重复表头 |
58
+ | 代码块 | 1×1 底纹表格承载,等宽字体 |
59
+ | 引用块 / 分隔线 / 硬换行 | 缩进 + 左竖线 / 底边框线 |
60
+ | 超链接与自动链接 | 真实 Word 超链接(主题色 + 下划线) |
61
+ | 图片 `![alt](path)` | 本地图片真实嵌入(超宽自动缩放,alt 作图注);缺失/远程图片降级为占位文字 |
62
+ | 脚注 `[^1]` | 正文上标编号 + 文末「注释」小节 |
63
+ | 定义列表 | 术语加粗、定义缩进 |
64
+ | 数学 `$…$` / `$$…$$` | 等宽文本降级展示(非原生公式) |
65
+ | HTML | `<br>` 换行;其余标签剥离保留文本 |
66
+
67
+ ## 项目结构
68
+
69
+ ```
70
+ src/md2docx/
71
+ cli.py 命令行入口
72
+ docbuild.py 文档组装(样式/封面/目录/页脚/多文件合并)
73
+ renderer.py Markdown token → docx 渲染器
74
+ oxml.py OOXML 底层工具
75
+ theme.py 主题与页面版式预设
76
+ tests/ pytest 测试 + 全语法样例 sample.md
77
+ ```
78
+
79
+ ## 开发
80
+
81
+ ```bash
82
+ uv sync
83
+ uv run pytest # 全量测试
84
+ uv run ruff check . # Lint
85
+ ```
@@ -0,0 +1,32 @@
1
+ [project]
2
+ name = "md2todocx"
3
+ version = "0.1.0"
4
+ description = "Markdown 转 Word(.docx) 通用命令行工具,内置多套文档主题"
5
+ readme = "README.md"
6
+ requires-python = ">=3.10"
7
+ classifiers = ["Programming Language :: Python :: 3"]
8
+ dependencies = [
9
+ "markdown-it-py[linkify]>=4.3.0",
10
+ "python-docx>=1.2.0",
11
+ "mdit-py-plugins>=0.5",
12
+ ]
13
+
14
+ [project.license]
15
+ text = "MIT"
16
+
17
+ [[project.authors]]
18
+ name = "Your Name"
19
+ email = "you@example.com"
20
+
21
+ [project.scripts]
22
+ m2td = "md2todocx.cli:main"
23
+
24
+ [build-system]
25
+ requires = ["uv_build>=0.13.0,<0.14.0"]
26
+ build-backend = "uv_build"
27
+
28
+ [dependency-groups]
29
+ dev = [
30
+ "pytest>=8.0",
31
+ "ruff>=0.17.6",
32
+ ]
@@ -0,0 +1,30 @@
1
+ [project]
2
+ name = "md2todocx"
3
+ version = "0.1.0"
4
+ description = "Markdown 转 Word(.docx) 通用命令行工具,内置多套文档主题"
5
+ readme = "README.md"
6
+ requires-python = ">=3.10"
7
+ license = {text = "MIT"}
8
+ authors = [
9
+ { name = "Your Name", email = "you@example.com" }
10
+ ]
11
+
12
+ classifiers = [
13
+ "Programming Language :: Python :: 3",
14
+ ]
15
+
16
+ dependencies = [
17
+ "markdown-it-py[linkify]>=4.3.0",
18
+ "python-docx>=1.2.0",
19
+ "mdit-py-plugins>=0.5",
20
+ ]
21
+
22
+ [project.scripts]
23
+ m2td = "md2todocx.cli:main"
24
+
25
+ [build-system]
26
+ requires = ["uv_build>=0.13.0,<0.14.0"]
27
+ build-backend = "uv_build"
28
+
29
+ [dependency-groups]
30
+ dev = ["pytest>=8.0", "ruff>=0.17.6"]
File without changes
@@ -0,0 +1,95 @@
1
+ """md2todocx 命令行入口。"""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ from .docbuild import build_document
9
+ from .theme import THEMES
10
+
11
+ PAGE_ALIASES = {
12
+ "a4-portrait": "a4_portrait",
13
+ "a4-landscape": "a4_landscape",
14
+ "widescreen": "widescreen",
15
+ }
16
+
17
+
18
+ def main(argv: list[str] | None = None) -> int:
19
+ parser = argparse.ArgumentParser(
20
+ prog="md2todocx",
21
+ description="Markdown 转 Word(.docx) 通用转换工具,内置多套文档主题")
22
+ parser.add_argument("files", nargs="+", metavar="FILE",
23
+ help="输入 Markdown 文件(多个时合并为一份 docx,每个文件从新页开始)")
24
+ parser.add_argument("-o", "--output",
25
+ help="输出 docx 路径(默认与首个输入文件同名)")
26
+ parser.add_argument("--theme", choices=sorted(THEMES), default="business",
27
+ help="文档主题(默认 business)")
28
+ parser.add_argument("--page", choices=sorted(PAGE_ALIASES), default="a4-portrait",
29
+ help="页面版式(默认 a4-portrait)")
30
+ parser.add_argument("--title", default="", help="封面标题(提供后生成封面)")
31
+ parser.add_argument("--subtitle", default="", help="封面副标题")
32
+ parser.add_argument("--toc", action="store_true",
33
+ help="插入 Word 目录域(打开文档后自动刷新)")
34
+ parser.add_argument("--cover", action="store_true", help="强制生成封面")
35
+ parser.add_argument("--no-footer", dest="footer", action="store_false",
36
+ help="不添加页码页脚")
37
+ parser.add_argument("--split", action="store_true",
38
+ help="按文件分别输出(每个 md 生成一个 docx)")
39
+ args = parser.parse_args(argv)
40
+
41
+ files = [Path(f) for f in args.files]
42
+ existing = [f for f in files if f.is_file()]
43
+ missing = [f for f in files if not f.is_file()]
44
+ for f in missing:
45
+ print(f"警告:输入文件不存在,已跳过:{f}", file=sys.stderr)
46
+ if not existing:
47
+ print("错误:所有输入文件都不存在,未生成文档。", file=sys.stderr)
48
+ return 2
49
+
50
+ theme = THEMES[args.theme]
51
+ page = PAGE_ALIASES[args.page]
52
+
53
+ if args.split:
54
+ if args.output:
55
+ print("错误:--split 与 -o/--output 不能同时使用。", file=sys.stderr)
56
+ return 2
57
+ if args.toc or args.title or args.subtitle or args.cover:
58
+ print("警告:--split 模式忽略 --toc/--title/--subtitle/--cover。",
59
+ file=sys.stderr)
60
+ for f in existing:
61
+ # spec §5.2:--split 时 TOC/封面不生效(与上方警告一致)
62
+ try:
63
+ doc = build_document([f], theme, page, title="",
64
+ subtitle="", toc=False,
65
+ cover=False, footer=args.footer)
66
+ out = f.with_suffix(".docx")
67
+ doc.save(out)
68
+ except ValueError as e: # 编码等文档级错误
69
+ print(f"错误:{e}", file=sys.stderr)
70
+ return 2
71
+ except OSError as e: # 输出路径不可写等
72
+ print(f"错误:无法写入输出文件 {f.with_suffix('.docx')}:{e}",
73
+ file=sys.stderr)
74
+ return 1
75
+ print(f"OK -> {out}")
76
+ return 0
77
+
78
+ out = Path(args.output) if args.output else existing[0].with_suffix(".docx")
79
+ try:
80
+ doc = build_document(existing, theme, page, title=args.title,
81
+ subtitle=args.subtitle, toc=args.toc,
82
+ cover=args.cover, footer=args.footer)
83
+ doc.save(out)
84
+ except ValueError as e:
85
+ print(f"错误:{e}", file=sys.stderr)
86
+ return 2
87
+ except OSError as e:
88
+ print(f"错误:无法写入输出文件 {out}:{e}", file=sys.stderr)
89
+ return 1
90
+ print(f"OK -> {out}")
91
+ return 0
92
+
93
+
94
+ if __name__ == "__main__":
95
+ sys.exit(main())
@@ -0,0 +1,175 @@
1
+ # pyright: reportGeneralTypeIssues=false, reportOptionalMemberAccess=false, reportArgumentType=false, reportUnknownParameterType=false, reportMissingParameterType=false, reportUnknownVariableType=false, reportUnknownMemberType=false, reportUnknownArgumentType=false, reportUnannotatedClassAttribute=false, reportUnusedVariable=false
2
+ """文档组装:样式、封面、目录、页脚、updateFields、多文件合并。"""
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ from docx import Document
8
+ from docx.enum.text import WD_ALIGN_PARAGRAPH
9
+ from docx.oxml import OxmlElement
10
+ from docx.oxml.ns import qn
11
+ from docx.shared import Pt
12
+
13
+ from .oxml import add_fld, set_font
14
+ from .renderer import Renderer, build_parser, plain_text
15
+ from .theme import PAGE_PROFILES, Theme
16
+
17
+ _HEADING_SPACING = {1: (16, 8), 2: (12, 6), 3: (10, 4)}
18
+
19
+
20
+ def setup_styles(doc: Document, theme: Theme, page: str = "a4_portrait"):
21
+ normal = doc.styles["Normal"]
22
+ normal.font.name = theme.font_body_latin
23
+ normal.font.size = Pt(theme.body_size)
24
+ normal.font.color.rgb = theme.color_dark
25
+ normal.element.get_or_add_rPr().get_or_add_rFonts().set(
26
+ qn("w:eastAsia"), theme.font_body_east)
27
+ normal.paragraph_format.line_spacing = 1.4
28
+ normal.paragraph_format.space_after = Pt(4)
29
+
30
+ for idx in range(1, 7):
31
+ name = f"Heading {idx}"
32
+ st = doc.styles[name]
33
+ st.font.name = theme.font_head_latin
34
+ st.font.size = Pt(theme.heading_sizes[idx - 1])
35
+ st.font.bold = True
36
+ if idx <= 2:
37
+ st.font.color.rgb = theme.color_brand
38
+ elif idx == 3:
39
+ st.font.color.rgb = theme.color_dark
40
+ else:
41
+ st.font.color.rgb = theme.color_gray
42
+ st.element.get_or_add_rPr().get_or_add_rFonts().set(
43
+ qn("w:eastAsia"), theme.font_head_east)
44
+ before, after = _HEADING_SPACING.get(idx, (8, 4))
45
+ st.paragraph_format.space_before = Pt(before)
46
+ st.paragraph_format.space_after = Pt(after)
47
+ st.paragraph_format.keep_with_next = True
48
+
49
+ title = doc.styles["Title"]
50
+ title.font.name = theme.font_head_latin
51
+ title.font.size = Pt(26)
52
+ title.font.bold = True
53
+ title.font.color.rgb = theme.color_dark
54
+ title.element.get_or_add_rPr().get_or_add_rFonts().set(
55
+ qn("w:eastAsia"), theme.font_head_east)
56
+
57
+ prof = PAGE_PROFILES[page]
58
+ for sec in doc.sections:
59
+ sec.page_width = prof["width"]
60
+ sec.page_height = prof["height"]
61
+ sec.top_margin = prof["top"]
62
+ sec.bottom_margin = prof["bottom"]
63
+ sec.left_margin = prof["left"]
64
+ sec.right_margin = prof["right"]
65
+
66
+
67
+ def add_cover(doc: Document, theme: Theme, title: str, subtitle: str = "",
68
+ info: str = ""):
69
+ for _ in range(6):
70
+ doc.add_paragraph()
71
+ p = doc.add_paragraph(style="Title")
72
+ p.alignment = WD_ALIGN_PARAGRAPH.CENTER
73
+ set_font(p.add_run(title), latin=theme.font_head_latin,
74
+ east=theme.font_head_east, size=28, bold=True, color=theme.color_dark)
75
+ if subtitle:
76
+ sub = doc.add_paragraph()
77
+ sub.alignment = WD_ALIGN_PARAGRAPH.CENTER
78
+ set_font(sub.add_run(subtitle), size=13, color=theme.color_gray)
79
+ if info:
80
+ inf = doc.add_paragraph()
81
+ inf.alignment = WD_ALIGN_PARAGRAPH.CENTER
82
+ set_font(inf.add_run(f"含:{info}"), size=11, color=theme.color_gray)
83
+ brk = doc.add_paragraph()
84
+ brk.paragraph_format.page_break_before = True
85
+
86
+
87
+ def add_toc(doc: Document, theme: Theme):
88
+ h = doc.add_paragraph()
89
+ set_font(h.add_run("目 录"), latin=theme.font_head_latin,
90
+ east=theme.font_head_east, size=16, bold=True, color=theme.color_brand)
91
+ h.paragraph_format.space_after = Pt(10)
92
+ p = doc.add_paragraph()
93
+ add_fld(p, r' TOC \o "1-3" \h \z \u ',
94
+ placeholder="(打开文档后目录自动生成;若未刷新请全选后按 F9)")
95
+ end = doc.add_paragraph()
96
+ end.paragraph_format.page_break_before = True
97
+
98
+
99
+ def add_footer(doc: Document, theme: Theme):
100
+ p = doc.sections[0].footer.paragraphs[0]
101
+ p.alignment = WD_ALIGN_PARAGRAPH.CENTER
102
+ set_font(p.add_run("第 "), size=9, color=theme.color_gray)
103
+ add_fld(p, " PAGE ")
104
+ set_font(p.add_run(" 页 / 共 "), size=9, color=theme.color_gray)
105
+ add_fld(p, " NUMPAGES ")
106
+ set_font(p.add_run(" 页"), size=9, color=theme.color_gray)
107
+
108
+
109
+ def enable_update_fields(doc: Document):
110
+ settings = doc.settings.element
111
+ # 模板自带的 zoom 缺 percent 属性,补上
112
+ zoom = settings.find(qn("w:zoom"))
113
+ if zoom is not None and zoom.get(qn("w:percent")) is None:
114
+ zoom.set(qn("w:percent"), "100")
115
+ # updateFields 必须位于 hdrShapeDefaults/footnotePr/endnotePr/compat 之前
116
+ upd = OxmlElement("w:updateFields")
117
+ upd.set(qn("w:val"), "true")
118
+ for tag in ("w:hdrShapeDefaults", "w:footnotePr", "w:endnotePr", "w:compat"):
119
+ anchor = settings.find(qn(tag))
120
+ if anchor is not None:
121
+ anchor.addprevious(upd)
122
+ return
123
+ settings.append(upd)
124
+
125
+
126
+ def _read_text(path: Path) -> str:
127
+ """读取 md 文本:UTF-8 优先,GBK 降级;均失败给出中文错误。"""
128
+ raw = path.read_bytes()
129
+ for enc in ("utf-8", "gbk"):
130
+ try:
131
+ return raw.decode(enc)
132
+ except UnicodeDecodeError:
133
+ continue
134
+ raise ValueError(f"无法解码文件(已尝试 UTF-8 与 GBK 编码):{path}")
135
+
136
+
137
+ def _first_h1_text(text: str) -> str | None:
138
+ tokens = build_parser().parse(text)
139
+ for i, t in enumerate(tokens):
140
+ if t.type == "heading_open" and t.tag == "h1":
141
+ return plain_text(tokens[i + 1]).strip()
142
+ return None
143
+
144
+
145
+ def build_document(files: list[Path], theme: Theme, page: str, *,
146
+ title: str = "", subtitle: str = "", toc: bool = False,
147
+ cover: bool = False, footer: bool = True) -> Document:
148
+ doc = Document()
149
+ setup_styles(doc, theme, page)
150
+
151
+ texts = [_read_text(f) for f in files]
152
+ first_h1 = _first_h1_text(texts[0]) if texts else None
153
+
154
+ if title or subtitle or cover:
155
+ info = " · ".join(f.stem for f in files) if len(files) > 1 else ""
156
+ add_cover(doc, theme, title or first_h1 or files[0].stem, subtitle, info)
157
+ if toc:
158
+ add_toc(doc, theme)
159
+ if footer:
160
+ add_footer(doc, theme)
161
+ enable_update_fields(doc)
162
+
163
+ renderer = Renderer(doc, theme)
164
+ for k, text in enumerate(texts):
165
+ tokens = build_parser().parse(text)
166
+ # 现状分页语义:仅当第 2 个及以后的文件以 H1 开头时,该 H1 分页起页
167
+ starts_h1 = bool(tokens and tokens[0].type == "heading_open"
168
+ and tokens[0].tag == "h1")
169
+ renderer.first_h1_pending = k > 0 and starts_h1
170
+ renderer.base_dir = files[k].resolve().parent # 图片相对当前 md 文件解析
171
+ renderer.render(tokens)
172
+
173
+ doc.core_properties.title = title or first_h1 or files[0].stem
174
+ doc.core_properties.author = "md2todocx"
175
+ return doc
@@ -0,0 +1,193 @@
1
+ # pyright: reportGeneralTypeIssues=false, reportOptionalMemberAccess=false, reportArgumentType=false, reportUnknownParameterType=false, reportMissingParameterType=false, reportUnknownVariableType=false, reportUnknownMemberType=false, reportUnknownArgumentType=false, reportUnannotatedClassAttribute=false, reportUnusedVariable=false
2
+ """OOXML 底层工具:从 cc-docs 原样移植,正确性由 docx 校验脚本/测试保证。"""
3
+ from __future__ import annotations
4
+
5
+ from docx.document import Document
6
+ from docx.enum.text import WD_PARAGRAPH_ALIGNMENT # noqa: F401 (占位避免误删)
7
+ from docx.opc.constants import RELATIONSHIP_TYPE as RT
8
+ from docx.oxml import OxmlElement
9
+ from docx.oxml.ns import qn
10
+ from docx.shared import Pt
11
+
12
+ # OOXML 子元素顺序(用于 insert_ordered 的后继标签)
13
+ TBLPR_SEQ = ("w:tblStyle", "w:tblpPr", "w:tblOverlap", "w:bidiVisual",
14
+ "w:tblStyleRowBandSize", "w:tblStyleColBandSize", "w:tblW", "w:jc",
15
+ "w:tblCellSpacing", "w:tblInd", "w:tblBorders", "w:shd",
16
+ "w:tblLayout", "w:tblCellMar", "w:tblLook", "w:tblCaption",
17
+ "w:tblDescription", "w:tblPrChange")
18
+ TCPR_SEQ = ("w:cnfStyle", "w:tcW", "w:gridSpan", "w:hMerge", "w:vMerge",
19
+ "w:tcBorders", "w:shd", "w:noWrap", "w:tcMar", "w:textDirection",
20
+ "w:tcFitText", "w:vAlign", "w:hideMark", "w:headers", "w:cellIns",
21
+ "w:cellDel", "w:cellMerge", "w:tcPrChange")
22
+ PPR_SEQ = ("w:pStyle", "w:keepNext", "w:keepLines", "w:pageBreakBefore",
23
+ "w:framePr", "w:widowControl", "w:numPr", "w:suppressLineNumbers",
24
+ "w:pBdr", "w:shd", "w:tabs", "w:suppressAutoHyphens", "w:kinsoku",
25
+ "w:wordWrap", "w:overflowPunct", "w:topLinePunct", "w:autoSpaceDE",
26
+ "w:autoSpaceDN", "w:bidi", "w:adjustRightInd", "w:snapToGrid",
27
+ "w:spacing", "w:ind", "w:contextualSpacing", "w:mirrorIndents",
28
+ "w:suppressOverlap", "w:jc", "w:textDirection", "w:textAlignment",
29
+ "w:textboxTightWrap", "w:outlineLvl", "w:divId", "w:cnfStyle",
30
+ "w:rPr", "w:sectPr", "w:pPrChange")
31
+
32
+
33
+ def insert_ordered(parent, el, seq, tag):
34
+ """按 OOXML schema 顺序把 el 插入 parent。"""
35
+ idx = seq.index(tag)
36
+ successors = seq[idx + 1:]
37
+ parent.insert_element_before(el, *successors)
38
+
39
+
40
+ def set_font(run, *, latin="Calibri", east="等线", size=None, bold=None,
41
+ italic=None, strike=None, color=None):
42
+ run.font.name = latin
43
+ rpr = run._element.get_or_add_rPr()
44
+ rpr.get_or_add_rFonts().set(qn("w:eastAsia"), east)
45
+ if size is not None:
46
+ run.font.size = Pt(size)
47
+ if bold is not None:
48
+ run.font.bold = bold
49
+ if italic is not None:
50
+ run.font.italic = italic
51
+ if strike is not None:
52
+ run.font.strike = strike
53
+ if color is not None:
54
+ run.font.color.rgb = color
55
+ return run
56
+
57
+
58
+ def shade_run(run, fill):
59
+ rpr = run._element.get_or_add_rPr()
60
+ shd = OxmlElement("w:shd")
61
+ shd.set(qn("w:val"), "clear")
62
+ shd.set(qn("w:color"), "auto")
63
+ shd.set(qn("w:fill"), fill)
64
+ rpr.append(shd) # rPr 末尾追加符合 schema(shd 位于尾部区域)
65
+
66
+
67
+ def shade_cell(cell, fill):
68
+ tcpr = cell._tc.get_or_add_tcPr()
69
+ shd = OxmlElement("w:shd")
70
+ shd.set(qn("w:val"), "clear")
71
+ shd.set(qn("w:color"), "auto")
72
+ shd.set(qn("w:fill"), fill)
73
+ insert_ordered(tcpr, shd, TCPR_SEQ, "w:shd")
74
+
75
+
76
+ def cell_borders(cell, border_color):
77
+ tcpr = cell._tc.get_or_add_tcPr()
78
+ borders = OxmlElement("w:tcBorders")
79
+ for edge in ("top", "left", "bottom", "right"):
80
+ el = OxmlElement(f"w:{edge}")
81
+ el.set(qn("w:val"), "single")
82
+ el.set(qn("w:sz"), "4")
83
+ el.set(qn("w:color"), border_color)
84
+ borders.append(el)
85
+ insert_ordered(tcpr, borders, TCPR_SEQ, "w:tcBorders")
86
+
87
+
88
+ def table_fullwidth(table):
89
+ tblpr = table._tbl.tblPr
90
+ width = tblpr.find(qn("w:tblW")) # add_table 已创建 auto 宽度,直接改写避免重复
91
+ if width is None:
92
+ width = OxmlElement("w:tblW")
93
+ insert_ordered(tblpr, width, TBLPR_SEQ, "w:tblW")
94
+ width.set(qn("w:type"), "pct")
95
+ width.set(qn("w:w"), "5000")
96
+ layout = tblpr.find(qn("w:tblLayout"))
97
+ if layout is None:
98
+ layout = OxmlElement("w:tblLayout")
99
+ insert_ordered(tblpr, layout, TBLPR_SEQ, "w:tblLayout")
100
+ layout.set(qn("w:type"), "autofit")
101
+
102
+
103
+ def repeat_header(row):
104
+ trpr = row._tr.get_or_add_trPr()
105
+ el = OxmlElement("w:tblHeader")
106
+ el.set(qn("w:val"), "true")
107
+ trpr.append(el)
108
+
109
+
110
+ def add_fld(paragraph, instr, placeholder="1"):
111
+ fld = OxmlElement("w:fldSimple")
112
+ fld.set(qn("w:instr"), instr)
113
+ r = OxmlElement("w:r")
114
+ t = OxmlElement("w:t")
115
+ t.text = placeholder
116
+ r.append(t)
117
+ fld.append(r)
118
+ paragraph._p.append(fld)
119
+
120
+
121
+ def para_border(paragraph, edge, color, size):
122
+ ppr = paragraph._p.get_or_add_pPr()
123
+ pbdr = ppr.find(qn("w:pBdr"))
124
+ if pbdr is None:
125
+ pbdr = OxmlElement("w:pBdr")
126
+ insert_ordered(ppr, pbdr, PPR_SEQ, "w:pBdr")
127
+ el = OxmlElement(f"w:{edge}")
128
+ el.set(qn("w:val"), "single")
129
+ el.set(qn("w:sz"), size)
130
+ el.set(qn("w:space"), "4")
131
+ el.set(qn("w:color"), color)
132
+ pbdr.append(el)
133
+
134
+
135
+ def set_numpr(paragraph, num_id, ilvl=0):
136
+ ppr = paragraph._p.get_or_add_pPr()
137
+ numpr = ppr.find(qn("w:numPr"))
138
+ if numpr is None:
139
+ numpr = OxmlElement("w:numPr")
140
+ insert_ordered(ppr, numpr, PPR_SEQ, "w:numPr")
141
+ il = OxmlElement("w:ilvl")
142
+ il.set(qn("w:val"), str(ilvl))
143
+ ni = OxmlElement("w:numId")
144
+ ni.set(qn("w:val"), str(num_id))
145
+ numpr.append(il)
146
+ numpr.append(ni)
147
+
148
+
149
+ def make_decimal_numbering(doc: Document):
150
+ """为每个有序列表创建独立编号实例(各列表从 1 重新计数)。"""
151
+ try:
152
+ numbering = doc.part.part_related_by(RT.NUMBERING)
153
+ except KeyError:
154
+ return None
155
+ root = getattr(numbering, "element", None)
156
+ if root is None:
157
+ root = numbering._element
158
+ abstract_ids = [int(e.get(qn("w:abstractNumId")))
159
+ for e in root.findall(qn("w:abstractNum"))]
160
+ num_ids = [int(e.get(qn("w:numId"))) for e in root.findall(qn("w:num"))]
161
+ a_id = (max(abstract_ids) + 1) if abstract_ids else 1
162
+ n_id = (max(num_ids) + 1) if num_ids else 1
163
+
164
+ abstract = OxmlElement("w:abstractNum")
165
+ abstract.set(qn("w:abstractNumId"), str(a_id))
166
+ for lvl in range(3):
167
+ lel = OxmlElement("w:lvl")
168
+ lel.set(qn("w:ilvl"), str(lvl))
169
+ start = OxmlElement("w:start"); start.set(qn("w:val"), "1"); lel.append(start)
170
+ fmt = OxmlElement("w:numFmt"); fmt.set(qn("w:val"), "decimal"); lel.append(fmt)
171
+ text = OxmlElement("w:lvlText"); text.set(qn("w:val"), f"%{lvl + 1}."); lel.append(text)
172
+ jc = OxmlElement("w:lvlJc"); jc.set(qn("w:val"), "left"); lel.append(jc)
173
+ ppr = OxmlElement("w:pPr")
174
+ ind = OxmlElement("w:ind")
175
+ ind.set(qn("w:left"), str(420 * (lvl + 1)))
176
+ ind.set(qn("w:hanging"), "360")
177
+ ppr.append(ind)
178
+ lel.append(ppr)
179
+ abstract.append(lel)
180
+
181
+ num = OxmlElement("w:num")
182
+ num.set(qn("w:numId"), str(n_id))
183
+ abref = OxmlElement("w:abstractNumId")
184
+ abref.set(qn("w:val"), str(a_id))
185
+ num.append(abref)
186
+
187
+ first_num = root.find(qn("w:num"))
188
+ if first_num is not None:
189
+ first_num.addprevious(abstract)
190
+ else:
191
+ root.append(abstract)
192
+ root.append(num)
193
+ return n_id
@@ -0,0 +1,483 @@
1
+ # pyright: reportGeneralTypeIssues=false, reportOptionalMemberAccess=false, reportArgumentType=false, reportUnknownParameterType=false, reportMissingParameterType=false, reportUnknownVariableType=false, reportUnknownMemberType=false, reportUnknownArgumentType=false, reportUnannotatedClassAttribute=false, reportUnusedVariable=false
2
+ """Markdown token 流 → docx 元素渲染器(自 cc-docs Renderer 移植,主题化)。"""
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from pathlib import Path
7
+
8
+ from docx.document import Document
9
+ from docx.enum.table import WD_TABLE_ALIGNMENT
10
+ from docx.enum.text import WD_ALIGN_PARAGRAPH
11
+ from docx.image.image import Image as DocxImage
12
+ from docx.opc.constants import RELATIONSHIP_TYPE as RT
13
+ from docx.oxml import OxmlElement
14
+ from docx.oxml.ns import qn
15
+ from docx.shared import Cm, Emu, Pt
16
+ from markdown_it import MarkdownIt
17
+ from mdit_py_plugins.deflist import deflist_plugin
18
+ from mdit_py_plugins.dollarmath import dollarmath_plugin
19
+ from mdit_py_plugins.footnote import footnote_plugin
20
+ from mdit_py_plugins.tasklists import tasklists_plugin
21
+
22
+ from .oxml import (
23
+ cell_borders,
24
+ make_decimal_numbering,
25
+ para_border,
26
+ repeat_header,
27
+ set_font,
28
+ set_numpr,
29
+ shade_cell,
30
+ shade_run,
31
+ table_fullwidth,
32
+ )
33
+ from .theme import Theme
34
+
35
+ BULLET_STYLES = {0: "List Bullet", 1: "List Bullet 2", 2: "List Bullet 3"}
36
+
37
+
38
+ def build_parser() -> MarkdownIt:
39
+ md = MarkdownIt("commonmark", {"linkify": True}).enable(
40
+ ["table", "strikethrough", "linkify"])
41
+ return (md.use(tasklists_plugin).use(footnote_plugin)
42
+ .use(deflist_plugin).use(dollarmath_plugin))
43
+
44
+
45
+ def plain_text(inline_token) -> str:
46
+ out = []
47
+ for c in inline_token.children or []:
48
+ if c.type in ("text", "text_special", "code_inline"):
49
+ out.append(c.content)
50
+ elif c.type == "softbreak":
51
+ out.append(" ")
52
+ elif c.children:
53
+ out.append(plain_text(c))
54
+ return "".join(out)
55
+
56
+
57
+ class Renderer:
58
+ def __init__(self, doc: Document, theme: Theme, base_dir: Path | None = None):
59
+ self.doc = doc
60
+ self.theme = theme
61
+ self.base_dir = base_dir
62
+ self.quote_depth = 0
63
+ self.bullet_depth = 0
64
+ self.ordered_stack: list[int] = []
65
+ self.first_h1_pending = False
66
+ self._dt_depth = 0
67
+ self._dd_depth = 0
68
+ self._footnote_no = 0
69
+
70
+ # ---- 标题 -------------------------------------------------------
71
+ def heading(self, level: int, inline_tok, page_break=False):
72
+ p = self.doc.add_paragraph(style=f"Heading {level}")
73
+ if page_break:
74
+ p.paragraph_format.page_break_before = True
75
+ size = self.theme.heading_sizes[min(level - 1, len(self.theme.heading_sizes) - 1)]
76
+ if level <= 2:
77
+ color = self.theme.color_brand
78
+ elif level == 3:
79
+ color = self.theme.color_dark
80
+ else:
81
+ color = self.theme.color_gray
82
+ self.render_inline(inline_tok.children, p, size=size, bold=True,
83
+ color=color, east=self.theme.font_head_east,
84
+ latin=self.theme.font_head_latin)
85
+ return p
86
+
87
+ # ---- 段落 -------------------------------------------------------
88
+ def paragraph(self, children, *, bullet=False, ordered=None):
89
+ if bullet:
90
+ style = BULLET_STYLES.get(min(self.bullet_depth, 2), "List Bullet 3")
91
+ p = self.doc.add_paragraph(style=style)
92
+ elif ordered is not None:
93
+ p = self.doc.add_paragraph(style="Normal")
94
+ if ordered:
95
+ set_numpr(p, ordered, ilvl=min(max(len(self.ordered_stack) - 1, 0), 2))
96
+ else:
97
+ p = self.doc.add_paragraph(style="Normal")
98
+ if self.quote_depth:
99
+ p.paragraph_format.left_indent = Cm(0.6 + 0.5 * self.quote_depth)
100
+ p.paragraph_format.right_indent = Cm(0.4)
101
+ para_border(p, "left", "B9C6E8", "18")
102
+ self.render_inline(children, p)
103
+ return p
104
+
105
+ # ---- 行内 -------------------------------------------------------
106
+ def render_inline(self, tokens, p, *, size=None, bold=None, color=None,
107
+ east=None, latin=None):
108
+ ctx = {"bold": bool(bold), "italic": False, "strike": False,
109
+ "size": size or self.theme.body_size, "color": color,
110
+ "east": east or self.theme.font_body_east,
111
+ "latin": latin or self.theme.font_body_latin}
112
+ self._walk(tokens, p, ctx)
113
+
114
+ def _walk(self, tokens, p, ctx):
115
+ i = 0
116
+ while i < len(tokens):
117
+ tok = tokens[i]
118
+ t = tok.type
119
+ if t in ("text", "text_special"):
120
+ text = tok.content
121
+ text = re.sub(r"^\[ \] ", "☐ ", text)
122
+ text = re.sub(r"^\[[xX]\] ", "☑ ", text)
123
+ if not text:
124
+ i += 1
125
+ continue
126
+ run = p.add_run(text)
127
+ set_font(run, latin=ctx["latin"], east=ctx["east"], size=ctx["size"],
128
+ bold=ctx["bold"], italic=ctx["italic"], strike=ctx["strike"],
129
+ color=ctx["color"])
130
+ elif t == "code_inline":
131
+ run = p.add_run(tok.content)
132
+ set_font(run, latin=self.theme.font_code_latin, east=self.theme.font_code_east,
133
+ size=max(ctx["size"] - 1, 8), color=self.theme.color_code_text)
134
+ shade_run(run, "EEF1F8")
135
+ elif t == "strong_open":
136
+ ctx["bold"] = True
137
+ elif t == "strong_close":
138
+ ctx["bold"] = False
139
+ elif t == "em_open":
140
+ ctx["italic"] = True
141
+ elif t == "em_close":
142
+ ctx["italic"] = False
143
+ elif t == "s_open":
144
+ ctx["strike"] = True
145
+ elif t == "s_close":
146
+ ctx["strike"] = False
147
+ elif t == "softbreak":
148
+ p.add_run(" ")
149
+ elif t == "hardbreak":
150
+ p.add_run().add_break()
151
+ elif t == "html_inline":
152
+ if re.match(r"<br\s*/?>", tok.content, re.IGNORECASE):
153
+ p.add_run().add_break()
154
+ elif "task-list-item-checkbox" in tok.content:
155
+ ch = "☑" if "checked" in tok.content else "☐"
156
+ run = p.add_run(ch)
157
+ set_font(run, latin=ctx["latin"], east=ctx["east"], size=ctx["size"])
158
+ else:
159
+ text = re.sub(r"<[^>]+>", "", tok.content)
160
+ if text:
161
+ run = p.add_run(text)
162
+ set_font(run, latin=ctx["latin"], east=ctx["east"], size=ctx["size"],
163
+ bold=ctx["bold"], italic=ctx["italic"], strike=ctx["strike"],
164
+ color=ctx["color"])
165
+ elif t == "math_inline":
166
+ run = p.add_run(tok.content)
167
+ set_font(run, latin=self.theme.font_code_latin, east=self.theme.font_code_east,
168
+ size=max(ctx["size"] - 1, 8), color=self.theme.color_code_text)
169
+ shade_run(run, "EEF1F8")
170
+ elif t == "footnote_ref":
171
+ sub_id = int((tok.meta or {}).get("subId", 0)) + 1
172
+ run = p.add_run(str(sub_id))
173
+ set_font(run, size=ctx["size"], color=ctx["color"])
174
+ run.font.superscript = True
175
+ elif t == "image":
176
+ self.embed_image(p, tok, ctx)
177
+ elif t == "link_open":
178
+ close_idx = self._find_link_close(tokens, i)
179
+ url = tok.attrGet("href") or ""
180
+ self.add_hyperlink(p, url, tokens[i + 1:close_idx], ctx)
181
+ i = close_idx # 跳到 link_close,外层再 +1
182
+ elif tok.children is not None:
183
+ self._walk(tok.children, p, ctx)
184
+ i += 1
185
+
186
+ @staticmethod
187
+ def _find_link_close(tokens, start):
188
+ depth = 0
189
+ for j in range(start, len(tokens)):
190
+ tt = tokens[j].type
191
+ if tt == "link_open":
192
+ depth += 1
193
+ elif tt == "link_close":
194
+ depth -= 1
195
+ if depth == 0:
196
+ return j
197
+ return len(tokens)
198
+
199
+ # ---- 超链接(真实 Word 超链接,品牌色 + 下划线)------------------
200
+ def add_hyperlink(self, p, url, inline_tokens, ctx):
201
+ r_id = p.part.relate_to(url, RT.HYPERLINK, is_external=True)
202
+ hl = OxmlElement("w:hyperlink")
203
+ hl.set(qn("r:id"), r_id)
204
+ tmp = self.doc.add_paragraph()
205
+ self.render_inline(inline_tokens, tmp, size=ctx["size"], bold=ctx["bold"],
206
+ color=self.theme.color_brand,
207
+ east=ctx["east"], latin=ctx["latin"])
208
+ runs = list(tmp.runs)
209
+ for child in list(tmp._p):
210
+ hl.append(child)
211
+ p._p.append(hl)
212
+ tmp._p.getparent().remove(tmp._p)
213
+ for run in runs:
214
+ run.font.underline = True
215
+
216
+ # ---- 图片(本地真实嵌入;远程/缺失降级占位)----------------------
217
+ def _resolve_image(self, src: str):
218
+ candidates = []
219
+ if Path(src).is_absolute():
220
+ candidates.append(Path(src))
221
+ else:
222
+ if self.base_dir is not None:
223
+ candidates.append(self.base_dir / src)
224
+ candidates.append(Path(src))
225
+ for c in candidates:
226
+ try:
227
+ if c.is_file():
228
+ return c
229
+ except OSError:
230
+ continue
231
+ return None
232
+
233
+ def embed_image(self, p, tok, ctx):
234
+ src = tok.attrGet("src") or ""
235
+ alt = plain_text(tok)
236
+
237
+ def placeholder():
238
+ run = p.add_run(f"[图: {alt}]" if alt else "[图]")
239
+ set_font(run, size=ctx["size"], color=self.theme.color_gray)
240
+
241
+ if src.startswith(("http://", "https://", "//")) or re.match(
242
+ r"^[a-zA-Z][a-zA-Z0-9+.-]*://", src):
243
+ placeholder()
244
+ return
245
+ path = self._resolve_image(src)
246
+ if path is None:
247
+ placeholder()
248
+ return
249
+ img_par = self.doc.add_paragraph()
250
+ img_par.alignment = WD_ALIGN_PARAGRAPH.CENTER
251
+ run = img_par.add_run()
252
+ try:
253
+ from docx.image.exceptions import UnrecognizedImageError
254
+
255
+ img = DocxImage.from_file(str(path))
256
+ dpi_h = img.horz_dpi or 96
257
+ width_emu = int(img.px_width / dpi_h * 914400)
258
+ sec = self.doc.sections[0]
259
+ avail = int(sec.page_width) - int(sec.left_margin) - int(sec.right_margin)
260
+ width_emu = min(width_emu, avail)
261
+ run.add_picture(str(path), width=Emu(width_emu))
262
+ except (UnrecognizedImageError, ValueError, OSError):
263
+ # 不支持的图片格式/损坏文件 → 降级为占位文字(spec §5.5)
264
+ img_par._p.getparent().remove(img_par._p)
265
+ placeholder()
266
+ return
267
+ cap_par = None
268
+ if alt:
269
+ cap_par = self.doc.add_paragraph()
270
+ cap_par.alignment = WD_ALIGN_PARAGRAPH.CENTER
271
+ set_font(cap_par.add_run(alt), size=9, color=self.theme.color_gray)
272
+ if cap_par is not None:
273
+ p._p.addnext(cap_par._p)
274
+ p._p.addnext(img_par._p)
275
+
276
+ # ---- 相邻表格分隔(Word 会把相邻 <w:tbl> 合并成一张错位表)------
277
+ def ensure_table_separator(self):
278
+ body = self.doc.element.body
279
+ for el in reversed(list(body)):
280
+ tag = el.tag.split("}")[1]
281
+ if tag == "sectPr":
282
+ continue
283
+ if tag == "tbl":
284
+ self.doc.add_paragraph()
285
+ break
286
+
287
+ # ---- 主循环 -----------------------------------------------------
288
+ def render(self, tokens):
289
+ i = 0
290
+ while i < len(tokens):
291
+ t = tokens[i]
292
+ if t.type == "heading_open":
293
+ level = int(t.tag[1])
294
+ page_break = False
295
+ if level == 1 and self.first_h1_pending:
296
+ page_break = True
297
+ self.first_h1_pending = False
298
+ self.heading(level, tokens[i + 1], page_break=page_break)
299
+ i += 3
300
+ elif t.type == "paragraph_open" and t.hidden:
301
+ if self._dt_depth:
302
+ p = self.doc.add_paragraph(style="Normal")
303
+ self.render_inline(tokens[i + 1].children, p, bold=True)
304
+ i += 2
305
+ elif self._dd_depth:
306
+ p = self.doc.add_paragraph(style="Normal")
307
+ p.paragraph_format.left_indent = Cm(0.8)
308
+ self.render_inline(tokens[i + 1].children, p)
309
+ i += 2
310
+ elif self.ordered_stack:
311
+ self.paragraph(tokens[i + 1].children,
312
+ ordered=self.ordered_stack[-1])
313
+ i += 2
314
+ else:
315
+ self.paragraph(tokens[i + 1].children, bullet=True)
316
+ i += 2
317
+ elif t.type == "paragraph_open":
318
+ self.paragraph(tokens[i + 1].children)
319
+ i += 3
320
+ elif t.type == "bullet_list_open":
321
+ self.bullet_depth += 1
322
+ i += 1
323
+ elif t.type == "bullet_list_close":
324
+ self.bullet_depth -= 1
325
+ i += 1
326
+ elif t.type == "ordered_list_open":
327
+ self.ordered_stack.append(make_decimal_numbering(self.doc))
328
+ i += 1
329
+ elif t.type == "ordered_list_close":
330
+ _ = self.ordered_stack.pop()
331
+ i += 1
332
+ elif t.type == "blockquote_open":
333
+ self.quote_depth += 1
334
+ i += 1
335
+ elif t.type == "blockquote_close":
336
+ self.quote_depth -= 1
337
+ i += 1
338
+ elif t.type == "dt_open":
339
+ self._dt_depth += 1
340
+ i += 1
341
+ elif t.type == "dt_close":
342
+ self._dt_depth -= 1
343
+ i += 1
344
+ elif t.type == "dd_open":
345
+ self._dd_depth += 1
346
+ i += 1
347
+ elif t.type == "dd_close":
348
+ self._dd_depth -= 1
349
+ i += 1
350
+ elif t.type == "footnote_block_open":
351
+ self._footnote_no = 0
352
+ p = self.doc.add_paragraph(style="Normal")
353
+ set_font(p.add_run("注释"), latin=self.theme.font_head_latin,
354
+ east=self.theme.font_head_east, size=11, bold=True,
355
+ color=self.theme.color_dark)
356
+ i += 1
357
+ elif t.type == "footnote_open":
358
+ self._footnote_no += 1
359
+ j = i + 1
360
+ inline_tok = None
361
+ while tokens[j].type != "footnote_close":
362
+ if tokens[j].type == "inline":
363
+ inline_tok = tokens[j]
364
+ j += 1
365
+ fp = self.doc.add_paragraph(style="Normal")
366
+ set_font(fp.add_run(f"{self._footnote_no}. "),
367
+ size=9, color=self.theme.color_gray)
368
+ if inline_tok is not None:
369
+ self.render_inline(inline_tok.children, fp,
370
+ size=9, color=self.theme.color_gray)
371
+ i = j
372
+ elif t.type == "math_block":
373
+ p = self.doc.add_paragraph(style="Normal")
374
+ p.alignment = WD_ALIGN_PARAGRAPH.CENTER
375
+ run = p.add_run(t.content.strip())
376
+ set_font(run, latin=self.theme.font_code_latin,
377
+ east=self.theme.font_code_east, size=9,
378
+ color=self.theme.color_code_text)
379
+ shade_run(run, "EEF1F8")
380
+ i += 1
381
+ elif t.type == "html_block":
382
+ text = re.sub(r"<[^>]+>", " ", t.content).strip()
383
+ if text:
384
+ for line in re.split(r"\n+", text):
385
+ if line.strip():
386
+ p = self.doc.add_paragraph(style="Normal")
387
+ run = p.add_run(line.strip())
388
+ set_font(run, latin=self.theme.font_body_latin,
389
+ east=self.theme.font_body_east,
390
+ size=self.theme.body_size)
391
+ i += 1
392
+ elif t.type == "fence":
393
+ self.code_block(t.content)
394
+ i += 1
395
+ elif t.type == "code_block":
396
+ self.code_block(t.content) # 缩进代码块(spec §5.4:与围栏同样承载)
397
+ i += 1
398
+ elif t.type == "table_open":
399
+ i = self.table(tokens, i) + 1
400
+ elif t.type == "inline":
401
+ p = self.doc.add_paragraph(style="Normal")
402
+ if self._dt_depth:
403
+ self.render_inline(t.children, p, bold=True)
404
+ elif self._dd_depth:
405
+ p.paragraph_format.left_indent = Cm(0.8)
406
+ self.render_inline(t.children, p)
407
+ else:
408
+ self.render_inline(t.children, p)
409
+ i += 1
410
+ elif t.type == "hr":
411
+ self.hr()
412
+ i += 1
413
+ else:
414
+ i += 1
415
+
416
+ # ---- 代码块(1×1 底纹表格承载,避免字体错位)--------------------
417
+ def code_block(self, content: str):
418
+ self.ensure_table_separator()
419
+ table = self.doc.add_table(rows=1, cols=1)
420
+ table.alignment = WD_TABLE_ALIGNMENT.CENTER
421
+ table_fullwidth(table)
422
+ cell = table.cell(0, 0)
423
+ cell_borders(cell, self.theme.color_border)
424
+ shade_cell(cell, self.theme.fill_code)
425
+ first_p = cell.paragraphs[0]
426
+ first_p._p.getparent().remove(first_p._p)
427
+ for line in content.rstrip("\n").split("\n"):
428
+ p = cell.add_paragraph()
429
+ p.paragraph_format.space_after = Pt(0)
430
+ p.paragraph_format.space_before = Pt(0)
431
+ p.paragraph_format.line_spacing = 1.15
432
+ run = p.add_run(line if line else " ")
433
+ set_font(run, latin=self.theme.font_code_latin, east=self.theme.font_code_east,
434
+ size=9, color=self.theme.color_code_text)
435
+
436
+ def table(self, tokens, start):
437
+ self.ensure_table_separator()
438
+ rows, cur_row = [], None
439
+ i = start
440
+ while tokens[i].type != "table_close":
441
+ t = tokens[i]
442
+ if t.type == "tr_open":
443
+ cur_row = []
444
+ elif t.type == "tr_close":
445
+ rows.append(cur_row)
446
+ elif t.type in ("th_open", "td_open"):
447
+ j = i + 1
448
+ while tokens[j].type not in ("th_close", "td_close"):
449
+ j += 1
450
+ cur_row.append(tokens[i + 1])
451
+ i = j
452
+ i += 1
453
+ ncols = max(len(r) for r in rows)
454
+ table = self.doc.add_table(rows=len(rows), cols=ncols)
455
+ table.alignment = WD_TABLE_ALIGNMENT.CENTER
456
+ table_fullwidth(table)
457
+ base_size = 8 if ncols >= 6 else 9
458
+ for ri, row in enumerate(rows):
459
+ if ri == 0:
460
+ repeat_header(table.rows[0])
461
+ for ci in range(ncols):
462
+ cell = table.cell(ri, ci)
463
+ cell_borders(cell, self.theme.color_border)
464
+ if ri == 0:
465
+ shade_cell(cell, self.theme.fill_head)
466
+ p = cell.paragraphs[0]
467
+ p.paragraph_format.space_before = Pt(1)
468
+ p.paragraph_format.space_after = Pt(1)
469
+ p.paragraph_format.line_spacing = 1.15
470
+ tok = row[ci] if ci < len(row) else None
471
+ if tok is not None:
472
+ self.render_inline(tok.children, p, size=base_size,
473
+ bold=True if ri == 0 else None,
474
+ color=self.theme.color_dark if ri == 0 else None)
475
+ else:
476
+ p.add_run(" ")
477
+ return i
478
+
479
+ def hr(self):
480
+ p = self.doc.add_paragraph()
481
+ para_border(p, "bottom", "D5DAE6", "6")
482
+ p.paragraph_format.space_before = Pt(6)
483
+ p.paragraph_format.space_after = Pt(6)
@@ -0,0 +1,140 @@
1
+ """内置文档主题与页面版式。取值来源:设计文档 §5.3。"""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass
5
+
6
+ from docx.shared import Cm, RGBColor
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class Theme:
11
+ name: str
12
+ font_head_latin: str
13
+ font_head_east: str
14
+ font_body_latin: str
15
+ font_body_east: str
16
+ font_code_latin: str
17
+ font_code_east: str
18
+ color_brand: RGBColor
19
+ color_dark: RGBColor
20
+ color_gray: RGBColor
21
+ color_code_text: RGBColor
22
+ fill_head: str
23
+ fill_code: str
24
+ color_border: str
25
+ body_size: float = 10.5
26
+ heading_sizes: tuple[float, ...] = (17, 14, 12, 11, 10, 10)
27
+
28
+
29
+ def _business() -> Theme:
30
+ return Theme(
31
+ name="business",
32
+ font_head_latin="微软雅黑",
33
+ font_head_east="微软雅黑",
34
+ font_body_latin="Calibri",
35
+ font_body_east="等线",
36
+ font_code_latin="Consolas",
37
+ font_code_east="等线",
38
+ color_brand=RGBColor(0x3A, 0x54, 0xD9),
39
+ color_dark=RGBColor(0x1F, 0x25, 0x33),
40
+ color_gray=RGBColor(0x5A, 0x64, 0x78),
41
+ color_code_text=RGBColor(0x2A, 0x33, 0x4C),
42
+ fill_head="EEF3FF",
43
+ fill_code="F5F7FC",
44
+ color_border="C9D3E8",
45
+ )
46
+
47
+
48
+ def _derived(name: str, *, brand: RGBColor, fill_head: str, fill_code: str,
49
+ color_border: str, fonts: dict | None = None,
50
+ body_size: float | None = None) -> Theme:
51
+ """以 business 为基线派生主题:仅替换差异项(spec §5.3 主题数值约定)。"""
52
+ b = _business()
53
+ return Theme(
54
+ name=name,
55
+ font_head_latin=(fonts or {}).get("head_latin", b.font_head_latin),
56
+ font_head_east=(fonts or {}).get("head_east", b.font_head_east),
57
+ font_body_latin=(fonts or {}).get("body_latin", b.font_body_latin),
58
+ font_body_east=(fonts or {}).get("body_east", b.font_body_east),
59
+ font_code_latin=(fonts or {}).get("code_latin", b.font_code_latin),
60
+ font_code_east=(fonts or {}).get("code_east", b.font_code_east),
61
+ color_brand=brand,
62
+ color_dark=b.color_dark,
63
+ color_gray=b.color_gray,
64
+ color_code_text=b.color_code_text,
65
+ fill_head=fill_head,
66
+ fill_code=fill_code,
67
+ color_border=color_border,
68
+ body_size=body_size if body_size is not None else b.body_size,
69
+ )
70
+
71
+
72
+ def _minimal() -> Theme:
73
+ return _derived("minimal", brand=RGBColor(0x11, 0x18, 0x27),
74
+ fill_head="F2F2F2", fill_code=_business().fill_code,
75
+ color_border="D9D9D9")
76
+
77
+
78
+ def _academic() -> Theme:
79
+ b = _business()
80
+ return _derived(
81
+ "academic",
82
+ brand=RGBColor(0x00, 0x00, 0x00),
83
+ fill_head="EFEFEF", fill_code=b.fill_code,
84
+ color_border=b.color_border, body_size=12,
85
+ fonts={"head_latin": "Times New Roman", "head_east": "黑体",
86
+ "body_latin": "Times New Roman", "body_east": "宋体",
87
+ "code_latin": "Consolas", "code_east": "宋体"})
88
+
89
+
90
+ def _forest() -> Theme:
91
+ b = _business()
92
+ return _derived("forest", brand=RGBColor(0x1E, 0x6E, 0x5C),
93
+ fill_head="E6F4EF", fill_code=b.fill_code,
94
+ color_border=b.color_border)
95
+
96
+
97
+ def _ocean() -> Theme:
98
+ return _derived("ocean", brand=RGBColor(0x0E, 0x74, 0x90),
99
+ fill_head="E0F2F7", fill_code="F0F9FB",
100
+ color_border="B7DCE8")
101
+
102
+
103
+ def _sunset() -> Theme:
104
+ return _derived("sunset", brand=RGBColor(0xC2, 0x41, 0x0C),
105
+ fill_head="FEF0E6", fill_code="FFF7F0",
106
+ color_border="F2D4BC")
107
+
108
+
109
+ def _violet() -> Theme:
110
+ return _derived("violet", brand=RGBColor(0x6D, 0x28, 0xD9),
111
+ fill_head="F1EBFE", fill_code="F7F4FE",
112
+ color_border="DACCF6")
113
+
114
+
115
+ def _plum() -> Theme:
116
+ return _derived("plum", brand=RGBColor(0x9D, 0x17, 0x4D),
117
+ fill_head="FCE9F1", fill_code="FDF4F8",
118
+ color_border="F1CBDD")
119
+
120
+
121
+ THEMES: dict[str, Theme] = {
122
+ "business": _business(),
123
+ "minimal": _minimal(),
124
+ "academic": _academic(),
125
+ "forest": _forest(),
126
+ "ocean": _ocean(),
127
+ "sunset": _sunset(),
128
+ "violet": _violet(),
129
+ "plum": _plum(),
130
+ }
131
+
132
+ # 页面版式:宽(width)×高(height)+ 四向页边距,单位 Cm
133
+ PAGE_PROFILES: dict[str, dict] = {
134
+ "a4_portrait": {"width": Cm(21), "height": Cm(29.7),
135
+ "top": Cm(2.2), "bottom": Cm(2.2), "left": Cm(2.5), "right": Cm(2.5)},
136
+ "a4_landscape": {"width": Cm(29.7), "height": Cm(21),
137
+ "top": Cm(1.5), "bottom": Cm(1.5), "left": Cm(1.6), "right": Cm(1.6)},
138
+ "widescreen": {"width": Cm(33.87), "height": Cm(19.05),
139
+ "top": Cm(1.27), "bottom": Cm(1.27), "left": Cm(1.9), "right": Cm(1.9)},
140
+ }