markdown-to-word 0.4.0 → 0.6.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/README.md +19 -8
- package/build/cli.js +66 -3
- package/build/cli.js.map +1 -1
- package/build/docx-font-preset.d.ts +29 -3
- package/build/docx-font-preset.js +261 -13
- package/build/docx-font-preset.js.map +1 -1
- package/build/docx-html.d.ts +14 -6
- package/build/docx-html.js +157 -21
- package/build/docx-html.js.map +1 -1
- package/build/docx-images.d.ts +3 -1
- package/build/docx-images.js +144 -13
- package/build/docx-images.js.map +1 -1
- package/build/docx-structure.d.ts +9 -0
- package/build/docx-structure.js +51 -1
- package/build/docx-structure.js.map +1 -1
- package/build/font-presets.d.ts +37 -0
- package/build/font-presets.js +19 -0
- package/build/font-presets.js.map +1 -1
- package/build/input-checks.d.ts +4 -0
- package/build/input-checks.js +9 -0
- package/build/input-checks.js.map +1 -0
- package/build/main.d.ts +1 -1
- package/build/main.js +1 -1
- package/build/main.js.map +1 -1
- package/build/markdown-parser.d.ts +6 -5
- package/build/markdown-parser.js +14 -8
- package/build/markdown-parser.js.map +1 -1
- package/build/mcp.js +7 -0
- package/build/mcp.js.map +1 -1
- package/package.json +12 -11
package/README.md
CHANGED
|
@@ -1,9 +1,15 @@
|
|
|
1
1
|
# Markdown to Word
|
|
2
2
|
|
|
3
|
-
[](https://github.com/benbalter/markdown-to-word-js/actions/workflows/ci.yml)
|
|
3
|
+
[](https://www.npmjs.com/package/markdown-to-word) [](https://www.npmjs.com/package/markdown-to-word) [](https://registry.modelcontextprotocol.io/v0/servers?search=io.github.benbalter/markdown-to-word) [](https://github.com/benbalter/markdown-to-word-js/actions/workflows/ci.yml) [](https://github.com/benbalter/markdown-to-word-js/blob/main/LICENSE)
|
|
4
4
|
|
|
5
5
|
Convert GitHub Flavored Markdown to a formatted Word (`.docx`) document, entirely in your browser, at **[md2word.app](https://md2word.app)**. Nothing is uploaded.
|
|
6
6
|
|
|
7
|
+
The same converter is on npm as [`markdown-to-word`](https://www.npmjs.com/package/markdown-to-word): a [command-line tool](#command-line), a [Node library](#use-it-from-code), and an [MCP server](#mcp-server) for AI agents, no clone required:
|
|
8
|
+
|
|
9
|
+
```console
|
|
10
|
+
npx markdown-to-word input.md
|
|
11
|
+
```
|
|
12
|
+
|
|
7
13
|
It's the mirror image of [word2md.com](https://word2md.com) ([word-to-markdown-js](https://github.com/benbalter/word-to-markdown-js)), which goes the other way, and the successor to [markdown_to_word](https://github.com/benbalter/markdown_to_word), the original Ruby gem and web demo, first published in 2015 and now archived.
|
|
8
14
|
|
|
9
15
|
## Usage
|
|
@@ -51,7 +57,10 @@ The preset also sets the page:
|
|
|
51
57
|
|
|
52
58
|
- **Paper and margins (5.1, 5.2.1):** A4, with a 37mm top margin (天头) and a 28mm left margin (订口) around a 156 × 225mm text block (版心).
|
|
53
59
|
- **22 lines of 28 characters (5.2.3):** a Word document grid (文档网格) with exact line spacing at its pitch, 28.95pt. Widow control (孤行控制) is off, so it can't push a line to the next page and leave 21.
|
|
54
|
-
- **Indent (7.3.3):** paragraphs, and the headings below the title, start two characters in (首行缩进 2 字符). Table cells
|
|
60
|
+
- **Indent (7.3.3):** paragraphs, and the headings below the title, start two characters in (首行缩进 2 字符). Table cells and code blocks don't.
|
|
61
|
+
- **Lists:** every level of an ordered or unordered list is laid out like a 公文 paragraph — the item's first line starts two characters in (首行缩进 2 字符) and one space, not a tab, separates the mark from its content (编号与内容的间距: 适中). Ordered levels stay flush with the text block (文本之前 0) at every depth, which is what a 公文 does: its numbering text already shows the level. Bulleted levels step out by two characters per level so nesting is visible, and each level gets its own bullet, as Word's multi-level library does: ● then ○ then ▪, repeated for deeper levels, drawn in the body font.
|
|
62
|
+
- **Multi-level numbering (opt-in):** the **Chinese official document (公文), 1.1 numbering** style additionally counts nested numbers through their parent, so the second item of the third item reads `3.2`. GB/T 9704-2012 §7.3.3 numbers levels 一、 (一) 1. (1) rather than 1.1, so this is a separate choice for contracts and similar instruments: it points every level of one list at a single numbering definition (`w:numId`) and rewrites the level text to `%1.`, `%1.%2.`, `%1.%2.%3.`. Separate lists keep separate counters, and a bullet nested inside a numbered list keeps its own definition.
|
|
63
|
+
- **Tables:** cells are centered vertically (垂直对齐: 居中) and their paragraphs use single line spacing with grid snapping off (取消"如果定义了文档网格,则与网格对齐"). The page grid's exact 28.95pt pitch would stretch every row and clip text that wraps, so cells stay outside it.
|
|
55
64
|
- **Title (7.3.1):** Heading 1 is centered.
|
|
56
65
|
- **Spacing:** 段前段后 0 行 on every level.
|
|
57
66
|
|
|
@@ -82,7 +91,7 @@ const blob = await convertMarkdownToWord(markdown, {
|
|
|
82
91
|
|
|
83
92
|
## Privacy
|
|
84
93
|
|
|
85
|
-
Conversion happens entirely in your browser: your Markdown and the Word document never leave your device. Images your Markdown links to load from the sites that host them, like on any web page. md2word.app uses cookie-free Cloudflare Web Analytics; a local or self-hosted copy
|
|
94
|
+
Conversion happens entirely in your browser: your Markdown and the Word document never leave your device. Images your Markdown links to load from the sites that host them, like on any web page. md2word.app uses cookie-free Cloudflare Web Analytics and keeps an anonymous count of conversions (whether each succeeded and if not why, the page's language, and how it started; never the content, filename, size, or anything that identifies you); a local or self-hosted copy sends neither. Raw HTML in the preview is sanitized, so a shared file can't run script. See the [privacy policy](https://md2word.app/privacy/).
|
|
86
95
|
|
|
87
96
|
## Limitations
|
|
88
97
|
|
|
@@ -111,7 +120,7 @@ npm install -g markdown-to-word
|
|
|
111
120
|
md2w report.md
|
|
112
121
|
```
|
|
113
122
|
|
|
114
|
-
It writes the `.docx` next to the input with the same name (`report.md` becomes `report.docx`), replacing any file already there, and prints where it wrote it to **stderr**. It needs Node 22.
|
|
123
|
+
It writes the `.docx` next to the input with the same name (`report.md` becomes `report.docx`), replacing any file already there, and prints where it wrote it to **stderr**. It needs Node 22.22.2+, 24.15+, or 26+, and exits with status 1 and a message if the file is missing or empty.
|
|
115
124
|
|
|
116
125
|
To read the Markdown from **stdin**, pass `-` as the file, or leave it out and pipe the Markdown in. There's no file name to go on then, so `-o` is required:
|
|
117
126
|
|
|
@@ -123,7 +132,7 @@ md2w - -o - < report.md > report.docx
|
|
|
123
132
|
Options:
|
|
124
133
|
|
|
125
134
|
- `-o, --output <file>`: write the `.docx` to `<file>`, creating folders as needed. `-o -` writes it to stdout.
|
|
126
|
-
- `--font-preset <name>`: restyle the document with a font preset. `chinese-official` is the Chinese official document (公文) style described in [Optional Font Presets](#optional-font-presets).
|
|
135
|
+
- `--font-preset <name>`: restyle the document with a font preset. `chinese-official` is the Chinese official document (公文) style described in [Optional Font Presets](#optional-font-presets); `chinese-official-multilevel` adds the `1.1` numbering for contracts.
|
|
127
136
|
- `-q, --quiet`: print nothing to stderr except errors.
|
|
128
137
|
- `-V, --version`: print the version.
|
|
129
138
|
|
|
@@ -131,6 +140,8 @@ Options:
|
|
|
131
140
|
|
|
132
141
|
`md2w mcp` runs a local [Model Context Protocol](https://modelcontextprotocol.io) server on stdio, so AI agents can turn Markdown into Word documents on your machine. Like the website, it never uploads anything: the server converts in-process and writes the `.docx` to disk.
|
|
133
142
|
|
|
143
|
+
In Claude Desktop, it's one click: [download `markdown-to-word.mcpb`](https://github.com/benbalter/markdown-to-word-js/releases/latest/download/markdown-to-word.mcpb) and double-click it. Claude Desktop installs it as an extension. You don't need Node or a terminal, since Claude Desktop includes Node.
|
|
144
|
+
|
|
134
145
|
Add it to Claude Code:
|
|
135
146
|
|
|
136
147
|
```console
|
|
@@ -155,7 +166,7 @@ It has one tool, `convert_markdown_to_word`:
|
|
|
155
166
|
- `markdown` or `path` (exactly one): the Markdown as a string, or the path of a Markdown file (`.md`, `.markdown`, `.mdown`, or `.txt`). Prefer absolute paths; relative ones resolve against the server's working directory.
|
|
156
167
|
- `output_path` (required): where to write the `.docx`; it must end in `.docx`. Missing folders are created.
|
|
157
168
|
- `overwrite`: replace `output_path` if it already exists. Off by default, so the tool refuses to clobber an existing file and says so.
|
|
158
|
-
- `font_preset`: `chinese-official` for the 公文 style; omit for Word's default styling.
|
|
169
|
+
- `font_preset`: `chinese-official` for the 公文 style, `chinese-official-multilevel` for 公文 plus `1.1` numbering; omit for Word's default styling.
|
|
159
170
|
|
|
160
171
|
It returns the `output_path`, the file's size in `bytes`, and any `warnings` (remote images it didn't download, or a `.docx` patch that had to be skipped), also as structured content.
|
|
161
172
|
|
|
@@ -165,7 +176,7 @@ In the browser, md2word.app registers the same conversion as a [WebMCP](https://
|
|
|
165
176
|
|
|
166
177
|
## Use it from code
|
|
167
178
|
|
|
168
|
-
The converter is also on npm as [`markdown-to-word`](https://www.npmjs.com/package/markdown-to-word), for Node 22.
|
|
179
|
+
The converter is also on npm as [`markdown-to-word`](https://www.npmjs.com/package/markdown-to-word), for Node 22.22.2+, 24.15+, or 26+, and for browsers through a bundler (Vite, webpack, esbuild):
|
|
169
180
|
|
|
170
181
|
```bash
|
|
171
182
|
npm install markdown-to-word
|
|
@@ -193,7 +204,7 @@ On a server, treat Markdown from users as untrusted: the converter downloads eac
|
|
|
193
204
|
|
|
194
205
|
## Development
|
|
195
206
|
|
|
196
|
-
Requires Node.js 22.
|
|
207
|
+
Requires Node.js 22.22.2+, 24.15+, or 26+ (`.nvmrc` pins the version CI uses).
|
|
197
208
|
|
|
198
209
|
```bash
|
|
199
210
|
git clone https://github.com/benbalter/markdown-to-word-js.git
|
package/build/cli.js
CHANGED
|
@@ -5,9 +5,10 @@
|
|
|
5
5
|
// entry, which supplies the DOM APIs the converter needs.
|
|
6
6
|
import { Command, Option } from 'commander';
|
|
7
7
|
import { createRequire } from 'module';
|
|
8
|
-
import { mkdir, readFile, writeFile } from 'fs/promises';
|
|
8
|
+
import { mkdir, readFile, stat, writeFile } from 'fs/promises';
|
|
9
9
|
import path from 'path';
|
|
10
10
|
import { convertMarkdownToWord, FONT_PRESETS } from './node.js';
|
|
11
|
+
import { looksBinary, WORD_FILE } from './input-checks.js';
|
|
11
12
|
// Read our own version from package.json. createRequire resolves relative to
|
|
12
13
|
// this module, so `../package.json` points at the package root both from the
|
|
13
14
|
// TypeScript source (src/) and the compiled CLI (build/) after publish.
|
|
@@ -24,6 +25,50 @@ function defaultOutputPath(input) {
|
|
|
24
25
|
const { dir, name } = path.parse(input);
|
|
25
26
|
return path.join(dir, `${name}.docx`);
|
|
26
27
|
}
|
|
28
|
+
/**
|
|
29
|
+
* Whether `a` and `b` are the same file on disk. Compares inodes, not paths,
|
|
30
|
+
* so a symlink or a different case on a case-insensitive disk still counts.
|
|
31
|
+
* BigInt stats, because some filesystems hand out inode numbers above
|
|
32
|
+
* Number.MAX_SAFE_INTEGER, where two different files could round to the same
|
|
33
|
+
* number.
|
|
34
|
+
*/
|
|
35
|
+
async function isSameFile(a, b) {
|
|
36
|
+
const [statA, statB] = await Promise.all([
|
|
37
|
+
stat(a, { bigint: true }).catch(() => undefined),
|
|
38
|
+
stat(b, { bigint: true }).catch(() => undefined),
|
|
39
|
+
]);
|
|
40
|
+
return (statA !== undefined &&
|
|
41
|
+
statB !== undefined &&
|
|
42
|
+
statA.dev === statB.dev &&
|
|
43
|
+
statA.ino === statB.ino);
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* `value` as one shell word, for commands we print for the user to copy.
|
|
47
|
+
* Plain names stay bare so the common case reads cleanly.
|
|
48
|
+
*/
|
|
49
|
+
function shellQuote(value) {
|
|
50
|
+
return /^[\w@%+=:,./-]+$/.test(value)
|
|
51
|
+
? value
|
|
52
|
+
: `'${value.replaceAll("'", "'\\''")}'`;
|
|
53
|
+
}
|
|
54
|
+
// html-to-docx logs as it works: debug lines with console.log, which would
|
|
55
|
+
// land in front of a .docx written to stdout, and skipped images or a missing
|
|
56
|
+
// sharp with console.warn and console.error. The convert action sends the
|
|
57
|
+
// console.log family to stderr, and with -q drops all of it while the
|
|
58
|
+
// generator runs; our own errors print afterward. (`md2w mcp` has its own
|
|
59
|
+
// guard in src/mcp.ts.)
|
|
60
|
+
async function withConsoleSilenced(run) {
|
|
61
|
+
const saved = { ...console };
|
|
62
|
+
const silent = () => { };
|
|
63
|
+
console.log = console.info = console.debug = silent;
|
|
64
|
+
console.warn = console.error = silent;
|
|
65
|
+
try {
|
|
66
|
+
return await run();
|
|
67
|
+
}
|
|
68
|
+
finally {
|
|
69
|
+
Object.assign(console, saved);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
27
72
|
const EXAMPLES = `
|
|
28
73
|
Examples:
|
|
29
74
|
$ md2w report.md # writes report.docx
|
|
@@ -57,6 +102,8 @@ const convert = program
|
|
|
57
102
|
.option('-q, --quiet', 'Print nothing to stderr except errors')
|
|
58
103
|
.addHelpText('after', EXAMPLES)
|
|
59
104
|
.action(async (file, options) => {
|
|
105
|
+
const toStderr = console.error.bind(console);
|
|
106
|
+
console.log = console.info = console.debug = toStderr;
|
|
60
107
|
const note = (message) => {
|
|
61
108
|
if (!options.quiet)
|
|
62
109
|
console.error(message);
|
|
@@ -68,6 +115,11 @@ const convert = program
|
|
|
68
115
|
if (!file && !fromStdin) {
|
|
69
116
|
convert.help({ error: true });
|
|
70
117
|
}
|
|
118
|
+
// A Word file would otherwise be read as garbage text and, with no -o,
|
|
119
|
+
// written back over itself as report.docx.
|
|
120
|
+
if (!fromStdin && WORD_FILE.test(file)) {
|
|
121
|
+
throw new Error(`${file} is already a Word document. To turn it into Markdown, use word2md.com or its CLI: npx word-to-markdown ${shellQuote(file)} > ${shellQuote(`${path.parse(file).name}.md`)}`);
|
|
122
|
+
}
|
|
71
123
|
if (fromStdin && !options.output) {
|
|
72
124
|
throw new Error('Reading from stdin, so there is no file name to name the .docx after. Pass -o report.docx (or -o - for stdout).');
|
|
73
125
|
}
|
|
@@ -84,13 +136,24 @@ const convert = program
|
|
|
84
136
|
? 'Nothing was piped to stdin. Pass a Markdown file, or pipe one in: md2w -o report.docx < report.md'
|
|
85
137
|
: `${file} is empty.`);
|
|
86
138
|
}
|
|
87
|
-
|
|
139
|
+
if (looksBinary(markdown)) {
|
|
140
|
+
throw new Error(`${fromStdin ? 'stdin' : file} doesn't look like a Markdown or text file, so it can't be converted.`);
|
|
141
|
+
}
|
|
142
|
+
const output = options.output ?? defaultOutputPath(file);
|
|
143
|
+
if (output !== '-' &&
|
|
144
|
+
!fromStdin &&
|
|
145
|
+
(await isSameFile(output, file))) {
|
|
146
|
+
throw new Error(`${output} is the input file, so writing the .docx there would overwrite it. Pass a different -o.`);
|
|
147
|
+
}
|
|
148
|
+
const generate = () => convertMarkdownToWord(markdown, {
|
|
88
149
|
fontPreset: options.fontPreset
|
|
89
150
|
? FONT_PRESETS[options.fontPreset]
|
|
90
151
|
: undefined,
|
|
91
152
|
});
|
|
153
|
+
const blob = options.quiet
|
|
154
|
+
? await withConsoleSilenced(generate)
|
|
155
|
+
: await generate();
|
|
92
156
|
const bytes = Buffer.from(await blob.arrayBuffer());
|
|
93
|
-
const output = options.output ?? defaultOutputPath(file);
|
|
94
157
|
if (output === '-') {
|
|
95
158
|
process.stdout.write(bytes);
|
|
96
159
|
}
|
package/build/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AAEA,wEAAwE;AACxE,0EAA0E;AAC1E,2EAA2E;AAC3E,0DAA0D;AAE1D,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAC5C,OAAO,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AACvC,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACzD,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,qBAAqB,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAEhE,6EAA6E;AAC7E,6EAA6E;AAC7E,wEAAwE;AACxE,MAAM,OAAO,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAC/C,MAAM,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,iBAAiB,CA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ACH,CAAC,CAAC,CAAC;AAEL,MAAM,OAAO,CAAC,UAAU,EAAE,CAAC","sourcesContent":["#!/usr/bin/env node\n\n// The `md2w` command (also installed as `markdown-to-word`): converts a\n// Markdown file, or stdin, to a .docx on disk. Patterned on word2md.com's\n// `w2m` CLI (benbalter/word-to-markdown-js), in reverse. It loads the Node\n// entry, which supplies the DOM APIs the converter needs.\n\nimport { Command, Option } from 'commander';\nimport { createRequire } from 'module';\nimport { mkdir, readFile, writeFile } from 'fs/promises';\nimport path from 'path';\nimport { convertMarkdownToWord, FONT_PRESETS } from './node.js';\n\n// Read our own version from package.json. createRequire resolves relative to\n// this module, so `../package.json` points at the package root both from the\n// TypeScript source (src/) and the compiled CLI (build/) after publish.\nconst require = createRequire(import.meta.url);\nconst { version } = require('../package.json') as { version: string };\n\nasync function readStdin(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) chunks.push(chunk as Buffer);\n return Buffer.concat(chunks).toString('utf8');\n}\n\n/** `notes.md` → `notes.docx`, next to the input. */\nfunction defaultOutputPath(input: string): string {\n const { dir, name } = path.parse(input);\n return path.join(dir, `${name}.docx`);\n}\n\nconst EXAMPLES = `\nExamples:\n $ md2w report.md # writes report.docx\n $ md2w report.md -o out/report.docx\n $ md2w --font-preset chinese-official notice.md\n $ cat reply.md | md2w -o reply.docx\n $ md2w - -o - < report.md > report.docx`;\n\nconst program = new Command();\nprogram.name('md2w');\nprogram.description('Convert Markdown to a formatted Word (.docx) document');\nprogram.version(version);\nprogram.addHelpText(\n 'after',\n `\\nRun \"md2w convert --help\" for all conversion options.\\n${EXAMPLES}`\n);\nprogram\n .command('mcp')\n .description(\n 'Run a local MCP server on stdio so AI agents can convert Markdown to ' +\n '.docx files on this machine (e.g. claude mcp add markdown-to-word -- ' +\n 'npx -y markdown-to-word mcp)'\n )\n .action(async () => {\n // Loaded only here, so conversions never pay for the MCP SDK.\n const { startMcpServer } = await import('./mcp.js');\n await startMcpServer(version);\n });\nconst convert = program\n .command('convert', { isDefault: true })\n .argument(\n '[file]',\n 'The Markdown file to convert. Use - (or omit it and pipe the Markdown ' +\n 'in) to read from stdin.'\n )\n .option(\n '-o, --output <file>',\n 'Write the .docx to <file> (- means stdout). Defaults to the input ' +\n 'file name with .docx; required when reading stdin.'\n )\n .addOption(\n new Option(\n '--font-preset <name>',\n 'Restyle the document with a font preset, e.g. chinese-official for ' +\n 'a Chinese official document (公文) after GB/T 9704-2012'\n ).choices(Object.keys(FONT_PRESETS))\n )\n .option('-q, --quiet', 'Print nothing to stderr except errors')\n .addHelpText('after', EXAMPLES)\n .action(async (file: string | undefined, options) => {\n const note = (message: string): void => {\n if (!options.quiet) console.error(message);\n };\n try {\n // An explicit `-`, or no file with something piped in, reads stdin. No\n // file at an interactive terminal would just hang, so ask for one.\n const fromStdin = file === '-' || (!file && !process.stdin.isTTY);\n if (!file && !fromStdin) {\n convert.help({ error: true });\n }\n if (fromStdin && !options.output) {\n throw new Error(\n 'Reading from stdin, so there is no file name to name the .docx after. Pass -o report.docx (or -o - for stdout).'\n );\n }\n\n const markdown = fromStdin\n ? await readStdin()\n : await readFile(file as string, 'utf8').catch((error: unknown) => {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new Error(`${file} was not found.`);\n }\n throw error;\n });\n if (markdown.trim() === '') {\n throw new Error(\n fromStdin\n ? 'Nothing was piped to stdin. Pass a Markdown file, or pipe one in: md2w -o report.docx < report.md'\n : `${file} is empty.`\n );\n }\n\n const blob = await convertMarkdownToWord(markdown, {\n fontPreset: options.fontPreset\n ? FONT_PRESETS[options.fontPreset]\n : undefined,\n });\n const bytes = Buffer.from(await blob.arrayBuffer());\n\n const output: string = options.output ?? defaultOutputPath(file!);\n if (output === '-') {\n process.stdout.write(bytes);\n } else {\n await mkdir(path.dirname(output), { recursive: true });\n await writeFile(output, bytes);\n note(`Wrote ${output}`);\n }\n } catch (error) {\n console.error(\n 'Error:',\n error instanceof Error ? error.message : String(error)\n );\n process.exit(1);\n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YACnB,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QAC9B,CAAC;aAAM,CAAC;YACN,MAAM,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;YACvD,MAAM,SAAS,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;YAC/B,IAAI,CAAC,SAAS,MAAM,EAAE,CAAC,CAAC;QAC1B,CAAC;IACH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,KAAK,CACX,QAAQ,EACR,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CACvD,CAAC;QACF,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;AACH,CAAC,CAAC,CAAC;AAEL,MAAM,OAAO,CAAC,UAAU,EAAE,CAAC","sourcesContent":["#!/usr/bin/env node\n\n// The `md2w` command (also installed as `markdown-to-word`): converts a\n// Markdown file, or stdin, to a .docx on disk. Patterned on word2md.com's\n// `w2m` CLI (benbalter/word-to-markdown-js), in reverse. It loads the Node\n// entry, which supplies the DOM APIs the converter needs.\n\nimport { Command, Option } from 'commander';\nimport { createRequire } from 'module';\nimport { mkdir, readFile, stat, writeFile } from 'fs/promises';\nimport path from 'path';\nimport { convertMarkdownToWord, FONT_PRESETS } from './node.js';\nimport { looksBinary, WORD_FILE } from './input-checks.js';\n\n// Read our own version from package.json. createRequire resolves relative to\n// this module, so `../package.json` points at the package root both from the\n// TypeScript source (src/) and the compiled CLI (build/) after publish.\nconst require = createRequire(import.meta.url);\nconst { version } = require('../package.json') as { version: string };\n\nasync function readStdin(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) chunks.push(chunk as Buffer);\n return Buffer.concat(chunks).toString('utf8');\n}\n\n/** `notes.md` → `notes.docx`, next to the input. */\nfunction defaultOutputPath(input: string): string {\n const { dir, name } = path.parse(input);\n return path.join(dir, `${name}.docx`);\n}\n\n/**\n * Whether `a` and `b` are the same file on disk. Compares inodes, not paths,\n * so a symlink or a different case on a case-insensitive disk still counts.\n * BigInt stats, because some filesystems hand out inode numbers above\n * Number.MAX_SAFE_INTEGER, where two different files could round to the same\n * number.\n */\nasync function isSameFile(a: string, b: string): Promise<boolean> {\n const [statA, statB] = await Promise.all([\n stat(a, { bigint: true }).catch(() => undefined),\n stat(b, { bigint: true }).catch(() => undefined),\n ]);\n return (\n statA !== undefined &&\n statB !== undefined &&\n statA.dev === statB.dev &&\n statA.ino === statB.ino\n );\n}\n\n/**\n * `value` as one shell word, for commands we print for the user to copy.\n * Plain names stay bare so the common case reads cleanly.\n */\nfunction shellQuote(value: string): string {\n return /^[\\w@%+=:,./-]+$/.test(value)\n ? value\n : `'${value.replaceAll(\"'\", \"'\\\\''\")}'`;\n}\n\n// html-to-docx logs as it works: debug lines with console.log, which would\n// land in front of a .docx written to stdout, and skipped images or a missing\n// sharp with console.warn and console.error. The convert action sends the\n// console.log family to stderr, and with -q drops all of it while the\n// generator runs; our own errors print afterward. (`md2w mcp` has its own\n// guard in src/mcp.ts.)\nasync function withConsoleSilenced<T>(run: () => Promise<T>): Promise<T> {\n const saved = { ...console };\n const silent = (): void => {};\n console.log = console.info = console.debug = silent;\n console.warn = console.error = silent;\n try {\n return await run();\n } finally {\n Object.assign(console, saved);\n }\n}\n\nconst EXAMPLES = `\nExamples:\n $ md2w report.md # writes report.docx\n $ md2w report.md -o out/report.docx\n $ md2w --font-preset chinese-official notice.md\n $ cat reply.md | md2w -o reply.docx\n $ md2w - -o - < report.md > report.docx`;\n\nconst program = new Command();\nprogram.name('md2w');\nprogram.description('Convert Markdown to a formatted Word (.docx) document');\nprogram.version(version);\nprogram.addHelpText(\n 'after',\n `\\nRun \"md2w convert --help\" for all conversion options.\\n${EXAMPLES}`\n);\nprogram\n .command('mcp')\n .description(\n 'Run a local MCP server on stdio so AI agents can convert Markdown to ' +\n '.docx files on this machine (e.g. claude mcp add markdown-to-word -- ' +\n 'npx -y markdown-to-word mcp)'\n )\n .action(async () => {\n // Loaded only here, so conversions never pay for the MCP SDK.\n const { startMcpServer } = await import('./mcp.js');\n await startMcpServer(version);\n });\nconst convert = program\n .command('convert', { isDefault: true })\n .argument(\n '[file]',\n 'The Markdown file to convert. Use - (or omit it and pipe the Markdown ' +\n 'in) to read from stdin.'\n )\n .option(\n '-o, --output <file>',\n 'Write the .docx to <file> (- means stdout). Defaults to the input ' +\n 'file name with .docx; required when reading stdin.'\n )\n .addOption(\n new Option(\n '--font-preset <name>',\n 'Restyle the document with a font preset, e.g. chinese-official for ' +\n 'a Chinese official document (公文) after GB/T 9704-2012'\n ).choices(Object.keys(FONT_PRESETS))\n )\n .option('-q, --quiet', 'Print nothing to stderr except errors')\n .addHelpText('after', EXAMPLES)\n .action(async (file: string | undefined, options) => {\n const toStderr = console.error.bind(console);\n console.log = console.info = console.debug = toStderr;\n const note = (message: string): void => {\n if (!options.quiet) console.error(message);\n };\n try {\n // An explicit `-`, or no file with something piped in, reads stdin. No\n // file at an interactive terminal would just hang, so ask for one.\n const fromStdin = file === '-' || (!file && !process.stdin.isTTY);\n if (!file && !fromStdin) {\n convert.help({ error: true });\n }\n // A Word file would otherwise be read as garbage text and, with no -o,\n // written back over itself as report.docx.\n if (!fromStdin && WORD_FILE.test(file as string)) {\n throw new Error(\n `${file} is already a Word document. To turn it into Markdown, use word2md.com or its CLI: npx word-to-markdown ${shellQuote(file as string)} > ${shellQuote(`${path.parse(file as string).name}.md`)}`\n );\n }\n if (fromStdin && !options.output) {\n throw new Error(\n 'Reading from stdin, so there is no file name to name the .docx after. Pass -o report.docx (or -o - for stdout).'\n );\n }\n\n const markdown = fromStdin\n ? await readStdin()\n : await readFile(file as string, 'utf8').catch((error: unknown) => {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new Error(`${file} was not found.`);\n }\n throw error;\n });\n if (markdown.trim() === '') {\n throw new Error(\n fromStdin\n ? 'Nothing was piped to stdin. Pass a Markdown file, or pipe one in: md2w -o report.docx < report.md'\n : `${file} is empty.`\n );\n }\n if (looksBinary(markdown)) {\n throw new Error(\n `${fromStdin ? 'stdin' : file} doesn't look like a Markdown or text file, so it can't be converted.`\n );\n }\n\n const output: string = options.output ?? defaultOutputPath(file!);\n if (\n output !== '-' &&\n !fromStdin &&\n (await isSameFile(output, file as string))\n ) {\n throw new Error(\n `${output} is the input file, so writing the .docx there would overwrite it. Pass a different -o.`\n );\n }\n\n const generate = (): Promise<Blob> =>\n convertMarkdownToWord(markdown, {\n fontPreset: options.fontPreset\n ? FONT_PRESETS[options.fontPreset]\n : undefined,\n });\n const blob = options.quiet\n ? await withConsoleSilenced(generate)\n : await generate();\n const bytes = Buffer.from(await blob.arrayBuffer());\n\n if (output === '-') {\n process.stdout.write(bytes);\n } else {\n await mkdir(path.dirname(output), { recursive: true });\n await writeFile(output, bytes);\n note(`Wrote ${output}`);\n }\n } catch (error) {\n console.error(\n 'Error:',\n error instanceof Error ? error.message : String(error)\n );\n process.exit(1);\n }\n });\n\nawait program.parseAsync();\n"]}
|
|
@@ -7,8 +7,8 @@ interface Grid {
|
|
|
7
7
|
charSpace: number;
|
|
8
8
|
}
|
|
9
9
|
/**
|
|
10
|
-
* Rewrites the fonts, sizes, paragraph spacing
|
|
11
|
-
* generated .docx.
|
|
10
|
+
* Rewrites the fonts, sizes, paragraph spacing, page grid and list layout of an
|
|
11
|
+
* already generated .docx.
|
|
12
12
|
*
|
|
13
13
|
* `html-to-docx` only ever writes `w:ascii`, which WinWord applies to Latin
|
|
14
14
|
* characters and digits; Chinese characters fall back to the theme font. The
|
|
@@ -37,9 +37,35 @@ export declare function patchStylesXml(stylesXml: string, preset: FontPreset, gr
|
|
|
37
37
|
* with a drawing keep single spacing; the grid then rounds them up to whole
|
|
38
38
|
* lines.
|
|
39
39
|
* - Table cells drop the first-line indent; it only crowds narrow columns.
|
|
40
|
+
* - When the preset describes table cells, they are laid out on their own
|
|
41
|
+
* terms instead of inheriting the page grid: vertical alignment, line
|
|
42
|
+
* spacing and grid snapping.
|
|
40
43
|
*/
|
|
41
|
-
export declare function patchDocumentXml(documentXml: string, preset: FontPreset): {
|
|
44
|
+
export declare function patchDocumentXml(documentXml: string, preset: FontPreset, formats?: NumberFormats): {
|
|
42
45
|
xml: string;
|
|
43
46
|
grid: Grid | null;
|
|
44
47
|
};
|
|
48
|
+
/** The number format a numbering definition uses at each level. */
|
|
49
|
+
export type NumberFormats = ReadonlyMap<string, string[]>;
|
|
50
|
+
/**
|
|
51
|
+
* Lays out lists the way a 公文 does, in the place Word itself writes these
|
|
52
|
+
* choices — the numbering definitions:
|
|
53
|
+
*
|
|
54
|
+
* - 首行缩进 N 字符: the item's first line is indented by the preset's
|
|
55
|
+
* `firstLineIndentChars`, written as `w:firstLineChars` so Word shows it in
|
|
56
|
+
* characters and it scales with the font size.
|
|
57
|
+
* - 编号与内容的间距 适中: `w:suff` is `space`, so one space separates the
|
|
58
|
+
* number or bullet from its content instead of a tab.
|
|
59
|
+
* - 文本之前: ordered levels sit flush with the text block at every level, the
|
|
60
|
+
* way a printed 公文 numbers its items (1. (1) ① all start from the same
|
|
61
|
+
* margin). Bulleted levels instead step out by the preset's indent each
|
|
62
|
+
* level, because a bullet carries no hierarchy of its own.
|
|
63
|
+
* - one bullet per nesting level, ● then ○ then ▪.
|
|
64
|
+
*
|
|
65
|
+
* Numbering itself is left alone: ordered levels keep the generator's
|
|
66
|
+
* `%1.` / `%2.` text. The level's tab stop stays where it is, so a renderer
|
|
67
|
+
* that ignores `w:suff` still puts the content near the indent rather than on
|
|
68
|
+
* top of the mark.
|
|
69
|
+
*/
|
|
70
|
+
export declare function patchNumberingXml(numberingXml: string, preset: FontPreset): string;
|
|
45
71
|
export {};
|
|
@@ -13,8 +13,8 @@ const THEME_FONT_ATTRIBUTES = [
|
|
|
13
13
|
*/
|
|
14
14
|
const SINGLE_SPACING = { line: '240', rule: 'auto' };
|
|
15
15
|
/**
|
|
16
|
-
* Rewrites the fonts, sizes, paragraph spacing
|
|
17
|
-
* generated .docx.
|
|
16
|
+
* Rewrites the fonts, sizes, paragraph spacing, page grid and list layout of an
|
|
17
|
+
* already generated .docx.
|
|
18
18
|
*
|
|
19
19
|
* `html-to-docx` only ever writes `w:ascii`, which WinWord applies to Latin
|
|
20
20
|
* characters and digits; Chinese characters fall back to the theme font. The
|
|
@@ -30,22 +30,36 @@ export async function applyFontPreset(wordDocument, preset) {
|
|
|
30
30
|
if (!stylesEntry) {
|
|
31
31
|
throw new Error('Cannot apply font preset: document contains no word/styles.xml');
|
|
32
32
|
}
|
|
33
|
+
// The numbering part is read first: laying the document's lists out needs to
|
|
34
|
+
// know which format each numbering definition uses at each level.
|
|
35
|
+
const numberingEntry = zip.file('word/numbering.xml');
|
|
36
|
+
const numberingXml = numberingEntry
|
|
37
|
+
? await numberingEntry.async('string')
|
|
38
|
+
: null;
|
|
39
|
+
const formats = numberingXml ? numberFormatsOf(numberingXml) : undefined;
|
|
33
40
|
let grid = null;
|
|
34
41
|
const pageGrid = preset.page?.grid;
|
|
35
42
|
if (pageGrid ||
|
|
36
43
|
preset.paragraph.lineSpacing === 'grid' ||
|
|
37
|
-
preset.paragraph.firstLineIndentChars
|
|
44
|
+
preset.paragraph.firstLineIndentChars ||
|
|
45
|
+
preset.list?.multilevelNumbers ||
|
|
46
|
+
preset.table) {
|
|
38
47
|
const documentEntry = zip.file('word/document.xml');
|
|
39
48
|
if (!documentEntry) {
|
|
40
49
|
throw new Error('Cannot apply font preset: document contains no word/document.xml');
|
|
41
50
|
}
|
|
42
51
|
const documentXml = await documentEntry.async('string');
|
|
43
|
-
const patched = patchDocumentXml(documentXml, preset);
|
|
52
|
+
const patched = patchDocumentXml(documentXml, preset, formats);
|
|
44
53
|
grid = patched.grid;
|
|
45
54
|
zip.file('word/document.xml', patched.xml);
|
|
46
55
|
}
|
|
47
56
|
const stylesXml = await stylesEntry.async('string');
|
|
48
57
|
zip.file('word/styles.xml', patchStylesXml(stylesXml, preset, grid));
|
|
58
|
+
// Lists are laid out only when the preset describes them; a document
|
|
59
|
+
// without lists has no numbering part anyway.
|
|
60
|
+
if (numberingXml !== null && preset.list) {
|
|
61
|
+
zip.file('word/numbering.xml', patchNumberingXml(numberingXml, preset));
|
|
62
|
+
}
|
|
49
63
|
const patched = await zip.generateAsync({ type: 'arraybuffer' });
|
|
50
64
|
return new Blob([patched], { type: wordDocument.type });
|
|
51
65
|
}
|
|
@@ -76,16 +90,21 @@ export function patchStylesXml(stylesXml, preset, grid = null) {
|
|
|
76
90
|
}
|
|
77
91
|
function resolveLayout(preset, grid) {
|
|
78
92
|
const { lineSpacing, firstLineIndentChars = 0 } = preset.paragraph;
|
|
79
|
-
if (lineSpacing === 'grid' && !grid) {
|
|
80
|
-
throw new Error("Cannot apply font preset: lineSpacing 'grid' needs page.grid");
|
|
81
|
-
}
|
|
82
93
|
return {
|
|
83
|
-
spacing: lineSpacing
|
|
84
|
-
? { line: String(grid.linePitch), rule: 'exact' }
|
|
85
|
-
: SINGLE_SPACING,
|
|
94
|
+
spacing: spacingFor(lineSpacing, grid),
|
|
86
95
|
firstLineIndent: Math.round(firstLineIndentChars * preset.body.sizePt * 20),
|
|
87
96
|
};
|
|
88
97
|
}
|
|
98
|
+
/** The `<w:spacing>` pair a line-spacing choice resolves to on this page. */
|
|
99
|
+
function spacingFor(lineSpacing, grid) {
|
|
100
|
+
if (lineSpacing !== 'grid') {
|
|
101
|
+
return SINGLE_SPACING;
|
|
102
|
+
}
|
|
103
|
+
if (!grid) {
|
|
104
|
+
throw new Error("Cannot apply font preset: lineSpacing 'grid' needs page.grid");
|
|
105
|
+
}
|
|
106
|
+
return { line: String(grid.linePitch), rule: 'exact' };
|
|
107
|
+
}
|
|
89
108
|
/**
|
|
90
109
|
* Sets the page grid in the section properties of a document.xml part, and
|
|
91
110
|
* fixes up the paragraphs that the style-level layout would break:
|
|
@@ -98,9 +117,15 @@ function resolveLayout(preset, grid) {
|
|
|
98
117
|
* with a drawing keep single spacing; the grid then rounds them up to whole
|
|
99
118
|
* lines.
|
|
100
119
|
* - Table cells drop the first-line indent; it only crowds narrow columns.
|
|
120
|
+
* - When the preset describes table cells, they are laid out on their own
|
|
121
|
+
* terms instead of inheriting the page grid: vertical alignment, line
|
|
122
|
+
* spacing and grid snapping.
|
|
101
123
|
*/
|
|
102
|
-
export function patchDocumentXml(documentXml, preset) {
|
|
124
|
+
export function patchDocumentXml(documentXml, preset, formats) {
|
|
103
125
|
const dom = new DOMParser().parseFromString(documentXml, 'application/xml');
|
|
126
|
+
if (preset.list?.multilevelNumbers && formats) {
|
|
127
|
+
unifyListNumbering(dom, formats);
|
|
128
|
+
}
|
|
104
129
|
let grid = null;
|
|
105
130
|
const pageGrid = preset.page?.grid;
|
|
106
131
|
if (pageGrid) {
|
|
@@ -110,9 +135,11 @@ export function patchDocumentXml(documentXml, preset) {
|
|
|
110
135
|
}
|
|
111
136
|
}
|
|
112
137
|
const gridSpacing = preset.paragraph.lineSpacing === 'grid';
|
|
138
|
+
const table = preset.table;
|
|
113
139
|
for (const paragraph of Array.from(dom.getElementsByTagNameNS(W_NS, 'p'))) {
|
|
114
140
|
const pPr = children(paragraph).find((child) => child.localName === 'pPr');
|
|
115
|
-
|
|
141
|
+
const inTableCell = isInTableCell(paragraph);
|
|
142
|
+
if (gridSpacing && !inTableCell) {
|
|
116
143
|
if (paragraph.getElementsByTagNameNS(W_NS, 'drawing').length > 0) {
|
|
117
144
|
const spacing = paragraphProperty(pPrOf(paragraph), 'spacing');
|
|
118
145
|
spacing.setAttributeNS(W_NS, 'w:line', SINGLE_SPACING.line);
|
|
@@ -128,15 +155,236 @@ export function patchDocumentXml(documentXml, preset) {
|
|
|
128
155
|
}
|
|
129
156
|
}
|
|
130
157
|
}
|
|
131
|
-
if (
|
|
158
|
+
if (table && inTableCell) {
|
|
159
|
+
layoutTableCell(pPrOf(paragraph), table, grid);
|
|
160
|
+
}
|
|
161
|
+
if (preset.paragraph.firstLineIndentChars && inTableCell) {
|
|
132
162
|
removeFirstLineIndent(pPrOf(paragraph));
|
|
133
163
|
}
|
|
134
164
|
}
|
|
165
|
+
if (table) {
|
|
166
|
+
for (const cell of Array.from(dom.getElementsByTagNameNS(W_NS, 'tc'))) {
|
|
167
|
+
cellVerticalAlign(cell).setAttributeNS(W_NS, 'w:val', table.verticalAlign);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
135
170
|
return {
|
|
136
171
|
xml: keepXmlDeclaration(documentXml, new XMLSerializer().serializeToString(dom)),
|
|
137
172
|
grid,
|
|
138
173
|
};
|
|
139
174
|
}
|
|
175
|
+
/**
|
|
176
|
+
* Reads the numbering part into a `numId` → formats map, the way the document's
|
|
177
|
+
* paragraphs reference it. `<w:num>` names an `<w:abstractNum>`, so the
|
|
178
|
+
* abstract's levels answer for the id the paragraphs use.
|
|
179
|
+
*/
|
|
180
|
+
function numberFormatsOf(numberingXml) {
|
|
181
|
+
const dom = new DOMParser().parseFromString(numberingXml, 'application/xml');
|
|
182
|
+
const formatsByAbstract = new Map();
|
|
183
|
+
for (const abstract of Array.from(dom.getElementsByTagNameNS(W_NS, 'abstractNum'))) {
|
|
184
|
+
const abstractId = abstract.getAttributeNS(W_NS, 'abstractNumId');
|
|
185
|
+
if (abstractId === null) {
|
|
186
|
+
continue;
|
|
187
|
+
}
|
|
188
|
+
const levels = [];
|
|
189
|
+
for (const lvl of children(abstract).filter((child) => child.localName === 'lvl')) {
|
|
190
|
+
const ilvl = Number(lvl.getAttributeNS(W_NS, 'ilvl') ?? levels.length);
|
|
191
|
+
levels[ilvl] =
|
|
192
|
+
children(lvl)
|
|
193
|
+
.find((child) => child.localName === 'numFmt')
|
|
194
|
+
?.getAttributeNS(W_NS, 'val') ?? '';
|
|
195
|
+
}
|
|
196
|
+
formatsByAbstract.set(abstractId, levels);
|
|
197
|
+
}
|
|
198
|
+
const formats = new Map();
|
|
199
|
+
for (const num of Array.from(dom.getElementsByTagNameNS(W_NS, 'num'))) {
|
|
200
|
+
const numId = num.getAttributeNS(W_NS, 'numId');
|
|
201
|
+
const abstractId = num
|
|
202
|
+
.getElementsByTagNameNS(W_NS, 'abstractNumId')[0]
|
|
203
|
+
?.getAttributeNS(W_NS, 'val');
|
|
204
|
+
const levels = abstractId === null ? undefined : formatsByAbstract.get(abstractId);
|
|
205
|
+
if (numId !== null && levels) {
|
|
206
|
+
formats.set(numId, levels);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
return formats;
|
|
210
|
+
}
|
|
211
|
+
/** The `<w:numPr>` of a paragraph, when it has one that names a numbering. */
|
|
212
|
+
function numberingOf(paragraph) {
|
|
213
|
+
const pPr = children(paragraph).find((child) => child.localName === 'pPr');
|
|
214
|
+
const numPr = pPr && children(pPr).find((child) => child.localName === 'numPr');
|
|
215
|
+
if (!numPr) {
|
|
216
|
+
return null;
|
|
217
|
+
}
|
|
218
|
+
const numIdElement = children(numPr).find((child) => child.localName === 'numId');
|
|
219
|
+
const numId = numIdElement?.getAttributeNS(W_NS, 'val');
|
|
220
|
+
if (!numIdElement || numId === undefined || numId === null) {
|
|
221
|
+
return null;
|
|
222
|
+
}
|
|
223
|
+
const ilvl = Number(children(numPr)
|
|
224
|
+
.find((child) => child.localName === 'ilvl')
|
|
225
|
+
?.getAttributeNS(W_NS, 'val') ?? '0');
|
|
226
|
+
return { ilvl, numId, numIdElement };
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Word counts a multi-level list inside one numbering definition: its items
|
|
230
|
+
* share a `w:numId` and only `w:ilvl` changes. The generator instead gives
|
|
231
|
+
* every nesting depth its own definition, so a nested item's `%1` is that
|
|
232
|
+
* sub-list's counter rather than its parent's, and 1.1 can never appear.
|
|
233
|
+
*
|
|
234
|
+
* Point the deeper items of a list at the definition its first level uses. A
|
|
235
|
+
* fresh first-level definition opens a new list, so separate lists never share
|
|
236
|
+
* a counter, and a nested level whose format differs from the list's own (a
|
|
237
|
+
* bullet inside a numbered list) keeps its own definition.
|
|
238
|
+
*/
|
|
239
|
+
function unifyListNumbering(dom, formats) {
|
|
240
|
+
let listNumId = null;
|
|
241
|
+
for (const paragraph of Array.from(dom.getElementsByTagNameNS(W_NS, 'p'))) {
|
|
242
|
+
const numbering = numberingOf(paragraph);
|
|
243
|
+
if (!numbering) {
|
|
244
|
+
// A list item's later paragraphs are unnumbered but indented under the
|
|
245
|
+
// item, so only an unindented paragraph ends the list.
|
|
246
|
+
const ind = paragraph.getElementsByTagNameNS(W_NS, 'ind')[0];
|
|
247
|
+
if (Number(ind?.getAttributeNS(W_NS, 'left') ?? 0) <= 0) {
|
|
248
|
+
listNumId = null;
|
|
249
|
+
}
|
|
250
|
+
continue;
|
|
251
|
+
}
|
|
252
|
+
if (numbering.ilvl === 0) {
|
|
253
|
+
listNumId = numbering.numId;
|
|
254
|
+
continue;
|
|
255
|
+
}
|
|
256
|
+
if (listNumId === null) {
|
|
257
|
+
continue;
|
|
258
|
+
}
|
|
259
|
+
const list = formats.get(listNumId);
|
|
260
|
+
const own = formats.get(numbering.numId);
|
|
261
|
+
if (!list || !own || list[numbering.ilvl] !== own[numbering.ilvl]) {
|
|
262
|
+
continue;
|
|
263
|
+
}
|
|
264
|
+
numbering.numIdElement.setAttributeNS(W_NS, 'w:val', listNumId);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Lays out lists the way a 公文 does, in the place Word itself writes these
|
|
269
|
+
* choices — the numbering definitions:
|
|
270
|
+
*
|
|
271
|
+
* - 首行缩进 N 字符: the item's first line is indented by the preset's
|
|
272
|
+
* `firstLineIndentChars`, written as `w:firstLineChars` so Word shows it in
|
|
273
|
+
* characters and it scales with the font size.
|
|
274
|
+
* - 编号与内容的间距 适中: `w:suff` is `space`, so one space separates the
|
|
275
|
+
* number or bullet from its content instead of a tab.
|
|
276
|
+
* - 文本之前: ordered levels sit flush with the text block at every level, the
|
|
277
|
+
* way a printed 公文 numbers its items (1. (1) ① all start from the same
|
|
278
|
+
* margin). Bulleted levels instead step out by the preset's indent each
|
|
279
|
+
* level, because a bullet carries no hierarchy of its own.
|
|
280
|
+
* - one bullet per nesting level, ● then ○ then ▪.
|
|
281
|
+
*
|
|
282
|
+
* Numbering itself is left alone: ordered levels keep the generator's
|
|
283
|
+
* `%1.` / `%2.` text. The level's tab stop stays where it is, so a renderer
|
|
284
|
+
* that ignores `w:suff` still puts the content near the indent rather than on
|
|
285
|
+
* top of the mark.
|
|
286
|
+
*/
|
|
287
|
+
export function patchNumberingXml(numberingXml, preset) {
|
|
288
|
+
const dom = new DOMParser().parseFromString(numberingXml, 'application/xml');
|
|
289
|
+
const indentChars = preset.paragraph.firstLineIndentChars ?? 0;
|
|
290
|
+
const bullets = preset.list?.bullets ?? [];
|
|
291
|
+
for (const lvl of Array.from(dom.getElementsByTagNameNS(W_NS, 'lvl'))) {
|
|
292
|
+
const format = children(lvl).find((child) => child.localName === 'numFmt');
|
|
293
|
+
const bulleted = format?.getAttributeNS(W_NS, 'val') === 'bullet';
|
|
294
|
+
const level = Number(lvl.getAttributeNS(W_NS, 'ilvl') ?? '0');
|
|
295
|
+
// Only bullets nest by indentation; numbering text already shows the level.
|
|
296
|
+
const indentLevel = bulleted ? level : 0;
|
|
297
|
+
setNumberSeparator(lvl);
|
|
298
|
+
const ind = childOrCreate(numberingParagraphOf(lvl), 'ind', 'last');
|
|
299
|
+
for (const attribute of ['hanging', 'hangingChars', 'firstLine']) {
|
|
300
|
+
ind.removeAttributeNS(W_NS, attribute);
|
|
301
|
+
}
|
|
302
|
+
// One character is the body font size in twips, which is what a renderer
|
|
303
|
+
// that ignores the `*Chars` attributes needs alongside them.
|
|
304
|
+
ind.setAttributeNS(W_NS, 'w:left', String(indentLevel * indentChars * preset.body.sizePt * 20));
|
|
305
|
+
ind.setAttributeNS(W_NS, 'w:leftChars', String(indentLevel * indentChars * 100));
|
|
306
|
+
ind.setAttributeNS(W_NS, 'w:firstLineChars', String(indentChars * 100));
|
|
307
|
+
if (bulleted && bullets.length) {
|
|
308
|
+
setBulletGlyph(lvl, level, bullets, preset.body.eastAsia);
|
|
309
|
+
}
|
|
310
|
+
else if (!bulleted && preset.list?.multilevelNumbers) {
|
|
311
|
+
setMultilevelNumber(lvl, level);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
return keepXmlDeclaration(numberingXml, new XMLSerializer().serializeToString(dom));
|
|
315
|
+
}
|
|
316
|
+
/**
|
|
317
|
+
* Gives each nesting level its own bullet, as Word's multi-level library does.
|
|
318
|
+
* The generator repeats one private-use glyph in the Symbol font at every
|
|
319
|
+
* level, so the level's run properties move to the body font, which carries
|
|
320
|
+
* these shapes.
|
|
321
|
+
*/
|
|
322
|
+
function setBulletGlyph(lvl, level, bullets, font) {
|
|
323
|
+
const format = children(lvl).find((child) => child.localName === 'numFmt');
|
|
324
|
+
if (format?.getAttributeNS(W_NS, 'val') !== 'bullet') {
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
const lvlText = children(lvl).find((child) => child.localName === 'lvlText');
|
|
328
|
+
if (!lvlText) {
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
lvlText.setAttributeNS(W_NS, 'w:val', bullets[Math.min(level, bullets.length - 1)]);
|
|
332
|
+
const rFonts = childOrCreate(childOrCreate(lvl, 'rPr', 'last'), 'rFonts', 'first');
|
|
333
|
+
for (const attribute of ['ascii', 'hAnsi', 'eastAsia', 'cs']) {
|
|
334
|
+
rFonts.setAttributeNS(W_NS, `w:${attribute}`, font);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
/**
|
|
338
|
+
* Makes a nested number carry its parents: level 0 stays `1.`, level 1 becomes
|
|
339
|
+
* `1.1`, level 2 `1.1.1`. Word restarts a level whenever the one above it
|
|
340
|
+
* moves, which is its default, so the second item of the third item reads 3.2.
|
|
341
|
+
*/
|
|
342
|
+
function setMultilevelNumber(lvl, level) {
|
|
343
|
+
const lvlText = children(lvl).find((child) => child.localName === 'lvlText');
|
|
344
|
+
if (!lvlText) {
|
|
345
|
+
return;
|
|
346
|
+
}
|
|
347
|
+
const parents = Array.from({ length: level }, (_, index) => `%${index + 1}`);
|
|
348
|
+
lvlText.setAttributeNS(W_NS, 'w:val', [...parents, `%${level + 1}.`].join('.'));
|
|
349
|
+
}
|
|
350
|
+
/** `<w:suff>` sits between `<w:isLgl>` and `<w:lvlText>` in a level. */
|
|
351
|
+
function setNumberSeparator(lvl) {
|
|
352
|
+
const existing = children(lvl).find((child) => child.localName === 'suff');
|
|
353
|
+
const suff = existing ?? lvl.ownerDocument.createElementNS(W_NS, 'w:suff');
|
|
354
|
+
if (!existing) {
|
|
355
|
+
const lvlText = children(lvl).find((child) => child.localName === 'lvlText');
|
|
356
|
+
lvl.insertBefore(suff, lvlText ?? null);
|
|
357
|
+
}
|
|
358
|
+
suff.setAttributeNS(W_NS, 'w:val', 'space');
|
|
359
|
+
}
|
|
360
|
+
/** The paragraph properties a numbering level carries, created when absent. */
|
|
361
|
+
function numberingParagraphOf(lvl) {
|
|
362
|
+
return childOrCreate(lvl, 'pPr', 'last');
|
|
363
|
+
}
|
|
364
|
+
/**
|
|
365
|
+
* Cells sit outside the page grid: exact spacing at the line pitch would
|
|
366
|
+
* stretch every row to a whole pitch and clip what wraps, so a cell paragraph
|
|
367
|
+
* takes its own line spacing and stops snapping to the grid (Word's 如果定义了
|
|
368
|
+
* 文档网格,则与网格对齐 checkbox, `w:snapToGrid`).
|
|
369
|
+
*/
|
|
370
|
+
function layoutTableCell(pPr, table, grid) {
|
|
371
|
+
const spacing = spacingFor(table.lineSpacing, grid);
|
|
372
|
+
const spacingElement = paragraphProperty(pPr, 'spacing');
|
|
373
|
+
spacingElement.setAttributeNS(W_NS, 'w:line', spacing.line);
|
|
374
|
+
spacingElement.setAttributeNS(W_NS, 'w:lineRule', spacing.rule);
|
|
375
|
+
paragraphProperty(pPr, 'snapToGrid').setAttributeNS(W_NS, 'w:val', table.snapToGrid ? '1' : '0');
|
|
376
|
+
}
|
|
377
|
+
/** `<w:vAlign>` in a cell's properties, created where Word writes it. */
|
|
378
|
+
function cellVerticalAlign(cell) {
|
|
379
|
+
const tcPr = childOrCreate(cell, 'tcPr', 'first');
|
|
380
|
+
const existing = children(tcPr).find((child) => child.localName === 'vAlign');
|
|
381
|
+
if (existing) {
|
|
382
|
+
return existing;
|
|
383
|
+
}
|
|
384
|
+
const created = tcPr.ownerDocument.createElementNS(W_NS, 'w:vAlign');
|
|
385
|
+
const hideMark = children(tcPr).find((child) => child.localName === 'hideMark');
|
|
386
|
+
return tcPr.insertBefore(created, hideMark ?? null);
|
|
387
|
+
}
|
|
140
388
|
/**
|
|
141
389
|
* The grid for the text block of `sectPr`'s page. Word stores the character
|
|
142
390
|
* pitch as an offset from the body font size. Both pitches are rounded down,
|