@christang/keel 5.190.0 → 5.192.0
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.
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +14 -4
- package/README.zh-CN.md +13 -4
- package/assets/bootstrap/AGENTS.md +1 -1
- package/bin/keel.js +7 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/plugins/keel/.claude-plugin/plugin.json +1 -1
- package/plugins/keel/.codex-plugin/plugin.json +1 -1
- package/plugins/keel/skills/keel-md-docx/SKILL.md +51 -0
- package/plugins/keel/skills/keel-md-docx/scripts/fonts-macos.conf +10 -0
- package/plugins/keel/skills/keel-md-docx/scripts/md2word.py +359 -0
- package/plugins/keel/skills/keel-md-docx/scripts/package.json +8 -0
- package/plugins/keel/skills/keel-md-docx/scripts/requirements.txt +3 -0
- package/plugins/keel/skills/keel-md-docx/scripts/runtime.mjs +31 -0
- package/scripts/validation/baseline.py +2 -0
- package/scripts/validation/common.py +2 -2
- package/scripts/validation/export.py +449 -0
- package/scripts/validation/hosts.py +1 -0
- package/scripts/validation/registry.py +7 -0
- package/scripts/validation/shift.py +72 -0
- package/src/core/config.js +17 -4
- package/src/core/docx.js +211 -0
- package/src/core/patrol.js +12 -6
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "keel",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.192.0",
|
|
4
4
|
"description": "Keel OpenSpec execution discipline: stateless continuity, task capsules, deterministic gates, and expectation alignment for Codex and Claude Code.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "TanglmChris",
|
package/README.md
CHANGED
|
@@ -508,8 +508,9 @@ the judgement a weak executor gets most wrong, and it would be answering it abou
|
|
|
508
508
|
|
|
509
509
|
One skill carries a guidance file today: `keel-tdd-or-test-first`, a table that picks a Verify
|
|
510
510
|
strategy by what would make the Acceptance false, with right and wrong choices and when each evidence
|
|
511
|
-
form pays (#389).
|
|
512
|
-
that has to stay
|
|
511
|
+
form pays (#389). Four of the others are almost entirely criteria, so splitting them would move the
|
|
512
|
+
half that has to stay; the fifth, `keel-md-docx`, is a short export procedure loaded only when you ask
|
|
513
|
+
to turn Markdown with SVG into Word (#405).
|
|
513
514
|
|
|
514
515
|
## How the agent uses these
|
|
515
516
|
|
|
@@ -905,11 +906,16 @@ Keel's own messages never count as waiting.
|
|
|
905
906
|
|
|
906
907
|
With `--issues`, patrol also routes issue updates (#242): `issue_roles:` in `keel/config.yaml`
|
|
907
908
|
maps a label to a role, and each role gets one direct message per update of an issue carrying its
|
|
908
|
-
label — so a handoff labelled `role:verify` reaches `verify` without a second message.
|
|
909
|
+
label — so a handoff labelled `role:verify` reaches `verify` without a second message. A key may
|
|
910
|
+
name a set of labels joined by ` + ` (#433), which matches an issue carrying all of them, so teams of
|
|
911
|
+
the same shape can share capability labels. When one matching route's labels are a subset of
|
|
912
|
+
another's, only the larger set's role is sent the update; a quoted key stays one label.
|
|
909
913
|
|
|
910
914
|
```yaml
|
|
911
915
|
issue_roles:
|
|
912
916
|
role:verify: verify
|
|
917
|
+
design: design-iecc
|
|
918
|
+
design + dmc_rmw: design-rmw
|
|
913
919
|
```
|
|
914
920
|
|
|
915
921
|
A host schedule made inside a session ends with that session, so a shift change or restart drops
|
|
@@ -999,6 +1005,10 @@ keel tick [--json] | keel tick task # one step; print the launchd
|
|
|
999
1005
|
keel agents [name] [--json]
|
|
1000
1006
|
keel agents brief <name> --mode helper|implementation --dir <path> --out <file>
|
|
1001
1007
|
|
|
1008
|
+
# Markdown with SVG to Word, on request (packages installed only with --yes, into ~/.keel/docx)
|
|
1009
|
+
keel docx setup [--yes]
|
|
1010
|
+
keel docx convert <input.md> [-o <output.docx>] [--template <template.docx>] [--replace] # an existing output is kept without --replace
|
|
1011
|
+
|
|
1002
1012
|
# Install / maintenance
|
|
1003
1013
|
keel --init [--target <t>] [--dry-run] [--force-template-update]
|
|
1004
1014
|
keel --install [--target <t>] [--dry-run] [--force-template-update] [--with-git-hooks]
|
|
@@ -1013,7 +1023,7 @@ keel openspec <args>
|
|
|
1013
1023
|
|
|
1014
1024
|
Commands take the repository as a positional path or as `--repo <path>`; `keel --help` shows which.
|
|
1015
1025
|
Each group prints its full subcommand list: `keel chat help`, `keel mail help`, `keel shift --help`,
|
|
1016
|
-
`keel lock --help`, `keel patrol --help`, and `keel
|
|
1026
|
+
`keel lock --help`, `keel patrol --help`, `keel agents --help`, and `keel docx --help`.
|
|
1017
1027
|
|
|
1018
1028
|
Exit codes: `0` pass · `1` input error · `2` usage error (an unknown flag or a flag the command refuses) · `3` policy failure · `4` missing semantic review. `keel patrol` uses `2` and `3` for what it found; see Coordinator patrol.
|
|
1019
1029
|
|
package/README.zh-CN.md
CHANGED
|
@@ -411,8 +411,9 @@ executor_tier: high
|
|
|
411
411
|
而它回答的还是关于它自己的问题。
|
|
412
412
|
|
|
413
413
|
目前只有一个技能带指导文件:`keel-tdd-or-test-first`,一张按"什么会让 Acceptance 不成立"来挑选 Verify 策略的
|
|
414
|
-
表,附带正确和错误的选择,以及每种证据形式何时划算(#389
|
|
415
|
-
|
|
414
|
+
表,附带正确和错误的选择,以及每种证据形式何时划算(#389)。其余技能中有四个几乎全是准则,拆开它们只会把必须
|
|
415
|
+
留下的那一半挪走;第五个 `keel-md-docx` 是一段简短的导出流程,只在你要求把含 SVG 的 Markdown 转成 Word 时
|
|
416
|
+
才加载(#405)。
|
|
416
417
|
|
|
417
418
|
## 这些命令,agent 是怎么用起来的
|
|
418
419
|
|
|
@@ -751,11 +752,15 @@ keel patrol --issues /tmp/issues.json # 以协调者的角色运行
|
|
|
751
752
|
|
|
752
753
|
带上 `--issues` 时,巡查还会分派 issue 更新(#242):`keel/config.yaml` 里的 `issue_roles:` 把一个标签映射到
|
|
753
754
|
一个角色,每个角色会为带着它标签的 issue 的每次更新收到一条私信——这样一个标为 `role:verify` 的交接无需第二条
|
|
754
|
-
消息就能到达 `verify
|
|
755
|
+
消息就能到达 `verify`。一个键也可以是用 ` + ` 连起来的一组标签(#433),只匹配同时带着这些标签的 issue,这样
|
|
756
|
+
结构相同的几个团队就能共用能力标签。当一条匹配路由的标签是另一条的子集时,只有标签更多的那条的角色收到更新;
|
|
757
|
+
加了引号的键仍是单个标签。
|
|
755
758
|
|
|
756
759
|
```yaml
|
|
757
760
|
issue_roles:
|
|
758
761
|
role:verify: verify
|
|
762
|
+
design: design-iecc
|
|
763
|
+
design + dmc_rmw: design-rmw
|
|
759
764
|
```
|
|
760
765
|
|
|
761
766
|
在会话内创建的宿主计划任务会随该会话结束,所以换班或重启就会丢掉它。声明由哪个角色巡查、多久一次,那个角色的
|
|
@@ -841,6 +846,10 @@ keel tick [--json] | keel tick task # 执行一步;打印 launc
|
|
|
841
846
|
keel agents [name] [--json]
|
|
842
847
|
keel agents brief <name> --mode helper|implementation --dir <path> --out <file>
|
|
843
848
|
|
|
849
|
+
# 含 SVG 的 Markdown 导出 Word,按需使用(依赖只在加 --yes 时安装,装到 ~/.keel/docx)
|
|
850
|
+
keel docx setup [--yes]
|
|
851
|
+
keel docx convert <input.md> [-o <output.docx>] [--template <template.docx>] [--replace] # 输出已存在时不加 --replace 就保留原文件
|
|
852
|
+
|
|
844
853
|
# 安装 / 维护
|
|
845
854
|
keel --init [--target <t>] [--dry-run] [--force-template-update]
|
|
846
855
|
keel --install [--target <t>] [--dry-run] [--force-template-update] [--with-git-hooks]
|
|
@@ -855,7 +864,7 @@ keel openspec <args>
|
|
|
855
864
|
|
|
856
865
|
命令接受仓库路径,可以是位置参数,也可以是 `--repo <path>`;具体用哪种见 `keel --help`。
|
|
857
866
|
每组命令都会打印自己的完整子命令列表:`keel chat help`、`keel mail help`、`keel shift --help`、
|
|
858
|
-
`keel lock --help`、`keel patrol --help` 和 `keel
|
|
867
|
+
`keel lock --help`、`keel patrol --help`、`keel agents --help` 和 `keel docx --help`。
|
|
859
868
|
|
|
860
869
|
退出码:`0` 通过 · `1` 输入错误 · `2` 用法错误(未知 flag,或命令拒绝的 flag) · `3` 策略失败 · `4` 缺少语义 review。`keel patrol` 用 `2` 和 `3` 表示它发现了什么;见「协调者巡查」。
|
|
861
870
|
|
package/bin/keel.js
CHANGED
|
@@ -52,6 +52,7 @@ const KEEL_SKILLS = [
|
|
|
52
52
|
"keel-align-expectations",
|
|
53
53
|
"keel-debug-failure",
|
|
54
54
|
"keel-handoff",
|
|
55
|
+
"keel-md-docx",
|
|
55
56
|
"keel-review-checklist",
|
|
56
57
|
"keel-tdd-or-test-first",
|
|
57
58
|
];
|
|
@@ -96,6 +97,8 @@ Usage:
|
|
|
96
97
|
keel mail role|send|list|read|hook [repo] ... (cross-host mailbox; see keel mail help)
|
|
97
98
|
keel triage [repo] [--labels <l1,l2>] [--issue <n>] [--json]
|
|
98
99
|
keel agents [name] [--repo path] [--json] (external model CLIs, read on demand; Keel launches none)
|
|
100
|
+
keel docx setup [--yes] (Markdown with SVG to Word: list its packages; --yes installs them into ~/.keel/docx)
|
|
101
|
+
keel docx convert <input.md> [-o <output.docx>] [--template <template.docx>] [--replace] (an existing output is kept without --replace)
|
|
99
102
|
keel shift request|check|ready|start|resume|status ... (a role's shift change; see keel shift --help)
|
|
100
103
|
keel lock acquire|release|list ... (shared resource leases; see keel lock --help)
|
|
101
104
|
keel worktrees [--repo <path>] [--issues <file>] [--json] (read-only worktree overview)
|
|
@@ -3203,6 +3206,10 @@ function main() {
|
|
|
3203
3206
|
if (process.argv[2] === "agents") {
|
|
3204
3207
|
return require("../src/core/agents").runAgents(process.argv.slice(3));
|
|
3205
3208
|
}
|
|
3209
|
+
// `keel docx` likewise: Markdown with SVG to Word, on request (#405).
|
|
3210
|
+
if (process.argv[2] === "docx") {
|
|
3211
|
+
return require("../src/core/docx").runDocx(process.argv.slice(3));
|
|
3212
|
+
}
|
|
3206
3213
|
const options = parseArgs(process.argv.slice(2));
|
|
3207
3214
|
if (options.adopt && options.action !== "update") {
|
|
3208
3215
|
fail("--adopt only applies to --update");
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@christang/keel",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.192.0",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@christang/keel",
|
|
9
|
-
"version": "5.
|
|
9
|
+
"version": "5.192.0",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@fission-ai/openspec": "^1.4.1"
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "keel",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.192.0",
|
|
4
4
|
"description": "Keel OpenSpec execution discipline: stateless continuity, task capsules, deterministic gates, and expectation alignment for Codex and Claude Code.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "TanglmChris",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "keel",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.192.0",
|
|
4
4
|
"description": "Keel OpenSpec execution discipline: stateless continuity, task capsules, deterministic gates, and expectation alignment for Codex and Claude Code.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "TanglmChris",
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: keel-md-docx
|
|
3
|
+
description: Export a local Markdown file that contains SVG diagrams to one Word (.docx) document, keeping the SVG as vector images with PNG fallbacks. Use when the user asks to export, convert, or deliver Markdown with SVG as Word or .docx. Do not use for other document formats, for Markdown without a Word request, or for editing an existing Word file.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# keel-md-docx
|
|
7
|
+
|
|
8
|
+
## Purpose
|
|
9
|
+
|
|
10
|
+
Turn one local Markdown file into one `.docx`: headings, paragraphs, inline formatting, lists, quotes, code blocks, and tables stay editable; every SVG becomes a vector image with an embedded PNG fallback, scaled to fit the page; every image ends up inside the document. The converter is `scripts/md2word.py` with the helper `scripts/runtime.mjs`, run by `keel docx convert` in an environment Keel manages. Nothing here runs unless the user asks for this export.
|
|
11
|
+
|
|
12
|
+
## Steps
|
|
13
|
+
|
|
14
|
+
1. **Check the environment.** Run `keel docx setup`. Without `--yes` it installs nothing: it prints each package, its licence and size, and where the environment would go (`~/.keel/docx/`, or `$KEEL_HOME/docx/`). If it reports the environment ready, go to step 3.
|
|
15
|
+
2. **Ask before installing.** Show the user that list in plain terms and ask whether to install. Only after they agree, run `keel docx setup --yes`. It installs into the Keel-managed environment, never into system Python or Node, and downloads no fonts or runtimes. If the user declines, stop and say the export needs it.
|
|
16
|
+
3. **State the output path.** Tell the user where the document will be written: by default the input's name with `.docx`, or the path they gave. If a file is already there, ask whether to replace it; `keel docx convert` refuses an existing output unless `--replace` is given.
|
|
17
|
+
4. **Convert.** Run `keel docx convert <input.md> [-o <output.docx>] [--template <template.docx>] [--replace]`. A template contributes its styles, headers, and page settings; its body is discarded.
|
|
18
|
+
5. **Report the result.** Relay the output path and image count on success, and every `Warning:` line. On failure relay the `Conversion failed:` reason; the previous output, if any, is untouched.
|
|
19
|
+
|
|
20
|
+
## What converts
|
|
21
|
+
|
|
22
|
+
- A standalone `<svg>…</svg>` block, a fenced code block labelled `svg`, and image references to local `.svg` files, resolved relative to the Markdown file. SVG inside ordinary code stays code.
|
|
23
|
+
- Local raster images (PNG, JPEG) and `data:` URIs.
|
|
24
|
+
- Headings, paragraphs, bold, italic, strikethrough, links, lists, quotes, code blocks, and tables.
|
|
25
|
+
|
|
26
|
+
## Limits
|
|
27
|
+
|
|
28
|
+
- An SVG stays an image; it is not split into editable Word shapes.
|
|
29
|
+
- `foreignObject`, scripts, external fonts, external images, and external stylesheets inside an SVG fail the conversion with the reason; use SVG `text` and `path`, and embed bitmaps as `data:` URIs.
|
|
30
|
+
- A remote image fails the conversion: save it locally first. Nothing is downloaded during conversion.
|
|
31
|
+
- Mermaid, math, footnotes, a table of contents, internal bookmark links, and HTML/CSS page layout are not converted. Lists use explicit numbers and bullets, not Word numbering. A tall diagram is scaled down rather than split across pages; a wide table may need a template or a landscape page.
|
|
32
|
+
- Inline HTML styling is dropped with a warning; an unsupported Markdown block stops the conversion.
|
|
33
|
+
- The default page is A4 with 2 cm margins, Arial with Heiti SC for Chinese. On macOS Keel points the SVG renderer at the system font folders for this process only; on other systems install the fonts the document needs or supply a template.
|
|
34
|
+
|
|
35
|
+
## Dependencies
|
|
36
|
+
|
|
37
|
+
Installed only by `keel docx setup --yes`, into `~/.keel/docx/` (`python/` is a virtual environment, `node/` holds the npm packages). Sizes are from the registries on 2026-10-21 for macOS arm64, not measured from an install.
|
|
38
|
+
|
|
39
|
+
| Package | Version | Licence | Size |
|
|
40
|
+
| --- | --- | --- | --- |
|
|
41
|
+
| python-docx | `>=1.1,<2` (1.2.0) | MIT | 0.25 MB wheel |
|
|
42
|
+
| lxml | `>=5,<7` (6.0.2) | BSD-3-Clause | 8.6 MB wheel |
|
|
43
|
+
| Pillow | `>=10,<13` (12.0.0) | MIT-CMU | 4.65 MB wheel |
|
|
44
|
+
| marked | 17.0.5 | MIT | 0.44 MB |
|
|
45
|
+
| sharp | 0.35.5 | Apache-2.0 | 0.96 MB, plus its platform binary (0.29 MB, Apache-2.0) and libvips 1.3.4 (18.2 MB, LGPL-3.0-or-later) |
|
|
46
|
+
|
|
47
|
+
The version lists are `scripts/requirements.txt` and `scripts/package.json`. Python 3.10 or newer and the Node that runs `keel` are used.
|
|
48
|
+
|
|
49
|
+
## Verification status
|
|
50
|
+
|
|
51
|
+
As of the release that added this skill (#405), the setup plan, the consent flow, the refusals, and the hand-off to the converter are tested with stand-in installers. The real conversion, every failure case against real SVG, and the page-by-page rendering of a Chinese mixed-text example are **unverified** in Keel: the converter was verified as the #405 prototype on macOS arm64 only (Python 3.12, marked 17.0.5, sharp 0.35.5), outside Keel. Linux, Windows, Codex, and Microsoft Word itself are unverified.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
<?xml version="1.0"?>
|
|
2
|
+
<!DOCTYPE fontconfig SYSTEM "urn:fontconfig:fonts.dtd">
|
|
3
|
+
<fontconfig>
|
|
4
|
+
<!-- Only used by this process; makes macOS CJK fonts visible to libvips/LO. -->
|
|
5
|
+
<dir>/System/Library/Fonts</dir>
|
|
6
|
+
<dir>/System/Library/Fonts/Supplemental</dir>
|
|
7
|
+
<dir>/Library/Fonts</dir>
|
|
8
|
+
<cachedir prefix="xdg">fontconfig</cachedir>
|
|
9
|
+
<alias><family>sans-serif</family><prefer><family>Arial</family><family>Heiti SC</family></prefer></alias>
|
|
10
|
+
</fontconfig>
|
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Convert Markdown and embedded SVG to DOCX, with SVG + PNG fallback images.
|
|
3
|
+
|
|
4
|
+
Usage: python md2word.py input.md -o output.docx
|
|
5
|
+
Dependencies: python-docx, lxml, Pillow; Node.js with marked and sharp.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import base64
|
|
11
|
+
import io
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
import re
|
|
16
|
+
import shutil
|
|
17
|
+
import subprocess
|
|
18
|
+
import sys
|
|
19
|
+
import tempfile
|
|
20
|
+
from urllib.parse import unquote, urlsplit
|
|
21
|
+
|
|
22
|
+
from docx import Document
|
|
23
|
+
from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT
|
|
24
|
+
from docx.enum.text import WD_ALIGN_PARAGRAPH
|
|
25
|
+
from docx.oxml import OxmlElement
|
|
26
|
+
from docx.oxml.ns import qn
|
|
27
|
+
from docx.opc.constants import RELATIONSHIP_TYPE as RT
|
|
28
|
+
from docx.opc.packuri import PackURI
|
|
29
|
+
from docx.opc.part import Part
|
|
30
|
+
from docx.shared import Cm, Pt, RGBColor
|
|
31
|
+
from lxml import etree, html
|
|
32
|
+
from PIL import Image
|
|
33
|
+
|
|
34
|
+
HERE = Path(__file__).resolve().parent
|
|
35
|
+
SVG_NS = 'http://www.w3.org/2000/svg'
|
|
36
|
+
ASVG_NS = 'http://schemas.microsoft.com/office/drawing/2016/SVG/main'
|
|
37
|
+
SVG_PATTERN = re.compile(r'<svg\b[\s\S]*?</svg\s*>', re.IGNORECASE)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def node_call(payload: dict) -> object:
|
|
41
|
+
node = os.environ.get('MD2WORD_NODE') or shutil.which('node')
|
|
42
|
+
if not node:
|
|
43
|
+
raise ValueError('Node.js not found; install Node.js or set MD2WORD_NODE.')
|
|
44
|
+
result = subprocess.run([node, str(HERE / 'runtime.mjs')],
|
|
45
|
+
input=json.dumps(payload), text=True, capture_output=True,
|
|
46
|
+
timeout=90, check=False)
|
|
47
|
+
if result.returncode:
|
|
48
|
+
raise ValueError(result.stderr.strip() or 'Markdown/SVG helper failed')
|
|
49
|
+
return json.loads(result.stdout)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class Converter:
|
|
53
|
+
def __init__(self, source: Path, template: Path | None = None):
|
|
54
|
+
self.source = source
|
|
55
|
+
self.doc = Document(str(template)) if template else Document()
|
|
56
|
+
if template:
|
|
57
|
+
# Keep styles, headers and section settings; discard template body.
|
|
58
|
+
body = self.doc._element.body
|
|
59
|
+
for child in list(body):
|
|
60
|
+
if child.tag != qn('w:sectPr'):
|
|
61
|
+
body.remove(child)
|
|
62
|
+
else:
|
|
63
|
+
section = self.doc.sections[0]
|
|
64
|
+
section.page_width, section.page_height = Cm(21), Cm(29.7)
|
|
65
|
+
section.top_margin = section.bottom_margin = Cm(2)
|
|
66
|
+
section.left_margin = section.right_margin = Cm(2)
|
|
67
|
+
for name in ['Normal', 'Title', 'Heading 1', 'Heading 2', 'Heading 3',
|
|
68
|
+
'Heading 4', 'Heading 5', 'Heading 6', 'List Bullet', 'List Number']:
|
|
69
|
+
style = self.doc.styles[name]
|
|
70
|
+
style.font.name = 'Arial'
|
|
71
|
+
style.font.color.rgb = RGBColor(0, 0, 0)
|
|
72
|
+
rpr = style.element.get_or_add_rPr()
|
|
73
|
+
fonts = rpr.find(qn('w:rFonts'))
|
|
74
|
+
if fonts is None:
|
|
75
|
+
fonts = OxmlElement('w:rFonts'); rpr.append(fonts)
|
|
76
|
+
fonts.set(qn('w:eastAsia'), 'Heiti SC')
|
|
77
|
+
normal = self.doc.styles['Normal']
|
|
78
|
+
normal.font.size = Pt(11)
|
|
79
|
+
normal.paragraph_format.space_after = Pt(6)
|
|
80
|
+
normal.paragraph_format.line_spacing = 1.15
|
|
81
|
+
self.images = 0
|
|
82
|
+
self.warnings: list[str] = []
|
|
83
|
+
self.temp = tempfile.TemporaryDirectory(prefix='md2word-')
|
|
84
|
+
|
|
85
|
+
@property
|
|
86
|
+
def usable_size(self):
|
|
87
|
+
s = self.doc.sections[-1]
|
|
88
|
+
return (s.page_width - s.left_margin - s.right_margin,
|
|
89
|
+
s.page_height - s.top_margin - s.bottom_margin - Cm(1))
|
|
90
|
+
|
|
91
|
+
def local_image(self, href: str) -> tuple[bytes, str]:
|
|
92
|
+
if href.startswith('data:'):
|
|
93
|
+
header, payload = href.split(',', 1)
|
|
94
|
+
data = base64.b64decode(payload, validate=True) if ';base64' in header else unquote(payload).encode()
|
|
95
|
+
return data, 'svg' if 'image/svg+xml' in header else 'raster'
|
|
96
|
+
split = urlsplit(href)
|
|
97
|
+
if split.scheme or split.netloc:
|
|
98
|
+
raise ValueError(f'Remote image is unsupported; save it locally first: {href}')
|
|
99
|
+
target = (self.source.parent / unquote(split.path)).resolve()
|
|
100
|
+
return target.read_bytes(), 'svg' if target.suffix.lower() == '.svg' else 'raster'
|
|
101
|
+
|
|
102
|
+
def image(self, data: bytes, kind: str, parent=None, alt=''):
|
|
103
|
+
svg = None
|
|
104
|
+
if kind == 'svg':
|
|
105
|
+
parser = etree.XMLParser(resolve_entities=False, no_network=True)
|
|
106
|
+
root = etree.fromstring(data, parser)
|
|
107
|
+
if etree.QName(root).localname != 'svg':
|
|
108
|
+
raise ValueError('Expected an SVG root element')
|
|
109
|
+
if root.getroottree().docinfo.doctype:
|
|
110
|
+
raise ValueError('SVG DOCTYPE is unsupported')
|
|
111
|
+
# A self-contained SVG makes the resulting DOCX portable.
|
|
112
|
+
for element in root.iter():
|
|
113
|
+
if not isinstance(element.tag, str):
|
|
114
|
+
continue
|
|
115
|
+
tag = etree.QName(element).localname.lower()
|
|
116
|
+
if tag in {'script', 'foreignObject'.lower()}:
|
|
117
|
+
raise ValueError(f'SVG {tag} is unsupported; use SVG text/path labels.')
|
|
118
|
+
for key, value in element.attrib.items():
|
|
119
|
+
if etree.QName(key).localname.lower() in {'href', 'src'}:
|
|
120
|
+
if not value.startswith(('#', 'data:')):
|
|
121
|
+
raise ValueError('SVG external resource found; embed it as a data URI first.')
|
|
122
|
+
text = data.decode('utf-8-sig')
|
|
123
|
+
urls = re.findall(r'url\(\s*([^)]*)\)', text, re.IGNORECASE)
|
|
124
|
+
if re.search(r'@import', text, re.IGNORECASE) or any(
|
|
125
|
+
not value.strip().strip('\"\'').strip().startswith(('#', 'data:')) for value in urls
|
|
126
|
+
):
|
|
127
|
+
raise ValueError('SVG external CSS/resource is unsupported')
|
|
128
|
+
if not root.tag.startswith('{'):
|
|
129
|
+
root.set('xmlns', SVG_NS)
|
|
130
|
+
svg = etree.tostring(root, encoding='utf-8')
|
|
131
|
+
target = Path(self.temp.name) / f'image-{self.images}.png'
|
|
132
|
+
node_call({'action': 'svg', 'svg': svg.decode(), 'output': str(target)})
|
|
133
|
+
data = target.read_bytes()
|
|
134
|
+
with Image.open(io.BytesIO(data)) as picture:
|
|
135
|
+
width, height = picture.size
|
|
136
|
+
max_width, max_height = self.usable_size
|
|
137
|
+
# Respect the source aspect ratio and avoid diagrams taller than a page.
|
|
138
|
+
scale = min(max_width / width, max_height / height, 9525)
|
|
139
|
+
p = parent if parent is not None else self.doc.add_paragraph()
|
|
140
|
+
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
|
141
|
+
shape = p.add_run().add_picture(io.BytesIO(data), width=int(width * scale), height=int(height * scale))
|
|
142
|
+
shape._inline.docPr.set('descr', alt or f'Figure {self.images + 1}')
|
|
143
|
+
if svg is not None:
|
|
144
|
+
existing = {str(part.partname) for part in self.doc.part.package.iter_parts()}
|
|
145
|
+
index = 1
|
|
146
|
+
while f'/word/media/vector{index}.svg' in existing:
|
|
147
|
+
index += 1
|
|
148
|
+
part = Part(PackURI(f'/word/media/vector{index}.svg'), 'image/svg+xml', svg, self.doc.part.package)
|
|
149
|
+
rid = self.doc.part.relate_to(part, RT.IMAGE)
|
|
150
|
+
blip = shape._inline.xpath('.//a:blip')[0]
|
|
151
|
+
ext_list = OxmlElement('a:extLst')
|
|
152
|
+
ext = OxmlElement('a:ext')
|
|
153
|
+
ext.set('uri', '{96DAC541-7B7A-43D3-8B79-37D633B846F1}')
|
|
154
|
+
vector = etree.SubElement(ext, f'{{{ASVG_NS}}}svgBlip', nsmap={'asvg': ASVG_NS})
|
|
155
|
+
vector.set(qn('r:embed'), rid)
|
|
156
|
+
ext_list.append(ext); blip.append(ext_list)
|
|
157
|
+
self.images += 1
|
|
158
|
+
|
|
159
|
+
def inline(self, p, tokens: list[dict], bold=False, italic=False, strike=False, link=None):
|
|
160
|
+
for token in tokens:
|
|
161
|
+
kind = token['type']
|
|
162
|
+
if kind in {'strong', 'em', 'del'}:
|
|
163
|
+
self.inline(p, token.get('tokens', []), bold or kind == 'strong',
|
|
164
|
+
italic or kind == 'em', strike or kind == 'del', link)
|
|
165
|
+
elif kind == 'link':
|
|
166
|
+
self.inline(p, token.get('tokens', []), bold, italic, strike, token['href'])
|
|
167
|
+
elif kind == 'image':
|
|
168
|
+
data, image_kind = self.local_image(token['href'])
|
|
169
|
+
self.image(data, image_kind, p, token.get('text', ''))
|
|
170
|
+
elif kind == 'br':
|
|
171
|
+
p.add_run().add_break()
|
|
172
|
+
elif kind == 'html':
|
|
173
|
+
text = token.get('text', '')
|
|
174
|
+
if SVG_PATTERN.fullmatch(text.strip()):
|
|
175
|
+
self.image(text.encode(), 'svg', p)
|
|
176
|
+
elif re.match(r'<br\s*/?>', text, re.IGNORECASE):
|
|
177
|
+
p.add_run().add_break()
|
|
178
|
+
else:
|
|
179
|
+
self.warnings.append('Inline HTML styling is not preserved: ' + text[:60])
|
|
180
|
+
else:
|
|
181
|
+
text = token.get('text', token.get('raw', ''))
|
|
182
|
+
if token.get('tokens'):
|
|
183
|
+
self.inline(p, token['tokens'], bold, italic, strike, link); continue
|
|
184
|
+
run = p.add_run(html.fromstring(f'<span>{text}</span>').text_content() if '&' in text and '<' not in text else text)
|
|
185
|
+
run.bold, run.italic, run.font.strike = bold, italic, strike
|
|
186
|
+
if kind == 'codespan':
|
|
187
|
+
run.font.name = 'Consolas'; run.font.size = Pt(10)
|
|
188
|
+
if link:
|
|
189
|
+
hyperlink = OxmlElement('w:hyperlink')
|
|
190
|
+
if link.startswith('#'):
|
|
191
|
+
# Heading bookmarks are not synthesized; keep the target visible.
|
|
192
|
+
self.warnings.append(f'Internal link target not resolved: {link}')
|
|
193
|
+
else:
|
|
194
|
+
hyperlink.set(qn('r:id'), self.doc.part.relate_to(link, RT.HYPERLINK, is_external=True))
|
|
195
|
+
p._p.remove(run._r); hyperlink.append(run._r); p._p.append(hyperlink)
|
|
196
|
+
|
|
197
|
+
def raw_html(self, value: str):
|
|
198
|
+
if re.search(r'<svg\b', value, re.IGNORECASE) and not SVG_PATTERN.search(value):
|
|
199
|
+
raise ValueError('Unclosed SVG element')
|
|
200
|
+
cursor = 0
|
|
201
|
+
for match in SVG_PATTERN.finditer(value):
|
|
202
|
+
self.html_fragment(value[cursor:match.start()])
|
|
203
|
+
self.image(match.group().encode(), 'svg')
|
|
204
|
+
cursor = match.end()
|
|
205
|
+
self.html_fragment(value[cursor:])
|
|
206
|
+
|
|
207
|
+
def html_fragment(self, value: str):
|
|
208
|
+
if not value.strip():
|
|
209
|
+
return
|
|
210
|
+
try:
|
|
211
|
+
root = html.fragment_fromstring(value, create_parent='div')
|
|
212
|
+
except etree.ParserError:
|
|
213
|
+
return
|
|
214
|
+
for img in root.xpath('.//img'):
|
|
215
|
+
data, kind = self.local_image(img.get('src', ''))
|
|
216
|
+
self.image(data, kind, alt=img.get('alt', ''))
|
|
217
|
+
text = root.text_content().strip()
|
|
218
|
+
if text:
|
|
219
|
+
self.doc.add_paragraph(text)
|
|
220
|
+
self.warnings.append('HTML block preserved as plain text; use Markdown for formatting.')
|
|
221
|
+
|
|
222
|
+
def blocks(self, tokens: list[dict], level=0):
|
|
223
|
+
for token in tokens:
|
|
224
|
+
kind = token['type']
|
|
225
|
+
if kind in {'space', 'def'}:
|
|
226
|
+
continue
|
|
227
|
+
if kind == 'heading':
|
|
228
|
+
p = self.doc.add_heading(level=token['depth'])
|
|
229
|
+
self.inline(p, token.get('tokens', []))
|
|
230
|
+
elif kind in {'paragraph', 'text'}:
|
|
231
|
+
value = token.get('text', '')
|
|
232
|
+
has_svg_html = any(child['type'] == 'html' and re.match(r'<svg\b', child.get('text', ''), re.IGNORECASE)
|
|
233
|
+
for child in token.get('tokens', []))
|
|
234
|
+
if has_svg_html:
|
|
235
|
+
# CommonMark treats a one-line SVG as inline HTML tokens.
|
|
236
|
+
# Read the original paragraph, not those individual tags.
|
|
237
|
+
self.raw_html(value)
|
|
238
|
+
else:
|
|
239
|
+
p = self.doc.add_paragraph()
|
|
240
|
+
self.inline(p, token.get('tokens') or [{'type': 'text', 'text': value}])
|
|
241
|
+
elif kind == 'code':
|
|
242
|
+
if (token.get('lang') or '').strip().lower() == 'svg':
|
|
243
|
+
self.image(token['text'].encode(), 'svg')
|
|
244
|
+
else:
|
|
245
|
+
p = self.doc.add_paragraph()
|
|
246
|
+
p.paragraph_format.space_before = Pt(4)
|
|
247
|
+
run = p.add_run(token['text']); run.font.name = 'Consolas'; run.font.size = Pt(9)
|
|
248
|
+
elif kind == 'html':
|
|
249
|
+
self.raw_html(token['text'])
|
|
250
|
+
elif kind == 'list':
|
|
251
|
+
self.list_items(token, level)
|
|
252
|
+
elif kind == 'blockquote':
|
|
253
|
+
start = len(self.doc.paragraphs)
|
|
254
|
+
self.blocks(token['tokens'], level)
|
|
255
|
+
for p in self.doc.paragraphs[start:]:
|
|
256
|
+
p.paragraph_format.left_indent = Cm(.7)
|
|
257
|
+
elif kind == 'table':
|
|
258
|
+
self.table(token)
|
|
259
|
+
elif kind == 'hr':
|
|
260
|
+
self.doc.add_paragraph()
|
|
261
|
+
else:
|
|
262
|
+
raise ValueError(f'Unsupported Markdown block: {kind}')
|
|
263
|
+
|
|
264
|
+
def list_items(self, token: dict, level: int):
|
|
265
|
+
for index, item in enumerate(token['items']):
|
|
266
|
+
p = self.doc.add_paragraph()
|
|
267
|
+
p.paragraph_format.left_indent = Cm(.6 * (level + 1))
|
|
268
|
+
p.paragraph_format.first_line_indent = Cm(-.4)
|
|
269
|
+
# Explicit markers preserve arbitrary Markdown starting numbers across renderers.
|
|
270
|
+
prefix = f"{int(token.get('start') or 1) + index}. " if token['ordered'] else '• '
|
|
271
|
+
if item.get('task'):
|
|
272
|
+
prefix = '[x] ' if item.get('checked') else '[ ] '
|
|
273
|
+
p.add_run(prefix)
|
|
274
|
+
first = True
|
|
275
|
+
for child in item['tokens']:
|
|
276
|
+
if child['type'] in {'text', 'paragraph'}:
|
|
277
|
+
if not first:
|
|
278
|
+
p = self.doc.add_paragraph()
|
|
279
|
+
p.paragraph_format.left_indent = Cm(.6 * (level + 1))
|
|
280
|
+
self.inline(p, child.get('tokens') or [{'type': 'text', 'text': child['text']}])
|
|
281
|
+
first = False
|
|
282
|
+
elif child['type'] == 'list':
|
|
283
|
+
self.list_items(child, level + 1)
|
|
284
|
+
else:
|
|
285
|
+
self.blocks([child], level + 1)
|
|
286
|
+
|
|
287
|
+
def table(self, token: dict):
|
|
288
|
+
rows = [token['header']] + token['rows']
|
|
289
|
+
table = self.doc.add_table(rows=len(rows), cols=len(rows[0]))
|
|
290
|
+
table.style = 'Table Grid'
|
|
291
|
+
for i, row in enumerate(rows):
|
|
292
|
+
trpr = table.rows[i]._tr.get_or_add_trPr()
|
|
293
|
+
if i == 0:
|
|
294
|
+
repeat = OxmlElement('w:tblHeader'); trpr.append(repeat)
|
|
295
|
+
for j, cell in enumerate(row):
|
|
296
|
+
target = table.cell(i, j)
|
|
297
|
+
target.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
|
|
298
|
+
self.inline(target.paragraphs[0], cell['tokens'])
|
|
299
|
+
props = target._tc.get_or_add_tcPr()
|
|
300
|
+
borders = OxmlElement('w:tcBorders')
|
|
301
|
+
for side in ['top', 'left', 'bottom', 'right']:
|
|
302
|
+
line = OxmlElement('w:' + side)
|
|
303
|
+
for key, val in [('val', 'single'), ('sz', '4'), ('color', 'D9D9D9')]:
|
|
304
|
+
line.set(qn('w:' + key), val)
|
|
305
|
+
borders.append(line)
|
|
306
|
+
props.append(borders)
|
|
307
|
+
margins = OxmlElement('w:tcMar')
|
|
308
|
+
for side in ['top', 'left', 'bottom', 'right']:
|
|
309
|
+
margin = OxmlElement('w:' + side); margin.set(qn('w:w'), '90'); margin.set(qn('w:type'), 'dxa'); margins.append(margin)
|
|
310
|
+
props.append(margins)
|
|
311
|
+
if i == 0:
|
|
312
|
+
shade = OxmlElement('w:shd'); shade.set(qn('w:fill'), 'E8EEF5'); props.append(shade)
|
|
313
|
+
for run in target.paragraphs[0].runs:
|
|
314
|
+
run.bold = True
|
|
315
|
+
alignment = token.get('align', [None] * len(row))[j]
|
|
316
|
+
if alignment in {'center', 'right'}:
|
|
317
|
+
target.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER if alignment == 'center' else WD_ALIGN_PARAGRAPH.RIGHT
|
|
318
|
+
self.doc.add_paragraph()
|
|
319
|
+
|
|
320
|
+
def convert(self, output: Path):
|
|
321
|
+
try:
|
|
322
|
+
tokens = node_call({'action': 'parse', 'markdown': self.source.read_text(encoding='utf-8-sig')})
|
|
323
|
+
self.blocks(tokens)
|
|
324
|
+
output.parent.mkdir(parents=True, exist_ok=True)
|
|
325
|
+
with tempfile.NamedTemporaryFile(dir=output.parent, suffix='.docx', delete=False) as file:
|
|
326
|
+
scratch = Path(file.name)
|
|
327
|
+
try:
|
|
328
|
+
self.doc.save(scratch)
|
|
329
|
+
os.replace(scratch, output)
|
|
330
|
+
finally:
|
|
331
|
+
scratch.unlink(missing_ok=True)
|
|
332
|
+
finally:
|
|
333
|
+
self.temp.cleanup()
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def main():
|
|
337
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
338
|
+
parser.add_argument('input', type=Path)
|
|
339
|
+
parser.add_argument('-o', '--output', type=Path)
|
|
340
|
+
parser.add_argument('--template', type=Path, help='Optional DOCX style template; its body is discarded')
|
|
341
|
+
args = parser.parse_args()
|
|
342
|
+
source = args.input.expanduser().resolve()
|
|
343
|
+
output = (args.output or source.with_suffix('.docx')).expanduser().resolve()
|
|
344
|
+
if source == output:
|
|
345
|
+
parser.error('Input and output must be different files')
|
|
346
|
+
try:
|
|
347
|
+
converter = Converter(source, args.template)
|
|
348
|
+
converter.convert(output)
|
|
349
|
+
print(f'Created {output} ({converter.images} images)')
|
|
350
|
+
for message in dict.fromkeys(converter.warnings):
|
|
351
|
+
print('Warning: ' + message, file=sys.stderr)
|
|
352
|
+
except (ValueError, OSError, etree.XMLSyntaxError, subprocess.TimeoutExpired) as exc:
|
|
353
|
+
print(f'Conversion failed: {exc}', file=sys.stderr)
|
|
354
|
+
return 1
|
|
355
|
+
return 0
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
if __name__ == '__main__':
|
|
359
|
+
raise SystemExit(main())
|