vscode-colaview 0.3.3 → 0.4.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.
Files changed (41) hide show
  1. package/.vscode/settings.json +1 -1
  2. package/CHANGELOG.md +20 -4
  3. package/README.md +310 -286
  4. package/README_CN.md +310 -286
  5. package/RELEASE_NOTES.md +36 -4
  6. package/esbuild.js +2 -0
  7. package/package.json +58 -19
  8. package/package.nls.json +14 -0
  9. package/package.nls.zh-cn.json +14 -0
  10. package/src/commands/commands.ts +48 -0
  11. package/src/docx/docx-builder.ts +241 -0
  12. package/src/export/docx-exporter.ts +961 -961
  13. package/src/export/html-exporter.ts +8 -2
  14. package/src/export/pdf-exporter.ts +65 -0
  15. package/src/export/pptx-exporter.ts +63 -0
  16. package/src/export/render-export-images.ts +386 -386
  17. package/src/export/theme-style.ts +195 -195
  18. package/src/pptx/pptx-builder.ts +249 -0
  19. package/src/pptx/zip.ts +158 -0
  20. package/src/present/presenter.ts +64 -0
  21. package/src/preview/preview-manager.ts +783 -541
  22. package/src/preview/webview/app.ts +588 -370
  23. package/src/preview/webview/index.html +167 -146
  24. package/src/slides/deck.ts +397 -0
  25. package/src/slides/markdown.ts +393 -0
  26. package/src/slides/render.ts +484 -0
  27. package/src/slides/slides.css +1082 -0
  28. package/src/themes/built-in/bear.css +89 -38
  29. package/src/themes/built-in/dark.css +87 -28
  30. package/src/themes/built-in/dracula.css +93 -34
  31. package/src/themes/built-in/elegant.css +109 -45
  32. package/src/themes/built-in/gruvbox.css +97 -38
  33. package/src/themes/built-in/light.css +80 -20
  34. package/src/themes/built-in/midnight.css +93 -35
  35. package/src/themes/built-in/nord.css +93 -34
  36. package/src/themes/built-in/notion.css +98 -46
  37. package/src/themes/built-in/sepia.css +99 -44
  38. package/src/themes/built-in/solarized-dark.css +94 -35
  39. package/src/themes/built-in/writer.css +99 -52
  40. package/src/themes/theme-manager.ts +207 -180
  41. package/src/types/colamd-renderer.d.ts +47 -47
@@ -1,962 +1,962 @@
1
- // Word (docx) 导出器 — 参考 ColaMD-extend/src/main/docx-export.ts 移植
2
- // 用 docx 库在扩展宿主内解析 Markdown(remark-parse + remark-gfm)并生成 OOXML。
3
- // 与 colamd-extend 的差异:扩展宿主是纯 Node,无 Electron nativeImage,
4
- // 图片解码/尺寸检测改用纯 JS 实现(sniffImage),截图类图片直接透传 PNG buffer。
5
- import * as vscode from 'vscode';
6
- import * as fs from 'fs';
7
- import { basename, dirname, extname, isAbsolute, resolve } from 'path';
8
- import { fileURLToPath } from 'url';
9
- // 这三个必须在 package.json 里**直接声明**(而非仅作 colamd 的传递依赖):
10
- // 曾经靠 npm 依赖提升侥幸能 load,一旦上游依赖树变动,Word 导出就会在运行时
11
- // 「模块找不到」。参照 colamd-extend 的注释。
12
- import { unified } from 'unified';
13
- import remarkParse from 'remark-parse';
14
- import remarkGfm from 'remark-gfm';
15
- import {
16
- AlignmentType,
17
- BorderStyle,
18
- Document,
19
- ExternalHyperlink,
20
- Footer,
21
- FootnoteReferenceRun,
22
- HeadingLevel,
23
- ImageRun,
24
- LevelFormat,
25
- LineRuleType,
26
- Packer,
27
- PageNumber,
28
- Paragraph,
29
- Table,
30
- TableCell,
31
- TableRow,
32
- TextRun,
33
- UnderlineType,
34
- WidthType,
35
- type IParagraphOptions,
36
- type IRunStylePropertiesOptions,
37
- type ParagraphChild,
38
- } from 'docx';
39
- import { renderMathAndMermaidToImages } from './render-export-images';
40
- import { buildDocxStyleFromThemeCss } from './theme-style';
41
- import { ThemeManager } from '../themes/theme-manager';
42
-
43
- interface MarkdownNode {
44
- type: string;
45
- value?: string;
46
- depth?: number;
47
- ordered?: boolean;
48
- start?: number;
49
- url?: string;
50
- alt?: string;
51
- align?: Array<'left' | 'center' | 'right' | null>;
52
- checked?: boolean | null;
53
- identifier?: string;
54
- label?: string;
55
- /** 列表编号实例,预扫描时写入;每个列表一个,保证编号各自重新开始。 */
56
- instance?: number;
57
- children?: MarkdownNode[];
58
- }
59
-
60
- /** 主题令牌。颜色一律不带 `#`;字体是 CSS 字体栈,落到 Word 前会挑一个具体字体名。 */
61
- export interface DocxStyle {
62
- text: string;
63
- secondaryText: string;
64
- link: string;
65
- bodyFontStack: string;
66
- monoFontStack: string;
67
- bodySize: number;
68
- lineHeight: number;
69
- inlineCodeBackground: string;
70
- codeBlockBackground: string;
71
- codeBlockText: string;
72
- highlightBackground: string;
73
- blockquoteBorder: string;
74
- blockquoteBackground: string | null;
75
- border: string;
76
- tableHeaderBackground: string;
77
- }
78
-
79
- export interface DocxExportInput {
80
- content: string;
81
- sourcePath: string | null;
82
- /** 渲染端为本次导出生成的图片(公式/示意图),keyed by Markdown 里重写后的名字。 */
83
- images?: Record<string, string>;
84
- /** 图片在 Word 里的目标尺寸(CSS 像素)。 */
85
- imageSizes?: unknown;
86
- style?: unknown;
87
- }
88
-
89
- // 没有拿到渲染进程的令牌时,仍生成一份完整的浅色文档。
90
- const DEFAULT_STYLE: DocxStyle = {
91
- text: '24292F',
92
- secondaryText: '656D76',
93
- link: '0969DA',
94
- bodyFontStack: 'Segoe UI, Helvetica, Arial, sans-serif',
95
- monoFontStack: 'Consolas, Menlo, monospace',
96
- bodySize: 16,
97
- lineHeight: 1.75,
98
- inlineCodeBackground: 'EFF1F3',
99
- codeBlockBackground: 'F6F8FA',
100
- codeBlockText: '24292F',
101
- highlightBackground: 'FFF3BF',
102
- blockquoteBorder: 'D0D7DE',
103
- blockquoteBackground: null,
104
- border: 'D0D7DE',
105
- tableHeaderBackground: 'F6F8FA',
106
- };
107
-
108
- // 与 colamd-extend themes/document.css 的字号比例一致:h1 1.9em … h5/h6 1em。
109
- const HEADING_SCALE = [1.9, 1.55, 1.3, 1.12, 1, 1];
110
-
111
- interface DocxContext {
112
- style: DocxStyle;
113
- bodyFont: string;
114
- monoFont: string;
115
- /**
116
- * 代码用的字体(含 eastAsia 槽位)。
117
- * 以前只用 `font: monoFont` 字符串:docx 会把它同时写进 w:rFonts 的 ascii / hAnsi /
118
- * cs / eastAsia 四个槽位,如果选中了 Windows 没有的字体(如 Menlo),Word 就整段
119
- * 替换,代码块变成 ♣ ○ ◇ 这类符号乱码。eastAsia 单独给一个中文字体,代码里的
120
- * 中文注释才不会乱码(镜像 colamd-extend aad3bf6 的修复)。
121
- */
122
- codeFont: { ascii: string; hAnsi: string; cs: string; eastAsia: string };
123
- bodySizeHalf: number;
124
- paragraphLine: number;
125
- codeSizeHalf: number;
126
- footnoteIds: Map<string, number>;
127
- sourcePath: string | null;
128
- images?: Record<string, string>;
129
- imageSizes?: Record<string, { width: number; height: number }>;
130
- }
131
-
132
- /** 已解码的图片(原生类型 + 字节 + 尺寸)。替代 Electron 的 NativeImage。 */
133
- interface LoadedImage {
134
- data: Buffer;
135
- type: 'png' | 'jpg' | 'gif' | 'bmp';
136
- width: number;
137
- height: number;
138
- }
139
-
140
- function hexColor(value: unknown, fallback: string): string {
141
- if (typeof value !== 'string') return fallback;
142
- const raw = value.trim().replace(/^#/, '');
143
- if (/^[0-9a-f]{3}$/i.test(raw)) return raw.split('').map((digit) => digit + digit).join('').toUpperCase();
144
- if (/^[0-9a-f]{6}$/i.test(raw)) return raw.toUpperCase();
145
- if (/^[0-9a-f]{8}$/i.test(raw)) return raw.slice(0, 6).toUpperCase();
146
- return fallback;
147
- }
148
-
149
- function stringValue(value: unknown, fallback: string): string {
150
- return typeof value === 'string' && value.trim() !== '' ? value.trim() : fallback;
151
- }
152
-
153
- function numberValue(value: unknown, fallback: number, min: number, max: number): number {
154
- return typeof value === 'number' && Number.isFinite(value) ? Math.min(max, Math.max(min, value)) : fallback;
155
- }
156
-
157
- const FRONTMATTER_MAPPING = /^[ \t]*(?:[\p{L}\p{N}_][\p{L}\p{N}_.-]*|"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*')[ \t]*:([ \t]|$)/mu;
158
-
159
- function frontmatterEnd(text: string): number {
160
- if (!text.startsWith('---')) return 0;
161
- const firstLineEnd = text.indexOf('\n');
162
- if (firstLineEnd === -1) return 0;
163
- if (text.slice(0, firstLineEnd).trim() !== '---') return 0;
164
- const rest = text.slice(firstLineEnd + 1);
165
- const close = /^(?:---|\.\.\.)[ \t]*$/m.exec(rest);
166
- if (!close) return 0;
167
- const body = rest.slice(0, close.index);
168
- if (!FRONTMATTER_MAPPING.test(body)) return 0;
169
- return firstLineEnd + 1 + close.index + close[0].length;
170
- }
171
-
172
- function normalizeImageSizes(raw: unknown): Record<string, { width: number; height: number }> | undefined {
173
- if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;
174
- const sizes: Record<string, { width: number; height: number }> = {};
175
- for (const [name, value] of Object.entries(raw as Record<string, unknown>)) {
176
- if (!value || typeof value !== 'object') continue;
177
- const width = (value as { width?: unknown }).width;
178
- const height = (value as { height?: unknown }).height;
179
- if (
180
- typeof width === 'number' && Number.isFinite(width) && width > 0
181
- && typeof height === 'number' && Number.isFinite(height) && height > 0
182
- ) {
183
- sizes[name] = { width: Math.min(4000, width), height: Math.min(4000, height) };
184
- }
185
- }
186
- return Object.keys(sizes).length > 0 ? sizes : undefined;
187
- }
188
-
189
- function normalizeStyle(raw: unknown): DocxStyle {
190
- const source = typeof raw === 'object' && raw !== null ? raw as Record<string, unknown> : {};
191
- const blockquoteBackground = typeof source.blockquoteBackground === 'string'
192
- ? hexColor(source.blockquoteBackground, '')
193
- : '';
194
- return {
195
- text: hexColor(source.text, DEFAULT_STYLE.text),
196
- secondaryText: hexColor(source.secondaryText, DEFAULT_STYLE.secondaryText),
197
- link: hexColor(source.link, DEFAULT_STYLE.link),
198
- bodyFontStack: stringValue(source.bodyFontStack, DEFAULT_STYLE.bodyFontStack),
199
- monoFontStack: stringValue(source.monoFontStack, DEFAULT_STYLE.monoFontStack),
200
- bodySize: numberValue(source.bodySize, DEFAULT_STYLE.bodySize, 8, 40),
201
- lineHeight: numberValue(source.lineHeight, DEFAULT_STYLE.lineHeight, 1, 3),
202
- inlineCodeBackground: hexColor(source.inlineCodeBackground, DEFAULT_STYLE.inlineCodeBackground),
203
- codeBlockBackground: hexColor(source.codeBlockBackground, DEFAULT_STYLE.codeBlockBackground),
204
- codeBlockText: hexColor(source.codeBlockText, DEFAULT_STYLE.codeBlockText),
205
- highlightBackground: hexColor(source.highlightBackground, DEFAULT_STYLE.highlightBackground),
206
- blockquoteBorder: hexColor(source.blockquoteBorder, DEFAULT_STYLE.blockquoteBorder),
207
- blockquoteBackground: blockquoteBackground !== '' ? blockquoteBackground : null,
208
- border: hexColor(source.border, DEFAULT_STYLE.border),
209
- tableHeaderBackground: hexColor(source.tableHeaderBackground, DEFAULT_STYLE.tableHeaderBackground),
210
- };
211
- }
212
-
213
- /** 从 CSS 字体栈里挑一个 Word 认得的字体名。 */
214
- function fontName(stack: string, mono: boolean): string {
215
- const generic = new Set([
216
- 'serif', 'sans-serif', 'monospace', 'system-ui', 'ui-sans-serif', 'ui-monospace',
217
- 'cursive', 'fantasy', '-apple-system', 'blinkmacsystemfont',
218
- ]);
219
- const families = stack
220
- .split(',')
221
- .map((family) => family.trim().replace(/^["']|["']$/g, ''))
222
- .filter((family) => family !== '' && !generic.has(family.toLowerCase()));
223
-
224
- const platform = process.platform;
225
- const preferred = mono
226
- ? platform === 'win32'
227
- ? ['consolas', 'cascadia code', 'fira code', 'menlo']
228
- : platform === 'darwin'
229
- ? ['sf mono', 'menlo', 'fira code', 'consolas']
230
- : ['dejavu sans mono', 'liberation mono', 'noto sans mono']
231
- : platform === 'win32'
232
- ? ['segoe ui', 'microsoft yahei', 'noto sans']
233
- : platform === 'darwin'
234
- ? ['helvetica neue', 'helvetica', 'noto sans']
235
- : ['noto sans', 'dejavu sans'];
236
-
237
- for (const name of preferred) {
238
- const hit = families.find((family) => family.toLowerCase() === name);
239
- if (hit) return hit;
240
- }
241
- if (families[0]) return families[0];
242
- if (mono) return platform === 'win32' ? 'Consolas' : platform === 'darwin' ? 'Menlo' : 'DejaVu Sans Mono';
243
- return platform === 'win32' ? 'Segoe UI' : platform === 'darwin' ? 'Helvetica Neue' : 'Noto Sans';
244
- }
245
-
246
- /** px → Word 的半磅值。 */
247
- function halfPoints(px: number): number {
248
- return Math.max(2, Math.round(px * 1.5));
249
- }
250
-
251
- /** 代码的 eastAsia 中文字体:按平台选一个 Word 认得的(镜像 colamd-extend aad3bf6)。 */
252
- function codeEastAsiaFont(): string {
253
- return process.platform === 'darwin'
254
- ? 'PingFang SC'
255
- : process.platform === 'win32'
256
- ? 'Microsoft YaHei'
257
- : 'Noto Sans CJK SC';
258
- }
259
-
260
- /** em 距离 → twips(1px = 15 twips)。 */
261
- function emTwips(px: number, em: number): number {
262
- return Math.round(px * em * 15);
263
- }
264
-
265
- function headingForDepth(depth: number): (typeof HeadingLevel)[keyof typeof HeadingLevel] {
266
- const headings = [
267
- HeadingLevel.HEADING_1,
268
- HeadingLevel.HEADING_2,
269
- HeadingLevel.HEADING_3,
270
- HeadingLevel.HEADING_4,
271
- HeadingLevel.HEADING_5,
272
- HeadingLevel.HEADING_6,
273
- ];
274
- return headings[Math.max(0, Math.min(5, depth - 1))] as (typeof HeadingLevel)[keyof typeof HeadingLevel];
275
- }
276
-
277
- function textContent(node: MarkdownNode): string {
278
- if (node.type === 'text' || node.type === 'inlineCode' || node.type === 'code') return node.value ?? '';
279
- if (node.type === 'break') return '\n';
280
- return node.children?.map(textContent).join('') ?? '';
281
- }
282
-
283
- /**
284
- * 纯 JS 识别图片字节类型并读取宽高(替代 nativeImage.getSize())。
285
- * 支持 PNG/JPEG/GIF/BMP;返回 null 表示无法识别(如 SVG)。
286
- */
287
- function sniffImage(buf: Buffer): { type: LoadedImage['type']; width: number; height: number } | null {
288
- if (!buf || buf.length < 24) return null;
289
- // PNG
290
- if (buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) {
291
- return { type: 'png', width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
292
- }
293
- // JPEG
294
- if (buf[0] === 0xff && buf[1] === 0xd8) {
295
- let i = 2;
296
- while (i + 9 < buf.length) {
297
- if (buf[i] !== 0xff) { i += 1; continue; }
298
- const marker = buf[i + 1];
299
- if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {
300
- return { type: 'jpg', width: buf.readUInt16BE(i + 7), height: buf.readUInt16BE(i + 5) };
301
- }
302
- const size = buf.readUInt16BE(i + 2);
303
- i += 2 + size;
304
- }
305
- return null;
306
- }
307
- // GIF
308
- const gifSig = buf.toString('ascii', 0, 6);
309
- if (gifSig === 'GIF87a' || gifSig === 'GIF89a') {
310
- return { type: 'gif', width: buf.readUInt16LE(6), height: buf.readUInt16LE(8) };
311
- }
312
- // BMP
313
- if (buf.toString('ascii', 0, 2) === 'BM') {
314
- return { type: 'bmp', width: Math.abs(buf.readInt32LE(18)), height: Math.abs(buf.readInt32LE(22)) };
315
- }
316
- return null;
317
- }
318
-
319
- function dataUrlToImage(dataURL: string): LoadedImage | null {
320
- const m = /^data:image\/[a-z0-9.+-]+;base64,([A-Za-z0-9+/=]+)$/i.exec(dataURL);
321
- if (!m) return null;
322
- const buffer = Buffer.from(m[1], 'base64');
323
- const dims = sniffImage(buffer);
324
- if (!dims) return null;
325
- return { data: buffer, ...dims };
326
- }
327
-
328
- function fileToImage(path: string): LoadedImage | null {
329
- try {
330
- const data = fs.readFileSync(path);
331
- const dims = sniffImage(data);
332
- if (!dims) return null;
333
- return { data, ...dims };
334
- } catch {
335
- return null;
336
- }
337
- }
338
-
339
- /** `==高亮==` 的底纹 run 拆分。 */
340
- function textRuns(text: string, context: DocxContext, style: IRunStylePropertiesOptions): ParagraphChild[] {
341
- if (!text.includes('==')) return [new TextRun({ text, ...style })];
342
- const runs: ParagraphChild[] = [];
343
- const pattern = /==([^=\n]+)==/g;
344
- let cursor = 0;
345
- for (const match of text.matchAll(pattern)) {
346
- const index = match.index ?? 0;
347
- if (index > cursor) runs.push(new TextRun({ text: text.slice(cursor, index), ...style }));
348
- runs.push(new TextRun({
349
- text: match[1] ?? '',
350
- ...style,
351
- shading: { fill: context.style.highlightBackground },
352
- }));
353
- cursor = index + match[0].length;
354
- }
355
- if (cursor === 0) return [new TextRun({ text, ...style })];
356
- if (cursor < text.length) runs.push(new TextRun({ text: text.slice(cursor), ...style }));
357
- return runs;
358
- }
359
-
360
- function loadImage(node: MarkdownNode, context: DocxContext): { image: LoadedImage; target?: { width: number; height: number } } | null {
361
- const inlineData = node.url && /^data:image\//i.test(node.url) ? node.url : undefined;
362
- const dataURL = node.url ? (context.images?.[node.url] ?? inlineData) : undefined;
363
- const image = dataURL
364
- ? dataUrlToImage(dataURL)
365
- : (() => {
366
- const p = node.url ? imagePath(node.url, context.sourcePath) : null;
367
- return p ? fileToImage(p) : null;
368
- })();
369
- if (!image) return null;
370
- return { image, target: node.url ? context.imageSizes?.[node.url] : undefined };
371
- }
372
-
373
- function imageSize(
374
- image: LoadedImage,
375
- target?: { width: number; height: number },
376
- targetMax: { width: number; height: number } = { width: 600, height: 420 },
377
- ): { width: number; height: number } {
378
- if (target) {
379
- const scale = Math.min(1, targetMax.width / target.width, targetMax.height / target.height);
380
- return {
381
- width: Math.max(1, Math.round(target.width * scale)),
382
- height: Math.max(1, Math.round(target.height * scale)),
383
- };
384
- }
385
- const scale = Math.min(1, 560 / image.width, 420 / image.height);
386
- return {
387
- width: Math.max(1, Math.round(image.width * scale)),
388
- height: Math.max(1, Math.round(image.height * scale)),
389
- };
390
- }
391
-
392
- function inlineRuns(
393
- nodes: MarkdownNode[] | undefined,
394
- context: DocxContext,
395
- style: IRunStylePropertiesOptions = {},
396
- ): ParagraphChild[] {
397
- if (!nodes) return [];
398
- const runs: ParagraphChild[] = [];
399
- for (const node of nodes) {
400
- if (node.type === 'text') {
401
- runs.push(...textRuns(node.value ?? '', context, style));
402
- } else if (node.type === 'break') {
403
- runs.push(new TextRun({ break: 1, ...style }));
404
- } else if (node.type === 'inlineCode') {
405
- runs.push(new TextRun({
406
- text: node.value ?? '',
407
- font: context.codeFont,
408
- size: context.codeSizeHalf,
409
- shading: { fill: context.style.inlineCodeBackground },
410
- noProof: true, // 变量名不再带拼写红波浪线
411
- ...style,
412
- }));
413
- } else if (node.type === 'strong') {
414
- runs.push(...inlineRuns(node.children, context, { ...style, bold: true }));
415
- } else if (node.type === 'emphasis') {
416
- runs.push(...inlineRuns(node.children, context, { ...style, italics: true }));
417
- } else if (node.type === 'delete') {
418
- runs.push(...inlineRuns(node.children, context, { ...style, strike: true }));
419
- } else if (node.type === 'link' && node.url) {
420
- runs.push(new ExternalHyperlink({
421
- link: node.url,
422
- children: inlineRuns(node.children, context, {
423
- ...style,
424
- color: context.style.link,
425
- underline: { type: UnderlineType.SINGLE },
426
- }),
427
- }));
428
- } else if (node.type === 'footnoteReference') {
429
- const id = node.identifier ? context.footnoteIds.get(node.identifier) : undefined;
430
- runs.push(id
431
- ? new FootnoteReferenceRun(id)
432
- : new TextRun({ text: node.label ?? '', superScript: true }));
433
- } else if (node.type === 'html') {
434
- const value = node.value ?? '';
435
- if (/^<br\b/i.test(value)) {
436
- runs.push(new TextRun({ break: 1, ...style }));
437
- } else {
438
- const img = /^<img\b[^>]*?\bsrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(value);
439
- if (img) {
440
- const url = img[1] ?? img[2] ?? img[3] ?? '';
441
- const altMatch = /\balt\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(value);
442
- const alt = altMatch?.[1] ?? altMatch?.[2] ?? altMatch?.[3] ?? '';
443
- const loaded = loadImage({ type: 'image', url, alt }, context);
444
- if (loaded) {
445
- runs.push(new ImageRun({
446
- type: loaded.image.type,
447
- data: loaded.image.data,
448
- transformation: imageSize(loaded.image, loaded.target),
449
- altText: alt ? { name: alt } : undefined,
450
- }));
451
- }
452
- }
453
- }
454
- } else if (node.type === 'image') {
455
- const loaded = loadImage(node, context);
456
- if (loaded) {
457
- runs.push(new ImageRun({
458
- type: loaded.image.type,
459
- data: loaded.image.data,
460
- transformation: imageSize(loaded.image, loaded.target),
461
- altText: node.alt ? { name: node.alt } : undefined,
462
- }));
463
- } else {
464
- runs.push(new TextRun({
465
- text: node.alt ? `[${node.alt}]` : '[image]',
466
- italics: true,
467
- color: context.style.secondaryText,
468
- ...style,
469
- }));
470
- }
471
- } else {
472
- runs.push(...inlineRuns(node.children, context, style));
473
- }
474
- }
475
- return runs;
476
- }
477
-
478
- function imagePath(url: string, sourcePath: string | null): string | null {
479
- if (/^(https?:|data:|blob:)/i.test(url)) return null;
480
- try {
481
- if (url.startsWith('file:')) return fileURLToPath(url);
482
- } catch {
483
- return null;
484
- }
485
- if (!sourcePath) return null;
486
- return isAbsolute(url) ? url : resolve(dirname(sourcePath), decodeURIComponent(url));
487
- }
488
-
489
- const REMOTE_TIMEOUT_MS = 15000;
490
- const REMOTE_MAX_BYTES = 20 * 1024 * 1024;
491
-
492
- /** 远程图片:下载后保留原始字节,失败返回 null。 */
493
- async function downloadImage(url: string): Promise<string | null> {
494
- try {
495
- const response = await fetch(url, {
496
- signal: AbortSignal.timeout(REMOTE_TIMEOUT_MS),
497
- headers: { 'User-Agent': 'ColaView', Accept: 'image/*' },
498
- });
499
- if (!response.ok) return null;
500
- const declared = Number(response.headers.get('content-length') ?? 0);
501
- if (declared > REMOTE_MAX_BYTES) return null;
502
- const buffer = Buffer.from(await response.arrayBuffer());
503
- if (buffer.length === 0 || buffer.length > REMOTE_MAX_BYTES) return null;
504
- if (!sniffImage(buffer)) return null;
505
- const contentType = (response.headers.get('content-type') ?? 'image/png').split(';')[0].trim();
506
- return `data:${contentType};base64,${buffer.toString('base64')}`;
507
- } catch {
508
- return null;
509
- }
510
- }
511
-
512
- function collectRemoteImageUrls(nodes: MarkdownNode[] | undefined, urls: Set<string>): void {
513
- for (const node of nodes ?? []) {
514
- if (node.type === 'image' && node.url && /^https?:/i.test(node.url)) urls.add(node.url);
515
- if (node.type === 'html' && node.value) {
516
- const img = /<img\b[^>]*\bsrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(node.value);
517
- const src = img?.[1] ?? img?.[2] ?? img?.[3];
518
- if (src && /^https?:/i.test(src)) urls.add(src);
519
- }
520
- collectRemoteImageUrls(node.children, urls);
521
- }
522
- }
523
-
524
- async function remoteImagesFor(tree: MarkdownNode): Promise<Record<string, string>> {
525
- const urls = new Set<string>();
526
- collectRemoteImageUrls(tree.children, urls);
527
- if (urls.size === 0) return {};
528
- const entries = await Promise.all([...urls].map(async (url) => [url, await downloadImage(url)] as const));
529
- return Object.fromEntries(entries.filter((entry): entry is readonly [string, string] => entry[1] !== null));
530
- }
531
-
532
- function imageParagraph(node: MarkdownNode, context: DocxContext): Paragraph {
533
- const loaded = loadImage(node, context);
534
- if (!loaded) {
535
- return new Paragraph({
536
- children: [new TextRun({ text: node.alt ? `[${node.alt}]` : '[image]', italics: true })],
537
- });
538
- }
539
- const url = node.url ?? '';
540
- const size = imageSize(
541
- loaded.image,
542
- loaded.target,
543
- /colamd-html-/.test(url) ? { width: 600, height: 800 } : undefined,
544
- );
545
- return new Paragraph({
546
- alignment: AlignmentType.CENTER,
547
- spacing: { before: emTwips(context.style.bodySize, 1.2), after: emTwips(context.style.bodySize, 1.2) },
548
- children: [new ImageRun({
549
- type: loaded.image.type,
550
- data: loaded.image.data,
551
- transformation: size,
552
- altText: node.alt ? { name: node.alt } : undefined,
553
- })],
554
- });
555
- }
556
-
557
- function alignmentFor(align: string | null | undefined): (typeof AlignmentType)[keyof typeof AlignmentType] {
558
- if (align === 'center') return AlignmentType.CENTER;
559
- if (align === 'right') return AlignmentType.RIGHT;
560
- return AlignmentType.LEFT;
561
- }
562
-
563
- function tableForNode(node: MarkdownNode, context: DocxContext): Table {
564
- const border = { style: BorderStyle.SINGLE, size: 6, color: context.style.border };
565
- return new Table({
566
- width: { size: 100, type: WidthType.PERCENTAGE },
567
- borders: {
568
- top: border,
569
- bottom: border,
570
- left: border,
571
- right: border,
572
- insideHorizontal: border,
573
- insideVertical: border,
574
- },
575
- rows: (node.children ?? []).map((row, rowIndex) => new TableRow({
576
- tableHeader: rowIndex === 0,
577
- children: (row.children ?? []).map((cell, cellIndex) => new TableCell({
578
- shading: rowIndex === 0 ? { fill: context.style.tableHeaderBackground } : undefined,
579
- margins: { top: 120, bottom: 120, left: 180, right: 180 },
580
- children: [new Paragraph({
581
- alignment: alignmentFor(node.align?.[cellIndex]),
582
- spacing: { before: 0, after: 0, line: 240, lineRule: LineRuleType.AUTO },
583
- children: inlineRuns(cell.children, context, rowIndex === 0 ? { bold: true } : {}),
584
- })],
585
- })),
586
- })),
587
- });
588
- }
589
-
590
- function codeParagraph(node: MarkdownNode, context: DocxContext, extra: IParagraphOptions = {}): Paragraph {
591
- // 每一行自己一个 run,行间用 `<w:br/>`;空行也要留一个 break,不然空行会被吃掉。
592
- const lines = (node.value ?? '').replace(/\n+$/, '').split('\n');
593
- const children: ParagraphChild[] = lines.map((line, index) => (
594
- line === ''
595
- ? new TextRun({ text: '', break: 1 })
596
- : new TextRun({
597
- text: line,
598
- break: index > 0 ? 1 : undefined,
599
- font: context.codeFont,
600
- size: context.codeSizeHalf,
601
- color: context.style.codeBlockText,
602
- noProof: true, // 变量名不再带拼写红波浪线
603
- })
604
- ));
605
- const codeLine = Math.round(context.style.bodySize * 0.875 * 1.6 * 15);
606
- const codePad = emTwips(context.style.bodySize, 1.0);
607
- const codeBorder = { color: context.style.border, space: 4, style: BorderStyle.SINGLE, size: 4 };
608
- return new Paragraph({
609
- ...extra,
610
- // 显式左对齐:不写的话继承默认样式,默认是两端对齐时每一行都会被拉满行宽,
611
- // 键留在左边、值被顶到右边(镜像 colamd-extend aad3bf6)。
612
- alignment: AlignmentType.LEFT,
613
- shading: { fill: context.style.codeBlockBackground },
614
- spacing: { before: codePad, after: codePad, line: codeLine, lineRule: LineRuleType.AT_LEAST },
615
- border: {
616
- top: codeBorder,
617
- bottom: codeBorder,
618
- left: codeBorder,
619
- right: codeBorder,
620
- },
621
- children,
622
- });
623
- }
624
-
625
- function blockquoteNodes(
626
- node: MarkdownNode,
627
- context: DocxContext,
628
- ): Array<Paragraph | Table> {
629
- const quote: IParagraphOptions = {
630
- border: {
631
- left: { color: context.style.blockquoteBorder, space: 12, style: BorderStyle.SINGLE, size: 24 },
632
- },
633
- indent: { left: 240 },
634
- shading: context.style.blockquoteBackground ? { fill: context.style.blockquoteBackground } : undefined,
635
- spacing: { after: emTwips(context.style.bodySize, 0.5) },
636
- };
637
- const childStyle: IRunStylePropertiesOptions = { color: context.style.secondaryText };
638
- const output: Array<Paragraph | Table> = [];
639
-
640
- for (const child of node.children ?? []) {
641
- if (child.type === 'paragraph' || child.type === 'heading') {
642
- output.push(new Paragraph({ ...quote, children: inlineRuns(child.children, context, childStyle) }));
643
- } else if (child.type === 'list') {
644
- const start = child.start ?? 1;
645
- for (const [index, item] of (child.children ?? []).entries()) {
646
- const first = item.children?.find((entry) => entry.type === 'paragraph');
647
- const prefix = child.ordered ? `${start + index}. ` : '• ';
648
- output.push(new Paragraph({
649
- ...quote,
650
- indent: { left: 600, hanging: 240 },
651
- children: [
652
- new TextRun({ text: prefix, ...childStyle }),
653
- ...inlineRuns(first?.children, context, childStyle),
654
- ],
655
- }));
656
- }
657
- } else if (child.type === 'code') {
658
- output.push(codeParagraph(child, context, quote));
659
- } else if (child.type === 'thematicBreak') {
660
- output.push(new Paragraph({
661
- ...quote,
662
- border: { bottom: { color: context.style.border, space: 1, style: BorderStyle.SINGLE, size: 6 } },
663
- }));
664
- } else {
665
- output.push(new Paragraph({
666
- ...quote,
667
- children: [new TextRun({ text: textContent(child), ...childStyle })],
668
- }));
669
- }
670
- }
671
- return output;
672
- }
673
-
674
- function prepareLists(nodes: MarkdownNode[] | undefined, state: { next: number; starts: Set<number> }): void {
675
- for (const node of nodes ?? []) {
676
- if (node.type === 'list') {
677
- node.instance = state.next;
678
- state.next += 1;
679
- if (node.ordered) state.starts.add(node.start ?? 1);
680
- }
681
- prepareLists(node.children, state);
682
- }
683
- }
684
-
685
- function bulletLevels() {
686
- const marks = ['•', '○', '■'];
687
- return Array.from({ length: 9 }, (_, level) => ({
688
- level,
689
- format: LevelFormat.BULLET,
690
- text: marks[level % marks.length],
691
- alignment: AlignmentType.LEFT,
692
- style: { paragraph: { indent: { left: 360 + level * 360, hanging: 240 } } },
693
- }));
694
- }
695
-
696
- function decimalLevels(start: number) {
697
- return Array.from({ length: 9 }, (_, level) => ({
698
- level,
699
- format: LevelFormat.DECIMAL,
700
- text: `%${level + 1}.`,
701
- alignment: AlignmentType.LEFT,
702
- ...(level === 0 ? { start } : {}),
703
- style: { paragraph: { indent: { left: 360 + level * 360, hanging: 240 } } },
704
- }));
705
- }
706
-
707
- function numberingConfig(starts: Set<number>) {
708
- return {
709
- config: [
710
- { reference: 'bullet', levels: bulletLevels() },
711
- ...[...starts].sort((left, right) => left - right).map((start) => ({
712
- reference: `ordered-${start}`,
713
- levels: decimalLevels(start),
714
- })),
715
- ],
716
- };
717
- }
718
-
719
- function prepareFootnotes(nodes: MarkdownNode[] | undefined, ids: Map<string, number>): void {
720
- for (const node of nodes ?? []) {
721
- if (node.type === 'footnoteDefinition') continue;
722
- if (node.type === 'footnoteReference' && node.identifier && !ids.has(node.identifier)) {
723
- ids.set(node.identifier, ids.size + 1);
724
- }
725
- prepareFootnotes(node.children, ids);
726
- }
727
- }
728
-
729
- function blockNodes(
730
- nodes: MarkdownNode[] | undefined,
731
- context: DocxContext,
732
- listDepth = 0,
733
- ): Array<Paragraph | Table> {
734
- if (!nodes) return [];
735
- const output: Array<Paragraph | Table> = [];
736
- for (const node of nodes) {
737
- if (node.type === 'heading') {
738
- output.push(new Paragraph({ heading: headingForDepth(node.depth ?? 1), children: inlineRuns(node.children, context) }));
739
- } else if (node.type === 'paragraph') {
740
- const image = node.children?.length === 1 && node.children[0]?.type === 'image' ? node.children[0] : null;
741
- output.push(image
742
- ? imageParagraph(image, context)
743
- : new Paragraph({ children: inlineRuns(node.children, context) }));
744
- } else if (node.type === 'image') {
745
- output.push(imageParagraph(node, context));
746
- } else if (node.type === 'blockquote') {
747
- output.push(...blockquoteNodes(node, context));
748
- } else if (node.type === 'code') {
749
- output.push(codeParagraph(node, context));
750
- } else if (node.type === 'list') {
751
- const start = node.start ?? 1;
752
- for (const item of (node.children ?? [])) {
753
- const first = item.children?.find((child) => child.type === 'paragraph');
754
- const itemSpacing = {
755
- before: 0,
756
- after: emTwips(context.style.bodySize, 0.3),
757
- line: context.paragraphLine,
758
- lineRule: LineRuleType.AT_LEAST,
759
- };
760
- if (typeof item.checked === 'boolean') {
761
- output.push(new Paragraph({
762
- children: [
763
- new TextRun({
764
- text: item.checked ? '☑ ' : '☐ ',
765
- color: item.checked ? context.style.link : context.style.secondaryText,
766
- }),
767
- ...inlineRuns(first?.children, context),
768
- ],
769
- indent: { left: 360 + listDepth * 360, hanging: 240 },
770
- spacing: itemSpacing,
771
- }));
772
- } else {
773
- output.push(new Paragraph({
774
- children: inlineRuns(first?.children, context),
775
- numbering: node.ordered
776
- ? { reference: `ordered-${start}`, level: listDepth, instance: node.instance ?? 0 }
777
- : { reference: 'bullet', level: listDepth, instance: 0 },
778
- spacing: itemSpacing,
779
- }));
780
- }
781
- output.push(...blockNodes(item.children?.filter((child) => child !== first), context, listDepth + 1));
782
- }
783
- } else if (node.type === 'table') {
784
- output.push(tableForNode(node, context));
785
- } else if (node.type === 'thematicBreak') {
786
- output.push(new Paragraph({ border: { bottom: { color: context.style.border, space: 1, style: BorderStyle.SINGLE, size: 6 } } }));
787
- } else if (node.type === 'html') {
788
- output.push(new Paragraph({
789
- children: [new TextRun({ text: node.value ?? '', font: context.monoFont, size: context.codeSizeHalf, color: context.style.secondaryText })],
790
- }));
791
- } else if (node.type === 'footnoteDefinition') {
792
- continue;
793
- } else {
794
- output.push(...blockNodes(node.children, context, listDepth));
795
- }
796
- }
797
- return output;
798
- }
799
-
800
- function buildFootnotes(
801
- tree: MarkdownNode,
802
- context: DocxContext,
803
- ): Record<string, { children: Paragraph[] }> | undefined {
804
- const definitions = (tree.children ?? []).filter((node) => (
805
- node.type === 'footnoteDefinition' && node.identifier && context.footnoteIds.has(node.identifier)
806
- ));
807
- if (definitions.length === 0) return undefined;
808
-
809
- const footnotes: Record<string, { children: Paragraph[] }> = {};
810
- for (const definition of definitions) {
811
- const id = context.footnoteIds.get(definition.identifier ?? '');
812
- if (!id) continue;
813
- const children = blockNodes(definition.children, context)
814
- .filter((child): child is Paragraph => child instanceof Paragraph);
815
- footnotes[String(id)] = { children: children.length > 0 ? children : [new Paragraph({ children: [] })] };
816
- }
817
- return footnotes;
818
- }
819
-
820
- function documentStyles(context: DocxContext) {
821
- const font = {
822
- ascii: context.bodyFont,
823
- hAnsi: context.bodyFont,
824
- eastAsia: context.bodyFont,
825
- cs: context.bodyFont,
826
- };
827
- const footnoteLine = Math.round(context.style.bodySize * 0.875 * 1.6 * 15);
828
- const bodyPadAfter = emTwips(context.style.bodySize, 0.75);
829
- const bodyPadBefore = Math.round(bodyPadAfter * 0.33);
830
- const heading = (level: number) => {
831
- const px = context.style.bodySize * HEADING_SCALE[level - 1];
832
- return {
833
- run: { bold: true, color: context.style.text, size: halfPoints(px) },
834
- paragraph: {
835
- outlineLevel: level - 1,
836
- keepNext: true,
837
- keepLines: true,
838
- spacing: {
839
- before: emTwips(px, 1.4),
840
- after: emTwips(px, 0.6),
841
- line: emTwips(px, 1.35),
842
- lineRule: LineRuleType.AT_LEAST,
843
- },
844
- },
845
- };
846
- };
847
-
848
- return {
849
- default: {
850
- document: {
851
- run: { font, size: context.bodySizeHalf, color: context.style.text },
852
- paragraph: {
853
- spacing: {
854
- line: context.paragraphLine,
855
- lineRule: LineRuleType.AT_LEAST,
856
- before: bodyPadBefore,
857
- after: bodyPadAfter,
858
- },
859
- },
860
- },
861
- heading1: heading(1),
862
- heading2: heading(2),
863
- heading3: heading(3),
864
- heading4: heading(4),
865
- heading5: heading(5),
866
- heading6: heading(6),
867
- footnoteText: {
868
- run: { size: context.codeSizeHalf, color: context.style.secondaryText },
869
- paragraph: {
870
- spacing: { after: 60, line: footnoteLine, lineRule: LineRuleType.AT_LEAST },
871
- },
872
- },
873
- },
874
- };
875
- }
876
-
877
- export async function markdownToDocx(input: DocxExportInput): Promise<Buffer> {
878
- const style = normalizeStyle(input.style);
879
- const source = input.content;
880
- const frontmatter = frontmatterEnd(source);
881
- const body = frontmatter > 0 ? source.slice(frontmatter) : source;
882
- const tree = unified()
883
- .use(remarkParse)
884
- .use(remarkGfm)
885
- .parse(body) as unknown as MarkdownNode;
886
-
887
- const footnoteIds = new Map<string, number>();
888
- prepareFootnotes(tree.children, footnoteIds);
889
- const listState = { next: 0, starts: new Set<number>() };
890
- prepareLists(tree.children, listState);
891
- const remoteImages = await remoteImagesFor(tree);
892
-
893
- const monoFont = fontName(style.monoFontStack, true);
894
- const context: DocxContext = {
895
- style,
896
- bodyFont: fontName(style.bodyFontStack, false),
897
- monoFont,
898
- codeFont: {
899
- ascii: monoFont,
900
- hAnsi: monoFont,
901
- cs: monoFont,
902
- eastAsia: codeEastAsiaFont(),
903
- },
904
- bodySizeHalf: halfPoints(style.bodySize),
905
- paragraphLine: Math.round(style.lineHeight * style.bodySize * 15),
906
- codeSizeHalf: halfPoints(style.bodySize * 0.875),
907
- footnoteIds,
908
- sourcePath: input.sourcePath,
909
- images: { ...remoteImages, ...input.images },
910
- imageSizes: normalizeImageSizes(input.imageSizes),
911
- };
912
-
913
- const footnotes = buildFootnotes(tree, context);
914
- const pageNumber = new TextRun({
915
- children: [PageNumber.CURRENT, ' / ', PageNumber.TOTAL_PAGES],
916
- size: context.codeSizeHalf,
917
- color: style.secondaryText,
918
- });
919
-
920
- const document = new Document({
921
- creator: 'ColaView',
922
- title: input.sourcePath ? basename(input.sourcePath, extname(input.sourcePath)) : 'Untitled',
923
- styles: documentStyles(context),
924
- numbering: numberingConfig(listState.starts),
925
- ...(footnotes ? { footnotes } : {}),
926
- sections: [{
927
- footers: {
928
- default: new Footer({
929
- children: [new Paragraph({ alignment: AlignmentType.CENTER, children: [pageNumber] })],
930
- }),
931
- },
932
- children: blockNodes(tree.children, context),
933
- }],
934
- });
935
- return Packer.toBuffer(document);
936
- }
937
-
938
- /**
939
- * 导出当前 Markdown 文档为 Word (.docx)。
940
- * 纯宿主转换:先渲染公式/Mermaid 为 PNG 并重写 Markdown,再生成 docx。
941
- */
942
- export async function exportWord(document: vscode.TextDocument): Promise<void> {
943
- const markdown = document.getText();
944
- const sourcePath = document.fileName;
945
-
946
- // 先取主题令牌:Mermaid 图的配色跟随当前预览主题(浅色跟随、深色回落浅色),
947
- // 再用同一份令牌构建 Word 文档样式,两边保持一致。
948
- const themeCss = ThemeManager.loadThemeCSS(ThemeManager.getCurrentTheme());
949
- const style = buildDocxStyleFromThemeCss(themeCss);
950
- const { content, images, imageSizes } = await renderMathAndMermaidToImages(markdown, style);
951
- const buffer = await markdownToDocx({ content, sourcePath, images, imageSizes, style });
952
-
953
- const defaultName = document.fileName.replace(/\.md$/i, '.docx');
954
- const uri = await vscode.window.showSaveDialog({
955
- defaultUri: vscode.Uri.file(defaultName),
956
- filters: { 'Word Document': ['docx'] },
957
- });
958
- if (!uri) return;
959
-
960
- await vscode.workspace.fs.writeFile(uri, buffer);
961
- vscode.window.showInformationMessage(`Exported to ${uri.fsPath}`);
1
+ // Word (docx) 导出器 — 参考 ColaMD-extend/src/main/docx-export.ts 移植
2
+ // 用 docx 库在扩展宿主内解析 Markdown(remark-parse + remark-gfm)并生成 OOXML。
3
+ // 与 colamd-extend 的差异:扩展宿主是纯 Node,无 Electron nativeImage,
4
+ // 图片解码/尺寸检测改用纯 JS 实现(sniffImage),截图类图片直接透传 PNG buffer。
5
+ import * as vscode from 'vscode';
6
+ import * as fs from 'fs';
7
+ import { basename, dirname, extname, isAbsolute, resolve } from 'path';
8
+ import { fileURLToPath } from 'url';
9
+ // 这三个必须在 package.json 里**直接声明**(而非仅作 colamd 的传递依赖):
10
+ // 曾经靠 npm 依赖提升侥幸能 load,一旦上游依赖树变动,Word 导出就会在运行时
11
+ // 「模块找不到」。参照 colamd-extend 的注释。
12
+ import { unified } from 'unified';
13
+ import remarkParse from 'remark-parse';
14
+ import remarkGfm from 'remark-gfm';
15
+ import {
16
+ AlignmentType,
17
+ BorderStyle,
18
+ Document,
19
+ ExternalHyperlink,
20
+ Footer,
21
+ FootnoteReferenceRun,
22
+ HeadingLevel,
23
+ ImageRun,
24
+ LevelFormat,
25
+ LineRuleType,
26
+ Packer,
27
+ PageNumber,
28
+ Paragraph,
29
+ Table,
30
+ TableCell,
31
+ TableRow,
32
+ TextRun,
33
+ UnderlineType,
34
+ WidthType,
35
+ type IParagraphOptions,
36
+ type IRunStylePropertiesOptions,
37
+ type ParagraphChild,
38
+ } from 'docx';
39
+ import { renderMathAndMermaidToImages } from './render-export-images';
40
+ import { buildDocxStyleFromThemeCss } from './theme-style';
41
+ import { ThemeManager } from '../themes/theme-manager';
42
+
43
+ interface MarkdownNode {
44
+ type: string;
45
+ value?: string;
46
+ depth?: number;
47
+ ordered?: boolean;
48
+ start?: number;
49
+ url?: string;
50
+ alt?: string;
51
+ align?: Array<'left' | 'center' | 'right' | null>;
52
+ checked?: boolean | null;
53
+ identifier?: string;
54
+ label?: string;
55
+ /** 列表编号实例,预扫描时写入;每个列表一个,保证编号各自重新开始。 */
56
+ instance?: number;
57
+ children?: MarkdownNode[];
58
+ }
59
+
60
+ /** 主题令牌。颜色一律不带 `#`;字体是 CSS 字体栈,落到 Word 前会挑一个具体字体名。 */
61
+ export interface DocxStyle {
62
+ text: string;
63
+ secondaryText: string;
64
+ link: string;
65
+ bodyFontStack: string;
66
+ monoFontStack: string;
67
+ bodySize: number;
68
+ lineHeight: number;
69
+ inlineCodeBackground: string;
70
+ codeBlockBackground: string;
71
+ codeBlockText: string;
72
+ highlightBackground: string;
73
+ blockquoteBorder: string;
74
+ blockquoteBackground: string | null;
75
+ border: string;
76
+ tableHeaderBackground: string;
77
+ }
78
+
79
+ export interface DocxExportInput {
80
+ content: string;
81
+ sourcePath: string | null;
82
+ /** 渲染端为本次导出生成的图片(公式/示意图),keyed by Markdown 里重写后的名字。 */
83
+ images?: Record<string, string>;
84
+ /** 图片在 Word 里的目标尺寸(CSS 像素)。 */
85
+ imageSizes?: unknown;
86
+ style?: unknown;
87
+ }
88
+
89
+ // 没有拿到渲染进程的令牌时,仍生成一份完整的浅色文档。
90
+ const DEFAULT_STYLE: DocxStyle = {
91
+ text: '24292F',
92
+ secondaryText: '656D76',
93
+ link: '0969DA',
94
+ bodyFontStack: 'Segoe UI, Helvetica, Arial, sans-serif',
95
+ monoFontStack: 'Consolas, Menlo, monospace',
96
+ bodySize: 16,
97
+ lineHeight: 1.75,
98
+ inlineCodeBackground: 'EFF1F3',
99
+ codeBlockBackground: 'F6F8FA',
100
+ codeBlockText: '24292F',
101
+ highlightBackground: 'FFF3BF',
102
+ blockquoteBorder: 'D0D7DE',
103
+ blockquoteBackground: null,
104
+ border: 'D0D7DE',
105
+ tableHeaderBackground: 'F6F8FA',
106
+ };
107
+
108
+ // 与 colamd-extend themes/document.css 的字号比例一致:h1 1.9em … h5/h6 1em。
109
+ const HEADING_SCALE = [1.9, 1.55, 1.3, 1.12, 1, 1];
110
+
111
+ interface DocxContext {
112
+ style: DocxStyle;
113
+ bodyFont: string;
114
+ monoFont: string;
115
+ /**
116
+ * 代码用的字体(含 eastAsia 槽位)。
117
+ * 以前只用 `font: monoFont` 字符串:docx 会把它同时写进 w:rFonts 的 ascii / hAnsi /
118
+ * cs / eastAsia 四个槽位,如果选中了 Windows 没有的字体(如 Menlo),Word 就整段
119
+ * 替换,代码块变成 ♣ ○ ◇ 这类符号乱码。eastAsia 单独给一个中文字体,代码里的
120
+ * 中文注释才不会乱码(镜像 colamd-extend aad3bf6 的修复)。
121
+ */
122
+ codeFont: { ascii: string; hAnsi: string; cs: string; eastAsia: string };
123
+ bodySizeHalf: number;
124
+ paragraphLine: number;
125
+ codeSizeHalf: number;
126
+ footnoteIds: Map<string, number>;
127
+ sourcePath: string | null;
128
+ images?: Record<string, string>;
129
+ imageSizes?: Record<string, { width: number; height: number }>;
130
+ }
131
+
132
+ /** 已解码的图片(原生类型 + 字节 + 尺寸)。替代 Electron 的 NativeImage。 */
133
+ interface LoadedImage {
134
+ data: Buffer;
135
+ type: 'png' | 'jpg' | 'gif' | 'bmp';
136
+ width: number;
137
+ height: number;
138
+ }
139
+
140
+ function hexColor(value: unknown, fallback: string): string {
141
+ if (typeof value !== 'string') return fallback;
142
+ const raw = value.trim().replace(/^#/, '');
143
+ if (/^[0-9a-f]{3}$/i.test(raw)) return raw.split('').map((digit) => digit + digit).join('').toUpperCase();
144
+ if (/^[0-9a-f]{6}$/i.test(raw)) return raw.toUpperCase();
145
+ if (/^[0-9a-f]{8}$/i.test(raw)) return raw.slice(0, 6).toUpperCase();
146
+ return fallback;
147
+ }
148
+
149
+ function stringValue(value: unknown, fallback: string): string {
150
+ return typeof value === 'string' && value.trim() !== '' ? value.trim() : fallback;
151
+ }
152
+
153
+ function numberValue(value: unknown, fallback: number, min: number, max: number): number {
154
+ return typeof value === 'number' && Number.isFinite(value) ? Math.min(max, Math.max(min, value)) : fallback;
155
+ }
156
+
157
+ const FRONTMATTER_MAPPING = /^[ \t]*(?:[\p{L}\p{N}_][\p{L}\p{N}_.-]*|"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*')[ \t]*:([ \t]|$)/mu;
158
+
159
+ function frontmatterEnd(text: string): number {
160
+ if (!text.startsWith('---')) return 0;
161
+ const firstLineEnd = text.indexOf('\n');
162
+ if (firstLineEnd === -1) return 0;
163
+ if (text.slice(0, firstLineEnd).trim() !== '---') return 0;
164
+ const rest = text.slice(firstLineEnd + 1);
165
+ const close = /^(?:---|\.\.\.)[ \t]*$/m.exec(rest);
166
+ if (!close) return 0;
167
+ const body = rest.slice(0, close.index);
168
+ if (!FRONTMATTER_MAPPING.test(body)) return 0;
169
+ return firstLineEnd + 1 + close.index + close[0].length;
170
+ }
171
+
172
+ function normalizeImageSizes(raw: unknown): Record<string, { width: number; height: number }> | undefined {
173
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;
174
+ const sizes: Record<string, { width: number; height: number }> = {};
175
+ for (const [name, value] of Object.entries(raw as Record<string, unknown>)) {
176
+ if (!value || typeof value !== 'object') continue;
177
+ const width = (value as { width?: unknown }).width;
178
+ const height = (value as { height?: unknown }).height;
179
+ if (
180
+ typeof width === 'number' && Number.isFinite(width) && width > 0
181
+ && typeof height === 'number' && Number.isFinite(height) && height > 0
182
+ ) {
183
+ sizes[name] = { width: Math.min(4000, width), height: Math.min(4000, height) };
184
+ }
185
+ }
186
+ return Object.keys(sizes).length > 0 ? sizes : undefined;
187
+ }
188
+
189
+ function normalizeStyle(raw: unknown): DocxStyle {
190
+ const source = typeof raw === 'object' && raw !== null ? raw as Record<string, unknown> : {};
191
+ const blockquoteBackground = typeof source.blockquoteBackground === 'string'
192
+ ? hexColor(source.blockquoteBackground, '')
193
+ : '';
194
+ return {
195
+ text: hexColor(source.text, DEFAULT_STYLE.text),
196
+ secondaryText: hexColor(source.secondaryText, DEFAULT_STYLE.secondaryText),
197
+ link: hexColor(source.link, DEFAULT_STYLE.link),
198
+ bodyFontStack: stringValue(source.bodyFontStack, DEFAULT_STYLE.bodyFontStack),
199
+ monoFontStack: stringValue(source.monoFontStack, DEFAULT_STYLE.monoFontStack),
200
+ bodySize: numberValue(source.bodySize, DEFAULT_STYLE.bodySize, 8, 40),
201
+ lineHeight: numberValue(source.lineHeight, DEFAULT_STYLE.lineHeight, 1, 3),
202
+ inlineCodeBackground: hexColor(source.inlineCodeBackground, DEFAULT_STYLE.inlineCodeBackground),
203
+ codeBlockBackground: hexColor(source.codeBlockBackground, DEFAULT_STYLE.codeBlockBackground),
204
+ codeBlockText: hexColor(source.codeBlockText, DEFAULT_STYLE.codeBlockText),
205
+ highlightBackground: hexColor(source.highlightBackground, DEFAULT_STYLE.highlightBackground),
206
+ blockquoteBorder: hexColor(source.blockquoteBorder, DEFAULT_STYLE.blockquoteBorder),
207
+ blockquoteBackground: blockquoteBackground !== '' ? blockquoteBackground : null,
208
+ border: hexColor(source.border, DEFAULT_STYLE.border),
209
+ tableHeaderBackground: hexColor(source.tableHeaderBackground, DEFAULT_STYLE.tableHeaderBackground),
210
+ };
211
+ }
212
+
213
+ /** 从 CSS 字体栈里挑一个 Word 认得的字体名。 */
214
+ function fontName(stack: string, mono: boolean): string {
215
+ const generic = new Set([
216
+ 'serif', 'sans-serif', 'monospace', 'system-ui', 'ui-sans-serif', 'ui-monospace',
217
+ 'cursive', 'fantasy', '-apple-system', 'blinkmacsystemfont',
218
+ ]);
219
+ const families = stack
220
+ .split(',')
221
+ .map((family) => family.trim().replace(/^["']|["']$/g, ''))
222
+ .filter((family) => family !== '' && !generic.has(family.toLowerCase()));
223
+
224
+ const platform = process.platform;
225
+ const preferred = mono
226
+ ? platform === 'win32'
227
+ ? ['consolas', 'cascadia code', 'fira code', 'menlo']
228
+ : platform === 'darwin'
229
+ ? ['sf mono', 'menlo', 'fira code', 'consolas']
230
+ : ['dejavu sans mono', 'liberation mono', 'noto sans mono']
231
+ : platform === 'win32'
232
+ ? ['segoe ui', 'microsoft yahei', 'noto sans']
233
+ : platform === 'darwin'
234
+ ? ['helvetica neue', 'helvetica', 'noto sans']
235
+ : ['noto sans', 'dejavu sans'];
236
+
237
+ for (const name of preferred) {
238
+ const hit = families.find((family) => family.toLowerCase() === name);
239
+ if (hit) return hit;
240
+ }
241
+ if (families[0]) return families[0];
242
+ if (mono) return platform === 'win32' ? 'Consolas' : platform === 'darwin' ? 'Menlo' : 'DejaVu Sans Mono';
243
+ return platform === 'win32' ? 'Segoe UI' : platform === 'darwin' ? 'Helvetica Neue' : 'Noto Sans';
244
+ }
245
+
246
+ /** px → Word 的半磅值。 */
247
+ function halfPoints(px: number): number {
248
+ return Math.max(2, Math.round(px * 1.5));
249
+ }
250
+
251
+ /** 代码的 eastAsia 中文字体:按平台选一个 Word 认得的(镜像 colamd-extend aad3bf6)。 */
252
+ function codeEastAsiaFont(): string {
253
+ return process.platform === 'darwin'
254
+ ? 'PingFang SC'
255
+ : process.platform === 'win32'
256
+ ? 'Microsoft YaHei'
257
+ : 'Noto Sans CJK SC';
258
+ }
259
+
260
+ /** em 距离 → twips(1px = 15 twips)。 */
261
+ function emTwips(px: number, em: number): number {
262
+ return Math.round(px * em * 15);
263
+ }
264
+
265
+ function headingForDepth(depth: number): (typeof HeadingLevel)[keyof typeof HeadingLevel] {
266
+ const headings = [
267
+ HeadingLevel.HEADING_1,
268
+ HeadingLevel.HEADING_2,
269
+ HeadingLevel.HEADING_3,
270
+ HeadingLevel.HEADING_4,
271
+ HeadingLevel.HEADING_5,
272
+ HeadingLevel.HEADING_6,
273
+ ];
274
+ return headings[Math.max(0, Math.min(5, depth - 1))] as (typeof HeadingLevel)[keyof typeof HeadingLevel];
275
+ }
276
+
277
+ function textContent(node: MarkdownNode): string {
278
+ if (node.type === 'text' || node.type === 'inlineCode' || node.type === 'code') return node.value ?? '';
279
+ if (node.type === 'break') return '\n';
280
+ return node.children?.map(textContent).join('') ?? '';
281
+ }
282
+
283
+ /**
284
+ * 纯 JS 识别图片字节类型并读取宽高(替代 nativeImage.getSize())。
285
+ * 支持 PNG/JPEG/GIF/BMP;返回 null 表示无法识别(如 SVG)。
286
+ */
287
+ function sniffImage(buf: Buffer): { type: LoadedImage['type']; width: number; height: number } | null {
288
+ if (!buf || buf.length < 24) return null;
289
+ // PNG
290
+ if (buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) {
291
+ return { type: 'png', width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
292
+ }
293
+ // JPEG
294
+ if (buf[0] === 0xff && buf[1] === 0xd8) {
295
+ let i = 2;
296
+ while (i + 9 < buf.length) {
297
+ if (buf[i] !== 0xff) { i += 1; continue; }
298
+ const marker = buf[i + 1];
299
+ if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {
300
+ return { type: 'jpg', width: buf.readUInt16BE(i + 7), height: buf.readUInt16BE(i + 5) };
301
+ }
302
+ const size = buf.readUInt16BE(i + 2);
303
+ i += 2 + size;
304
+ }
305
+ return null;
306
+ }
307
+ // GIF
308
+ const gifSig = buf.toString('ascii', 0, 6);
309
+ if (gifSig === 'GIF87a' || gifSig === 'GIF89a') {
310
+ return { type: 'gif', width: buf.readUInt16LE(6), height: buf.readUInt16LE(8) };
311
+ }
312
+ // BMP
313
+ if (buf.toString('ascii', 0, 2) === 'BM') {
314
+ return { type: 'bmp', width: Math.abs(buf.readInt32LE(18)), height: Math.abs(buf.readInt32LE(22)) };
315
+ }
316
+ return null;
317
+ }
318
+
319
+ function dataUrlToImage(dataURL: string): LoadedImage | null {
320
+ const m = /^data:image\/[a-z0-9.+-]+;base64,([A-Za-z0-9+/=]+)$/i.exec(dataURL);
321
+ if (!m) return null;
322
+ const buffer = Buffer.from(m[1], 'base64');
323
+ const dims = sniffImage(buffer);
324
+ if (!dims) return null;
325
+ return { data: buffer, ...dims };
326
+ }
327
+
328
+ function fileToImage(path: string): LoadedImage | null {
329
+ try {
330
+ const data = fs.readFileSync(path);
331
+ const dims = sniffImage(data);
332
+ if (!dims) return null;
333
+ return { data, ...dims };
334
+ } catch {
335
+ return null;
336
+ }
337
+ }
338
+
339
+ /** `==高亮==` 的底纹 run 拆分。 */
340
+ function textRuns(text: string, context: DocxContext, style: IRunStylePropertiesOptions): ParagraphChild[] {
341
+ if (!text.includes('==')) return [new TextRun({ text, ...style })];
342
+ const runs: ParagraphChild[] = [];
343
+ const pattern = /==([^=\n]+)==/g;
344
+ let cursor = 0;
345
+ for (const match of text.matchAll(pattern)) {
346
+ const index = match.index ?? 0;
347
+ if (index > cursor) runs.push(new TextRun({ text: text.slice(cursor, index), ...style }));
348
+ runs.push(new TextRun({
349
+ text: match[1] ?? '',
350
+ ...style,
351
+ shading: { fill: context.style.highlightBackground },
352
+ }));
353
+ cursor = index + match[0].length;
354
+ }
355
+ if (cursor === 0) return [new TextRun({ text, ...style })];
356
+ if (cursor < text.length) runs.push(new TextRun({ text: text.slice(cursor), ...style }));
357
+ return runs;
358
+ }
359
+
360
+ function loadImage(node: MarkdownNode, context: DocxContext): { image: LoadedImage; target?: { width: number; height: number } } | null {
361
+ const inlineData = node.url && /^data:image\//i.test(node.url) ? node.url : undefined;
362
+ const dataURL = node.url ? (context.images?.[node.url] ?? inlineData) : undefined;
363
+ const image = dataURL
364
+ ? dataUrlToImage(dataURL)
365
+ : (() => {
366
+ const p = node.url ? imagePath(node.url, context.sourcePath) : null;
367
+ return p ? fileToImage(p) : null;
368
+ })();
369
+ if (!image) return null;
370
+ return { image, target: node.url ? context.imageSizes?.[node.url] : undefined };
371
+ }
372
+
373
+ function imageSize(
374
+ image: LoadedImage,
375
+ target?: { width: number; height: number },
376
+ targetMax: { width: number; height: number } = { width: 600, height: 420 },
377
+ ): { width: number; height: number } {
378
+ if (target) {
379
+ const scale = Math.min(1, targetMax.width / target.width, targetMax.height / target.height);
380
+ return {
381
+ width: Math.max(1, Math.round(target.width * scale)),
382
+ height: Math.max(1, Math.round(target.height * scale)),
383
+ };
384
+ }
385
+ const scale = Math.min(1, 560 / image.width, 420 / image.height);
386
+ return {
387
+ width: Math.max(1, Math.round(image.width * scale)),
388
+ height: Math.max(1, Math.round(image.height * scale)),
389
+ };
390
+ }
391
+
392
+ function inlineRuns(
393
+ nodes: MarkdownNode[] | undefined,
394
+ context: DocxContext,
395
+ style: IRunStylePropertiesOptions = {},
396
+ ): ParagraphChild[] {
397
+ if (!nodes) return [];
398
+ const runs: ParagraphChild[] = [];
399
+ for (const node of nodes) {
400
+ if (node.type === 'text') {
401
+ runs.push(...textRuns(node.value ?? '', context, style));
402
+ } else if (node.type === 'break') {
403
+ runs.push(new TextRun({ break: 1, ...style }));
404
+ } else if (node.type === 'inlineCode') {
405
+ runs.push(new TextRun({
406
+ text: node.value ?? '',
407
+ font: context.codeFont,
408
+ size: context.codeSizeHalf,
409
+ shading: { fill: context.style.inlineCodeBackground },
410
+ noProof: true, // 变量名不再带拼写红波浪线
411
+ ...style,
412
+ }));
413
+ } else if (node.type === 'strong') {
414
+ runs.push(...inlineRuns(node.children, context, { ...style, bold: true }));
415
+ } else if (node.type === 'emphasis') {
416
+ runs.push(...inlineRuns(node.children, context, { ...style, italics: true }));
417
+ } else if (node.type === 'delete') {
418
+ runs.push(...inlineRuns(node.children, context, { ...style, strike: true }));
419
+ } else if (node.type === 'link' && node.url) {
420
+ runs.push(new ExternalHyperlink({
421
+ link: node.url,
422
+ children: inlineRuns(node.children, context, {
423
+ ...style,
424
+ color: context.style.link,
425
+ underline: { type: UnderlineType.SINGLE },
426
+ }),
427
+ }));
428
+ } else if (node.type === 'footnoteReference') {
429
+ const id = node.identifier ? context.footnoteIds.get(node.identifier) : undefined;
430
+ runs.push(id
431
+ ? new FootnoteReferenceRun(id)
432
+ : new TextRun({ text: node.label ?? '', superScript: true }));
433
+ } else if (node.type === 'html') {
434
+ const value = node.value ?? '';
435
+ if (/^<br\b/i.test(value)) {
436
+ runs.push(new TextRun({ break: 1, ...style }));
437
+ } else {
438
+ const img = /^<img\b[^>]*?\bsrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(value);
439
+ if (img) {
440
+ const url = img[1] ?? img[2] ?? img[3] ?? '';
441
+ const altMatch = /\balt\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(value);
442
+ const alt = altMatch?.[1] ?? altMatch?.[2] ?? altMatch?.[3] ?? '';
443
+ const loaded = loadImage({ type: 'image', url, alt }, context);
444
+ if (loaded) {
445
+ runs.push(new ImageRun({
446
+ type: loaded.image.type,
447
+ data: loaded.image.data,
448
+ transformation: imageSize(loaded.image, loaded.target),
449
+ altText: alt ? { name: alt } : undefined,
450
+ }));
451
+ }
452
+ }
453
+ }
454
+ } else if (node.type === 'image') {
455
+ const loaded = loadImage(node, context);
456
+ if (loaded) {
457
+ runs.push(new ImageRun({
458
+ type: loaded.image.type,
459
+ data: loaded.image.data,
460
+ transformation: imageSize(loaded.image, loaded.target),
461
+ altText: node.alt ? { name: node.alt } : undefined,
462
+ }));
463
+ } else {
464
+ runs.push(new TextRun({
465
+ text: node.alt ? `[${node.alt}]` : '[image]',
466
+ italics: true,
467
+ color: context.style.secondaryText,
468
+ ...style,
469
+ }));
470
+ }
471
+ } else {
472
+ runs.push(...inlineRuns(node.children, context, style));
473
+ }
474
+ }
475
+ return runs;
476
+ }
477
+
478
+ function imagePath(url: string, sourcePath: string | null): string | null {
479
+ if (/^(https?:|data:|blob:)/i.test(url)) return null;
480
+ try {
481
+ if (url.startsWith('file:')) return fileURLToPath(url);
482
+ } catch {
483
+ return null;
484
+ }
485
+ if (!sourcePath) return null;
486
+ return isAbsolute(url) ? url : resolve(dirname(sourcePath), decodeURIComponent(url));
487
+ }
488
+
489
+ const REMOTE_TIMEOUT_MS = 15000;
490
+ const REMOTE_MAX_BYTES = 20 * 1024 * 1024;
491
+
492
+ /** 远程图片:下载后保留原始字节,失败返回 null。 */
493
+ async function downloadImage(url: string): Promise<string | null> {
494
+ try {
495
+ const response = await fetch(url, {
496
+ signal: AbortSignal.timeout(REMOTE_TIMEOUT_MS),
497
+ headers: { 'User-Agent': 'ColaView', Accept: 'image/*' },
498
+ });
499
+ if (!response.ok) return null;
500
+ const declared = Number(response.headers.get('content-length') ?? 0);
501
+ if (declared > REMOTE_MAX_BYTES) return null;
502
+ const buffer = Buffer.from(await response.arrayBuffer());
503
+ if (buffer.length === 0 || buffer.length > REMOTE_MAX_BYTES) return null;
504
+ if (!sniffImage(buffer)) return null;
505
+ const contentType = (response.headers.get('content-type') ?? 'image/png').split(';')[0].trim();
506
+ return `data:${contentType};base64,${buffer.toString('base64')}`;
507
+ } catch {
508
+ return null;
509
+ }
510
+ }
511
+
512
+ function collectRemoteImageUrls(nodes: MarkdownNode[] | undefined, urls: Set<string>): void {
513
+ for (const node of nodes ?? []) {
514
+ if (node.type === 'image' && node.url && /^https?:/i.test(node.url)) urls.add(node.url);
515
+ if (node.type === 'html' && node.value) {
516
+ const img = /<img\b[^>]*\bsrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(node.value);
517
+ const src = img?.[1] ?? img?.[2] ?? img?.[3];
518
+ if (src && /^https?:/i.test(src)) urls.add(src);
519
+ }
520
+ collectRemoteImageUrls(node.children, urls);
521
+ }
522
+ }
523
+
524
+ async function remoteImagesFor(tree: MarkdownNode): Promise<Record<string, string>> {
525
+ const urls = new Set<string>();
526
+ collectRemoteImageUrls(tree.children, urls);
527
+ if (urls.size === 0) return {};
528
+ const entries = await Promise.all([...urls].map(async (url) => [url, await downloadImage(url)] as const));
529
+ return Object.fromEntries(entries.filter((entry): entry is readonly [string, string] => entry[1] !== null));
530
+ }
531
+
532
+ function imageParagraph(node: MarkdownNode, context: DocxContext): Paragraph {
533
+ const loaded = loadImage(node, context);
534
+ if (!loaded) {
535
+ return new Paragraph({
536
+ children: [new TextRun({ text: node.alt ? `[${node.alt}]` : '[image]', italics: true })],
537
+ });
538
+ }
539
+ const url = node.url ?? '';
540
+ const size = imageSize(
541
+ loaded.image,
542
+ loaded.target,
543
+ /colamd-html-/.test(url) ? { width: 600, height: 800 } : undefined,
544
+ );
545
+ return new Paragraph({
546
+ alignment: AlignmentType.CENTER,
547
+ spacing: { before: emTwips(context.style.bodySize, 1.2), after: emTwips(context.style.bodySize, 1.2) },
548
+ children: [new ImageRun({
549
+ type: loaded.image.type,
550
+ data: loaded.image.data,
551
+ transformation: size,
552
+ altText: node.alt ? { name: node.alt } : undefined,
553
+ })],
554
+ });
555
+ }
556
+
557
+ function alignmentFor(align: string | null | undefined): (typeof AlignmentType)[keyof typeof AlignmentType] {
558
+ if (align === 'center') return AlignmentType.CENTER;
559
+ if (align === 'right') return AlignmentType.RIGHT;
560
+ return AlignmentType.LEFT;
561
+ }
562
+
563
+ function tableForNode(node: MarkdownNode, context: DocxContext): Table {
564
+ const border = { style: BorderStyle.SINGLE, size: 6, color: context.style.border };
565
+ return new Table({
566
+ width: { size: 100, type: WidthType.PERCENTAGE },
567
+ borders: {
568
+ top: border,
569
+ bottom: border,
570
+ left: border,
571
+ right: border,
572
+ insideHorizontal: border,
573
+ insideVertical: border,
574
+ },
575
+ rows: (node.children ?? []).map((row, rowIndex) => new TableRow({
576
+ tableHeader: rowIndex === 0,
577
+ children: (row.children ?? []).map((cell, cellIndex) => new TableCell({
578
+ shading: rowIndex === 0 ? { fill: context.style.tableHeaderBackground } : undefined,
579
+ margins: { top: 120, bottom: 120, left: 180, right: 180 },
580
+ children: [new Paragraph({
581
+ alignment: alignmentFor(node.align?.[cellIndex]),
582
+ spacing: { before: 0, after: 0, line: 240, lineRule: LineRuleType.AUTO },
583
+ children: inlineRuns(cell.children, context, rowIndex === 0 ? { bold: true } : {}),
584
+ })],
585
+ })),
586
+ })),
587
+ });
588
+ }
589
+
590
+ function codeParagraph(node: MarkdownNode, context: DocxContext, extra: IParagraphOptions = {}): Paragraph {
591
+ // 每一行自己一个 run,行间用 `<w:br/>`;空行也要留一个 break,不然空行会被吃掉。
592
+ const lines = (node.value ?? '').replace(/\n+$/, '').split('\n');
593
+ const children: ParagraphChild[] = lines.map((line, index) => (
594
+ line === ''
595
+ ? new TextRun({ text: '', break: 1 })
596
+ : new TextRun({
597
+ text: line,
598
+ break: index > 0 ? 1 : undefined,
599
+ font: context.codeFont,
600
+ size: context.codeSizeHalf,
601
+ color: context.style.codeBlockText,
602
+ noProof: true, // 变量名不再带拼写红波浪线
603
+ })
604
+ ));
605
+ const codeLine = Math.round(context.style.bodySize * 0.875 * 1.6 * 15);
606
+ const codePad = emTwips(context.style.bodySize, 1.0);
607
+ const codeBorder = { color: context.style.border, space: 4, style: BorderStyle.SINGLE, size: 4 };
608
+ return new Paragraph({
609
+ ...extra,
610
+ // 显式左对齐:不写的话继承默认样式,默认是两端对齐时每一行都会被拉满行宽,
611
+ // 键留在左边、值被顶到右边(镜像 colamd-extend aad3bf6)。
612
+ alignment: AlignmentType.LEFT,
613
+ shading: { fill: context.style.codeBlockBackground },
614
+ spacing: { before: codePad, after: codePad, line: codeLine, lineRule: LineRuleType.AT_LEAST },
615
+ border: {
616
+ top: codeBorder,
617
+ bottom: codeBorder,
618
+ left: codeBorder,
619
+ right: codeBorder,
620
+ },
621
+ children,
622
+ });
623
+ }
624
+
625
+ function blockquoteNodes(
626
+ node: MarkdownNode,
627
+ context: DocxContext,
628
+ ): Array<Paragraph | Table> {
629
+ const quote: IParagraphOptions = {
630
+ border: {
631
+ left: { color: context.style.blockquoteBorder, space: 12, style: BorderStyle.SINGLE, size: 24 },
632
+ },
633
+ indent: { left: 240 },
634
+ shading: context.style.blockquoteBackground ? { fill: context.style.blockquoteBackground } : undefined,
635
+ spacing: { after: emTwips(context.style.bodySize, 0.5) },
636
+ };
637
+ const childStyle: IRunStylePropertiesOptions = { color: context.style.secondaryText };
638
+ const output: Array<Paragraph | Table> = [];
639
+
640
+ for (const child of node.children ?? []) {
641
+ if (child.type === 'paragraph' || child.type === 'heading') {
642
+ output.push(new Paragraph({ ...quote, children: inlineRuns(child.children, context, childStyle) }));
643
+ } else if (child.type === 'list') {
644
+ const start = child.start ?? 1;
645
+ for (const [index, item] of (child.children ?? []).entries()) {
646
+ const first = item.children?.find((entry) => entry.type === 'paragraph');
647
+ const prefix = child.ordered ? `${start + index}. ` : '• ';
648
+ output.push(new Paragraph({
649
+ ...quote,
650
+ indent: { left: 600, hanging: 240 },
651
+ children: [
652
+ new TextRun({ text: prefix, ...childStyle }),
653
+ ...inlineRuns(first?.children, context, childStyle),
654
+ ],
655
+ }));
656
+ }
657
+ } else if (child.type === 'code') {
658
+ output.push(codeParagraph(child, context, quote));
659
+ } else if (child.type === 'thematicBreak') {
660
+ output.push(new Paragraph({
661
+ ...quote,
662
+ border: { bottom: { color: context.style.border, space: 1, style: BorderStyle.SINGLE, size: 6 } },
663
+ }));
664
+ } else {
665
+ output.push(new Paragraph({
666
+ ...quote,
667
+ children: [new TextRun({ text: textContent(child), ...childStyle })],
668
+ }));
669
+ }
670
+ }
671
+ return output;
672
+ }
673
+
674
+ function prepareLists(nodes: MarkdownNode[] | undefined, state: { next: number; starts: Set<number> }): void {
675
+ for (const node of nodes ?? []) {
676
+ if (node.type === 'list') {
677
+ node.instance = state.next;
678
+ state.next += 1;
679
+ if (node.ordered) state.starts.add(node.start ?? 1);
680
+ }
681
+ prepareLists(node.children, state);
682
+ }
683
+ }
684
+
685
+ function bulletLevels() {
686
+ const marks = ['•', '○', '■'];
687
+ return Array.from({ length: 9 }, (_, level) => ({
688
+ level,
689
+ format: LevelFormat.BULLET,
690
+ text: marks[level % marks.length],
691
+ alignment: AlignmentType.LEFT,
692
+ style: { paragraph: { indent: { left: 360 + level * 360, hanging: 240 } } },
693
+ }));
694
+ }
695
+
696
+ function decimalLevels(start: number) {
697
+ return Array.from({ length: 9 }, (_, level) => ({
698
+ level,
699
+ format: LevelFormat.DECIMAL,
700
+ text: `%${level + 1}.`,
701
+ alignment: AlignmentType.LEFT,
702
+ ...(level === 0 ? { start } : {}),
703
+ style: { paragraph: { indent: { left: 360 + level * 360, hanging: 240 } } },
704
+ }));
705
+ }
706
+
707
+ function numberingConfig(starts: Set<number>) {
708
+ return {
709
+ config: [
710
+ { reference: 'bullet', levels: bulletLevels() },
711
+ ...[...starts].sort((left, right) => left - right).map((start) => ({
712
+ reference: `ordered-${start}`,
713
+ levels: decimalLevels(start),
714
+ })),
715
+ ],
716
+ };
717
+ }
718
+
719
+ function prepareFootnotes(nodes: MarkdownNode[] | undefined, ids: Map<string, number>): void {
720
+ for (const node of nodes ?? []) {
721
+ if (node.type === 'footnoteDefinition') continue;
722
+ if (node.type === 'footnoteReference' && node.identifier && !ids.has(node.identifier)) {
723
+ ids.set(node.identifier, ids.size + 1);
724
+ }
725
+ prepareFootnotes(node.children, ids);
726
+ }
727
+ }
728
+
729
+ function blockNodes(
730
+ nodes: MarkdownNode[] | undefined,
731
+ context: DocxContext,
732
+ listDepth = 0,
733
+ ): Array<Paragraph | Table> {
734
+ if (!nodes) return [];
735
+ const output: Array<Paragraph | Table> = [];
736
+ for (const node of nodes) {
737
+ if (node.type === 'heading') {
738
+ output.push(new Paragraph({ heading: headingForDepth(node.depth ?? 1), children: inlineRuns(node.children, context) }));
739
+ } else if (node.type === 'paragraph') {
740
+ const image = node.children?.length === 1 && node.children[0]?.type === 'image' ? node.children[0] : null;
741
+ output.push(image
742
+ ? imageParagraph(image, context)
743
+ : new Paragraph({ children: inlineRuns(node.children, context) }));
744
+ } else if (node.type === 'image') {
745
+ output.push(imageParagraph(node, context));
746
+ } else if (node.type === 'blockquote') {
747
+ output.push(...blockquoteNodes(node, context));
748
+ } else if (node.type === 'code') {
749
+ output.push(codeParagraph(node, context));
750
+ } else if (node.type === 'list') {
751
+ const start = node.start ?? 1;
752
+ for (const item of (node.children ?? [])) {
753
+ const first = item.children?.find((child) => child.type === 'paragraph');
754
+ const itemSpacing = {
755
+ before: 0,
756
+ after: emTwips(context.style.bodySize, 0.3),
757
+ line: context.paragraphLine,
758
+ lineRule: LineRuleType.AT_LEAST,
759
+ };
760
+ if (typeof item.checked === 'boolean') {
761
+ output.push(new Paragraph({
762
+ children: [
763
+ new TextRun({
764
+ text: item.checked ? '☑ ' : '☐ ',
765
+ color: item.checked ? context.style.link : context.style.secondaryText,
766
+ }),
767
+ ...inlineRuns(first?.children, context),
768
+ ],
769
+ indent: { left: 360 + listDepth * 360, hanging: 240 },
770
+ spacing: itemSpacing,
771
+ }));
772
+ } else {
773
+ output.push(new Paragraph({
774
+ children: inlineRuns(first?.children, context),
775
+ numbering: node.ordered
776
+ ? { reference: `ordered-${start}`, level: listDepth, instance: node.instance ?? 0 }
777
+ : { reference: 'bullet', level: listDepth, instance: 0 },
778
+ spacing: itemSpacing,
779
+ }));
780
+ }
781
+ output.push(...blockNodes(item.children?.filter((child) => child !== first), context, listDepth + 1));
782
+ }
783
+ } else if (node.type === 'table') {
784
+ output.push(tableForNode(node, context));
785
+ } else if (node.type === 'thematicBreak') {
786
+ output.push(new Paragraph({ border: { bottom: { color: context.style.border, space: 1, style: BorderStyle.SINGLE, size: 6 } } }));
787
+ } else if (node.type === 'html') {
788
+ output.push(new Paragraph({
789
+ children: [new TextRun({ text: node.value ?? '', font: context.monoFont, size: context.codeSizeHalf, color: context.style.secondaryText })],
790
+ }));
791
+ } else if (node.type === 'footnoteDefinition') {
792
+ continue;
793
+ } else {
794
+ output.push(...blockNodes(node.children, context, listDepth));
795
+ }
796
+ }
797
+ return output;
798
+ }
799
+
800
+ function buildFootnotes(
801
+ tree: MarkdownNode,
802
+ context: DocxContext,
803
+ ): Record<string, { children: Paragraph[] }> | undefined {
804
+ const definitions = (tree.children ?? []).filter((node) => (
805
+ node.type === 'footnoteDefinition' && node.identifier && context.footnoteIds.has(node.identifier)
806
+ ));
807
+ if (definitions.length === 0) return undefined;
808
+
809
+ const footnotes: Record<string, { children: Paragraph[] }> = {};
810
+ for (const definition of definitions) {
811
+ const id = context.footnoteIds.get(definition.identifier ?? '');
812
+ if (!id) continue;
813
+ const children = blockNodes(definition.children, context)
814
+ .filter((child): child is Paragraph => child instanceof Paragraph);
815
+ footnotes[String(id)] = { children: children.length > 0 ? children : [new Paragraph({ children: [] })] };
816
+ }
817
+ return footnotes;
818
+ }
819
+
820
+ function documentStyles(context: DocxContext) {
821
+ const font = {
822
+ ascii: context.bodyFont,
823
+ hAnsi: context.bodyFont,
824
+ eastAsia: context.bodyFont,
825
+ cs: context.bodyFont,
826
+ };
827
+ const footnoteLine = Math.round(context.style.bodySize * 0.875 * 1.6 * 15);
828
+ const bodyPadAfter = emTwips(context.style.bodySize, 0.75);
829
+ const bodyPadBefore = Math.round(bodyPadAfter * 0.33);
830
+ const heading = (level: number) => {
831
+ const px = context.style.bodySize * HEADING_SCALE[level - 1];
832
+ return {
833
+ run: { bold: true, color: context.style.text, size: halfPoints(px) },
834
+ paragraph: {
835
+ outlineLevel: level - 1,
836
+ keepNext: true,
837
+ keepLines: true,
838
+ spacing: {
839
+ before: emTwips(px, 1.4),
840
+ after: emTwips(px, 0.6),
841
+ line: emTwips(px, 1.35),
842
+ lineRule: LineRuleType.AT_LEAST,
843
+ },
844
+ },
845
+ };
846
+ };
847
+
848
+ return {
849
+ default: {
850
+ document: {
851
+ run: { font, size: context.bodySizeHalf, color: context.style.text },
852
+ paragraph: {
853
+ spacing: {
854
+ line: context.paragraphLine,
855
+ lineRule: LineRuleType.AT_LEAST,
856
+ before: bodyPadBefore,
857
+ after: bodyPadAfter,
858
+ },
859
+ },
860
+ },
861
+ heading1: heading(1),
862
+ heading2: heading(2),
863
+ heading3: heading(3),
864
+ heading4: heading(4),
865
+ heading5: heading(5),
866
+ heading6: heading(6),
867
+ footnoteText: {
868
+ run: { size: context.codeSizeHalf, color: context.style.secondaryText },
869
+ paragraph: {
870
+ spacing: { after: 60, line: footnoteLine, lineRule: LineRuleType.AT_LEAST },
871
+ },
872
+ },
873
+ },
874
+ };
875
+ }
876
+
877
+ export async function markdownToDocx(input: DocxExportInput): Promise<Buffer> {
878
+ const style = normalizeStyle(input.style);
879
+ const source = input.content;
880
+ const frontmatter = frontmatterEnd(source);
881
+ const body = frontmatter > 0 ? source.slice(frontmatter) : source;
882
+ const tree = unified()
883
+ .use(remarkParse)
884
+ .use(remarkGfm)
885
+ .parse(body) as unknown as MarkdownNode;
886
+
887
+ const footnoteIds = new Map<string, number>();
888
+ prepareFootnotes(tree.children, footnoteIds);
889
+ const listState = { next: 0, starts: new Set<number>() };
890
+ prepareLists(tree.children, listState);
891
+ const remoteImages = await remoteImagesFor(tree);
892
+
893
+ const monoFont = fontName(style.monoFontStack, true);
894
+ const context: DocxContext = {
895
+ style,
896
+ bodyFont: fontName(style.bodyFontStack, false),
897
+ monoFont,
898
+ codeFont: {
899
+ ascii: monoFont,
900
+ hAnsi: monoFont,
901
+ cs: monoFont,
902
+ eastAsia: codeEastAsiaFont(),
903
+ },
904
+ bodySizeHalf: halfPoints(style.bodySize),
905
+ paragraphLine: Math.round(style.lineHeight * style.bodySize * 15),
906
+ codeSizeHalf: halfPoints(style.bodySize * 0.875),
907
+ footnoteIds,
908
+ sourcePath: input.sourcePath,
909
+ images: { ...remoteImages, ...input.images },
910
+ imageSizes: normalizeImageSizes(input.imageSizes),
911
+ };
912
+
913
+ const footnotes = buildFootnotes(tree, context);
914
+ const pageNumber = new TextRun({
915
+ children: [PageNumber.CURRENT, ' / ', PageNumber.TOTAL_PAGES],
916
+ size: context.codeSizeHalf,
917
+ color: style.secondaryText,
918
+ });
919
+
920
+ const document = new Document({
921
+ creator: 'ColaView',
922
+ title: input.sourcePath ? basename(input.sourcePath, extname(input.sourcePath)) : 'Untitled',
923
+ styles: documentStyles(context),
924
+ numbering: numberingConfig(listState.starts),
925
+ ...(footnotes ? { footnotes } : {}),
926
+ sections: [{
927
+ footers: {
928
+ default: new Footer({
929
+ children: [new Paragraph({ alignment: AlignmentType.CENTER, children: [pageNumber] })],
930
+ }),
931
+ },
932
+ children: blockNodes(tree.children, context),
933
+ }],
934
+ });
935
+ return Packer.toBuffer(document);
936
+ }
937
+
938
+ /**
939
+ * 导出当前 Markdown 文档为 Word (.docx)。
940
+ * 纯宿主转换:先渲染公式/Mermaid 为 PNG 并重写 Markdown,再生成 docx。
941
+ */
942
+ export async function exportWord(document: vscode.TextDocument): Promise<void> {
943
+ const markdown = document.getText();
944
+ const sourcePath = document.fileName;
945
+
946
+ // 先取主题令牌:Mermaid 图的配色跟随当前预览主题(浅色跟随、深色回落浅色),
947
+ // 再用同一份令牌构建 Word 文档样式,两边保持一致。
948
+ const themeCss = ThemeManager.loadThemeCSS(ThemeManager.getCurrentTheme());
949
+ const style = buildDocxStyleFromThemeCss(themeCss);
950
+ const { content, images, imageSizes } = await renderMathAndMermaidToImages(markdown, style);
951
+ const buffer = await markdownToDocx({ content, sourcePath, images, imageSizes, style });
952
+
953
+ const defaultName = document.fileName.replace(/\.md$/i, '.docx');
954
+ const uri = await vscode.window.showSaveDialog({
955
+ defaultUri: vscode.Uri.file(defaultName),
956
+ filters: { 'Word Document': ['docx'] },
957
+ });
958
+ if (!uri) return;
959
+
960
+ await vscode.workspace.fs.writeFile(uri, buffer);
961
+ vscode.window.showInformationMessage(`Exported to ${uri.fsPath}`);
962
962
  }