vscode-colaview 0.3.0 → 0.3.2

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.
@@ -1,7 +1,4 @@
1
1
  {
2
2
  "colaview.autoPreview": false,
3
- "colaview.customThemesPath": ".themes/",
4
- "colaview.theme": "newsprint",
5
- "colaview.pdfMethod": "webviewPrint",
6
- "colaview.plugins.math": false
3
+ "colaview.theme": "elegant"
7
4
  }
package/CHANGELOG.md CHANGED
@@ -2,6 +2,35 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## [0.3.2] - 2026-11-07
6
+
7
+ ### Fixed
8
+ - Fixed **PDF/HTML export failing with `md is not defined`** — the export CSS injected by `patchExportHTML` lives in a JS template literal, and a CSS comment inside it contained unescaped backticks (`` `.cm-md-mermaid` ``). The first backtick closed the template literal early, so the rest of the comment was parsed as JavaScript (`…template.cm - md - mermaid…`), throwing `ReferenceError: md is not defined` at export time — surfacing to the user as "PDF export failed: md is not defined". The backticks are now escaped, so the comment stays a comment. (Only the packaged/minified build hit it in a confusing way; `tsc` flags it as `Cannot find name 'md'`.)
9
+ - Fixed **Mermaid diagrams left-aligned in PDF/HTML exports** — the engine serializes mermaid blocks as class-stripped `<p><svg class="pele pele-…">…</svg></p>`, so the previous export rule (`div:has(> svg.pele)`) never matched and its `text-align: center` never applied: diagrams were centered in the preview but flush-left on paper. Centering now lives on `svg.pele` itself (`display: block; margin: 0 auto`), independent of the wrapper element.
10
+ - Fixed **Mermaid diagram background not matching ColaMD-extend** — diagram colors are derived from the theme's code-block background (`--code-block-bg`), and in ColaMD the diagram sits on that block background. ColaView preview and export rendered it on the plain page background instead. Both now paint the same block behind the diagram (code-block background, 6px radius, `0.8em 1em` padding), so Elegant/Bear (light themes with dark code blocks) match ColaMD's dark diagram block.
11
+ - Fixed **Mermaid diagram colors drifting from the preview in PDF/HTML exports for non-Elegant themes** — exports re-derived the `--pele-*` tokens on a wrapper selector that never matched the serialized `<p><svg class="pele">` markup, so diagrams fell back to pele's built-in light palette (dark nodes/edges on dark themes, light gray surfaces where the theme wanted the code-block tone). Exports now use the runtime `--pele-*` values that `buildExportHTML` collects from the preview's `.cm-md-mermaid` into `:root`; a token block using the engine's own derivation is injected only when those runtime values are absent (e.g. no rendered mermaid node at export time).
12
+ - Fixed **preview blocks vanishing after viewing their source** — the engine (ColaMD 2.7.11) rendered mermaid diagrams and multi-line block math as *inline* replace decorations spanning multiple lines; CodeMirror 6 only honors such decorations on the initial build, so after clicking into a diagram/formula (source revealed) and clicking away, the widget was never recreated and the whole block disappeared. Fixed with `block: true` for whole-line-covering replace decorations (mermaid always, block math when covering full lines). Patched via `patch-package` (`patches/`); the same fix is applied upstream in ColaMD-extend `live-preview.ts`.
13
+ - Fixed **Word export producing broken images** — puppeteer v25's `screenshot()` returns a `Uint8Array`; calling `.toString('base64')` on a TypedArray yields a comma-joined decimal byte string instead of base64, so every formula/diagram image embedded in the `.docx` was corrupt and exported as placeholder text. Screenshots are now converted with `Buffer.from()`.
14
+ - Fixed **Word-exported formulas rendering with wrong glyphs** — the formula screenshot page inlines `katex.min.css`, but its relative `url(fonts/*.woff2)` references can't resolve on a `page.setContent` (about:blank) page, so KaTeX fell back to system fonts. KaTeX fonts are now inlined as base64 data URIs at render time (and the font files are copied to `out/assets/katex-fonts/` by the build).
15
+
16
+ ### Changed
17
+ - **Export HTML/PDF now carries the engine's theme-scoped body rules** — the per-theme accent rules (`body.theme-x .cm-content .cm-md-strong`, inline code colors, heading colors, table header styling...) that live in the engine's `colamd.css` are extracted and translated to semantic selectors (`body.theme-x .colamd-document strong` ...) and injected into exports, so exported documents match the preview and ColaMD-extend rendering for all 12 built-in themes.
18
+ - `src/preview/webview/index.html` gives `.cm-md-mermaid` the code-block background in the preview; `src/preview/preview-manager.ts` applies the same block, plus the centering rule, to the serialized mermaid wrapper in HTML/PDF exports, and no longer redeclares `--pele-*` on the exported SVG.
19
+
20
+ ### Removed
21
+ - Ineffective settings removed from the extension manifest: `colaview.plugins.math` and `colaview.plugins.mermaid` (no-ops since v0.3.0 — math and Mermaid are built into the engine), `colaview.pdfMethod` and `colaview.customThemesPath` (never read by the extension). The dead `togglePlugin` message plumbing and the no-op `onDidChangeConfiguration` listeners they fed are gone too. Remaining settings: `colaview.theme`, `colaview.autoPreview`, `colaview.scrollSync`.
22
+
23
+ ## [0.3.1] - 2026-11-07
24
+
25
+ ### Changed
26
+ - **Engine upgrade: ColaMD 2.7.11** — `@bytechain.cn/colamd` bumped from 2.7.9 to 2.7.11, bringing upstream fixes: inline math rendered as formulas inside table cells, list indent handled purely by CSS (source spaces hidden), cursor misalignment with multi-digit ordered lists, block-level widget layout (no margin placeholders, diagram height re-measured after async render), and Enter/Backspace restored to official CodeMirror commands.
27
+
28
+ ### Fixed
29
+ - Fixed **Word-exported code blocks breaking on Windows** — ported ColaMD-extend #202 fixes: code font now written into all four `w:rFonts` slots with a platform-appropriate mono font (Menlo/Consolas/DejaVu Sans Mono) plus a dedicated CJK `eastAsia` font (so Chinese comments no longer garble); explicit left alignment prevents justify-stretched lines; code blocks get a light border and `noProof` (no spell-check squiggles on identifiers, inline code included).
30
+ - Fixed **Word-exported Mermaid diagrams not following the preview theme** — diagram colors are now derived from the current theme's tokens (surface/border mixes at 18%/28%/45%, same ratios as the editor), with dark themes falling back to the light palette. Previously hardcoded to mermaid's `neutral` theme.
31
+ - Fixed **inline formulas wrapping in Word export** — the measurement viewport was widened to 2000px so wider formulas are not line-wrapped by KaTeX before capture (mirrors ColaMD-extend `MEASURE_WIDTH`).
32
+ - Fixed **exported HTML/PDF diagrams losing theme colors and carrying zoom controls** — injected export CSS now matches serialized `<div><svg class="pele pele-…">` wrappers to restore the `--pele-*` variable mapping (mirrors ColaMD-extend a25b3f8), and hides the editor-only `.pele-zoom` controls that Chromium print cannot remove via scripts (mirrors `print-layout.ts`).
33
+
5
34
  ## [0.3.0] - 2026-11-06
6
35
 
7
36
  ### Added
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  [![VS Code](https://img.shields.io/badge/VS_Code-1.85%2B-007ACC?logo=visual-studio-code)](https://code.visualstudio.com/)
4
4
  [![TypeScript](https://img.shields.io/badge/TypeScript-5.7-3178C6?logo=typescript)](https://www.typescriptlang.org/)
5
5
  [![License](https://img.shields.io/badge/License-MIT-green)](LICENSE)
6
- [![Version](https://img.shields.io/badge/Version-0.3.0-orange)](package.json)
6
+ [![Version](https://img.shields.io/badge/Version-0.3.2-orange)](package.json)
7
7
 
8
8
  Rich Markdown preview & PDF/HTML/Word export for VS Code — powered by [ColaMD](https://github.com/byteuser1977/ColaMD-extend) rendering engine (CodeMirror 6 based).
9
9
 
@@ -105,15 +105,9 @@ Import custom CSS: `Ctrl+Shift+P` → "ColaView MD: Import Custom Theme..." or v
105
105
  | Setting | Type | Default | Description |
106
106
  |---------|------|---------|-------------|
107
107
  | `colaview.theme` | `string` | `"elegant"` | Preview theme: `light`, `dark`, `elegant`, `sepia`, `notion`, `bear`, `writer`, `solarized-dark`, `nord`, `gruvbox`, `dracula`, `midnight`, or any custom theme name |
108
- | `colaview.plugins.math` | `boolean` | `true` | *(Deprecated, always-on since v0.3.0)* KaTeX is built into the ColaMD engine and cannot be disabled |
109
- | `colaview.plugins.mermaid` | `boolean` | `true` | *(Deprecated, always-on since v0.3.0)* Mermaid is built into the ColaMD engine and cannot be disabled |
110
- | `colaview.pdfMethod` | `string` | `"puppeteer"` | PDF engine: `puppeteer` or `webviewPrint` |
111
108
  | `colaview.autoPreview` | `boolean` | `false` | Auto-open preview for `.md` files |
112
- | `colaview.customThemesPath` | `string` | `""` | Directory for custom theme CSS files |
113
109
  | `colaview.scrollSync` | `boolean` | `false` | **Experimental** — Enable scroll sync between editor and preview |
114
110
 
115
- > **Note on plugin settings:** Since v0.3.0, math and mermaid rendering are integral parts of the CodeMirror 6 based ColaMD engine and are always enabled. The `colaview.plugins.math` and `colaview.plugins.mermaid` settings are retained for backward compatibility but no longer have any effect.
116
-
117
111
  ## Supported Syntax
118
112
 
119
113
  **Standard Markdown** — Headings, bold, italic, strikethrough, code blocks, links, images, lists, blockquotes
@@ -212,11 +206,31 @@ npm run package
212
206
 
213
207
  ### Build System
214
208
 
215
- The project uses **esbuild** for bundling — the extension side (`out/extension.js`) is a small CJS bundle with only VS Code API imports. The WebView side (`out/preview/webview/app.js`) is an IIFE bundle containing the full ColaMD 2.7.9 rendering engine (CodeMirror 6 + Mermaid + KaTeX) — approximately 3.4MB unminified, gzip ~400KB. Resource files (CSS, WebView HTML, KaTeX stylesheet, Mermaid script) are copied to `out/` during build so they survive `.vscodeignore` packaging.
209
+ The project uses **esbuild** for bundling — the extension side (`out/extension.js`) is a small CJS bundle with only VS Code API imports. The WebView side (`out/preview/webview/app.js`) is an IIFE bundle containing the full ColaMD 2.7.11 rendering engine (CodeMirror 6 + Mermaid + KaTeX) — approximately 3.4MB unminified, gzip ~400KB. Resource files (CSS, WebView HTML, KaTeX stylesheet, Mermaid script) are copied to `out/` during build so they survive `.vscodeignore` packaging.
216
210
 
217
211
  ## Changelog
218
212
 
219
- ### v0.3.0 (Current)
213
+ ### v0.3.2 (Current)
214
+
215
+ - **🐛 PDF/HTML Export Fixed (`md is not defined`)** — exporting failed with "PDF export failed: md is not defined": a CSS comment inside the export stylesheet template literal contained unescaped backticks, which closed the literal early and made the parser treat part of the comment as JavaScript. Backticks are now escaped.
216
+ - **🐛 PDF/HTML Mermaid Diagrams Centered** — the engine serializes mermaid blocks as class-stripped `<p><svg class="pele pele-…">…</svg></p>`, so the previous `div:has(> svg.pele)` export rule never matched and diagrams were left-aligned on paper. Centering now applies to `svg.pele` itself (`display: block; margin: 0 auto`), independent of the wrapper element.
217
+ - **🎨 Mermaid Diagram Background Matches ColaMD-extend** — diagrams are now drawn on the code-block background (`--code-block-bg`, 6px radius, `0.8em 1em` padding) in both the preview and HTML/PDF exports, matching ColaMD instead of floating on the plain page background (most visible with Elegant/Bear, whose dark code blocks sit on light pages).
218
+ - **🎨 Mermaid Colors Match the Preview in Every Theme** — non-Elegant themes exported diagrams with different node/edge/label colors because the export re-declared `--pele-*` on a `div:has(> svg.pele)` selector that never matched the serialized `<p><svg class="pele">` markup, leaving pele's built-in palette in effect. Exports now use the runtime values collected from the preview into `:root`, with the derived token block injected only when those values are absent.
219
+ - **🧹 Removed Ineffective Settings** — `colaview.plugins.math` / `colaview.plugins.mermaid` (no-ops since v0.3.0) and `colaview.pdfMethod` / `colaview.customThemesPath` (never read) are gone; remaining settings: `colaview.theme`, `colaview.autoPreview`, `colaview.scrollSync`.
220
+ - **🐛 Preview Blocks No Longer Vanish After Source View** — Fixed an engine bug (multi-line inline replace decorations are ignored by CodeMirror 6 on incremental updates): clicking a mermaid diagram / multi-line block formula to view its source, then clicking away, no longer makes the whole block disappear. Patched via `patch-package`; fix also applied upstream in ColaMD-extend.
221
+ - **🐛 Word Export Images Fixed** — puppeteer v25 screenshot returns `Uint8Array`; the previous base64 conversion produced corrupt data so formulas/diagrams appeared as placeholder text in the `.docx`. Now converted with `Buffer.from()`.
222
+ - **🐛 Word Formula Glyphs Fixed** — KaTeX fonts are inlined as base64 into the screenshot page (the relative `fonts/*.woff2` URLs could not resolve), so formulas render with proper KaTeX fonts.
223
+ - **🎨 Exports Match Preview Colors** — The engine's theme-scoped body rules (bold/inline-code/heading accent colors per theme) are translated to semantic selectors and injected into HTML/PDF exports for all 12 themes.
224
+
225
+ ### v0.3.1
226
+
227
+ - **🔧 Engine Upgrade — ColaMD 2.7.11** — Inline math in table cells, CSS-driven list indent, block widget layout fixes, official CM6 typing commands.
228
+ - **🎨 Word Mermaid Diagrams Follow Theme** — Diagram colors derived from the current preview theme's tokens (dark themes fall back to light), instead of mermaid's hardcoded `neutral`.
229
+ - **🐛 Windows Word Code Blocks Fixed** — Platform mono font in all four `w:rFonts` slots + CJK `eastAsia` font, explicit left alignment, light border, `noProof` (port of ColaMD-extend #202).
230
+ - **🐛 Inline Formulas No Longer Wrap** — Wider (2000px) measurement viewport before capture.
231
+ - **🐛 HTML/PDF Diagrams Follow Theme + No Zoom Controls** — Export CSS matches serialized pele SVG wrappers to restore `--pele-*` variables; editor-only zoom controls hidden on paper.
232
+
233
+ ### v0.3.0
220
234
 
221
235
  - **📝 Word Export (`.docx`)** — Ported from ColaMD-extend. High-fidelity Word export with headings, paragraphs, inline styles, code blocks, lists, tables, blockquotes, horizontal rules, images, footnotes, and rasterized KaTeX/Mermaid diagrams.
222
236
  - **🎨 Theme-Faithful Export** — New `theme-style.ts` conversion layer maps editor-only theme selectors (`#editor .cm-content .cm-md-*`) to semantic HTML selectors, so PDF/HTML/Word exports inherit the current preview theme's fonts, accent colors, table header styling and blockquote padding.
package/README_CN.md CHANGED
@@ -3,7 +3,7 @@
3
3
  [![VS Code](https://img.shields.io/badge/VS_Code-1.85%2B-007ACC?logo=visual-studio-code)](https://code.visualstudio.com/)
4
4
  [![TypeScript](https://img.shields.io/badge/TypeScript-5.7-3178C6?logo=typescript)](https://www.typescriptlang.org/)
5
5
  [![License](https://img.shields.io/badge/License-MIT-green)](LICENSE)
6
- [![Version](https://img.shields.io/badge/Version-0.3.0-orange)](package.json)
6
+ [![Version](https://img.shields.io/badge/Version-0.3.2-orange)](package.json)
7
7
 
8
8
  VS Code 富文本 Markdown 预览与 PDF/HTML/Word 导出扩展 — 基于 [ColaMD](https://github.com/byteuser1977/ColaMD-extend) 渲染引擎(CodeMirror 6 内核)。
9
9
 
@@ -105,15 +105,9 @@ my-project/
105
105
  | 配置 | 类型 | 默认值 | 说明 |
106
106
  |------|------|--------|------|
107
107
  | `colaview.theme` | `string` | `"elegant"` | 预览主题:`light`、`dark`、`elegant`、`sepia`、`notion`、`bear`、`writer`、`solarized-dark`、`nord`、`gruvbox`、`dracula`、`midnight` 或任意自定义主题名 |
108
- | `colaview.plugins.math` | `boolean` | `true` | *(已废弃,v0.3.0 起默认启用)* KaTeX 已内置于 ColaMD 引擎,无法单独关闭 |
109
- | `colaview.plugins.mermaid` | `boolean` | `true` | *(已废弃,v0.3.0 起默认启用)* Mermaid 已内置于 ColaMD 引擎,无法单独关闭 |
110
- | `colaview.pdfMethod` | `string` | `"puppeteer"` | PDF 引擎:`puppeteer` 或 `webviewPrint` |
111
108
  | `colaview.autoPreview` | `boolean` | `false` | 打开 `.md` 文件时自动显示预览 |
112
- | `colaview.customThemesPath` | `string` | `""` | 自定义主题 CSS 目录路径 |
113
109
  | `colaview.scrollSync` | `boolean` | `false` | **实验性功能** — 启用编辑器与预览面板的滚动同步 |
114
110
 
115
- > **关于插件开关:** v0.3.0 起,数学公式和 Mermaid 图表是 CodeMirror 6 版 ColaMD 引擎的内置功能,始终启用。`colaview.plugins.math` 和 `colaview.plugins.mermaid` 配置项为向后兼容保留,但已不再生效。
116
-
117
111
  ## 支持的语法
118
112
 
119
113
  **标准 Markdown** — 标题、粗体、斜体、删除线、代码块、链接、图片、列表、引用
@@ -212,11 +206,31 @@ npm run package
212
206
 
213
207
  ### 构建系统
214
208
 
215
- 项目使用 **esbuild** 打包 — 扩展端(`out/extension.js`)是一个仅依赖 VS Code API 的小型 CJS bundle。WebView 端(`out/preview/webview/app.js`)是包含完整 ColaMD 2.7.9 渲染引擎(CodeMirror 6 + Mermaid + KaTeX)的 IIFE bundle — 未压缩约 3.4MB,gzip 后约 400KB。构建时自动复制资源文件(CSS、WebView HTML、KaTeX 样式表、Mermaid 脚本)到 `out/` 目录,确保打包安装后功能正常。
209
+ 项目使用 **esbuild** 打包 — 扩展端(`out/extension.js`)是一个仅依赖 VS Code API 的小型 CJS bundle。WebView 端(`out/preview/webview/app.js`)是包含完整 ColaMD 2.7.11 渲染引擎(CodeMirror 6 + Mermaid + KaTeX)的 IIFE bundle — 未压缩约 3.4MB,gzip 后约 400KB。构建时自动复制资源文件(CSS、WebView HTML、KaTeX 样式表、Mermaid 脚本)到 `out/` 目录,确保打包安装后功能正常。
216
210
 
217
211
  ## 更新日志
218
212
 
219
- ### v0.3.0(当前版本)
213
+ ### v0.3.2(当前版本)
214
+
215
+ - **🐛 修复 PDF/HTML 导出失败(`md is not defined`)** — 导出时报 "PDF export failed: md is not defined":导出样式模板字符串里的一段 CSS 注释含未转义的反引号,提前闭合了模板字面量,剩余注释被当成 JavaScript 解析。现已转义反引号,注释保持为注释。
216
+ - **🐛 修复 PDF/HTML 导出中 Mermaid 图未居中** — 引擎把 mermaid 块序列化成不带类名的 `<p><svg class="pele pele-…">…</svg></p>`,此前的 `div:has(> svg.pele)` 导出规则匹配不到,居中在纸面上失效。现把居中规则落到 `svg.pele` 自身(`display: block; margin: 0 auto`),与父级是 `<p>` 还是 `<div>` 无关。
217
+ - **🎨 Mermaid 图背景色与 ColaMD-extend 一致** — 图表配色按主题的代码块底色(`--code-block-bg`)推导,ColaMD 中图就画在这块底色上。预览与 HTML/PDF 导出现在同样给图加代码块底色(6px 圆角、`0.8em 1em` 内边距),不再浮在浅色页面上;Elegant/Bear(浅色页面配深色代码块)此前差异最明显。
218
+ - **🎨 修复非 Elegant 主题导出后 Mermaid 图内配色与预览不一致** — 导出端此前在 `div:has(> svg.pele)` 上重新声明 `--pele-*`,而引擎序列化出来的是 `<p><svg class="pele">` 结构,选择器从不命中,图只能落回 pele 内置浅色配色(深色主题下节点/连线/文字明显偏色)。现改为直接使用 `buildExportHTML` 从预览 `.cm-md-mermaid` 收集进 `:root` 的运行时令牌;仅在确实缺失时才按引擎同一公式补一份兜底。
219
+ - **🧹 移除无效配置项** — `colaview.plugins.math` / `colaview.plugins.mermaid`(自 v0.3.0 起无实际作用)与 `colaview.pdfMethod` / `colaview.customThemesPath`(从未被读取)已移除;保留 `colaview.theme`、`colaview.autoPreview`、`colaview.scrollSync`。
220
+ - **🐛 修复预览中块级内容「看源码后消失」** — 引擎 bug(跨行 inline replace 装饰在 CM6 增量更新时不会被重建):点击 mermaid 图 / 多行块公式查看源码后再点走,整块内容不再消失。通过 `patch-package` 固化补丁,修复同步提交到 ColaMD-extend 上游。
221
+ - **🐛 修复 Word 导出图片损坏** — puppeteer v25 截图返回 `Uint8Array`,此前的 base64 转换产出的是逗号十进制串,`.docx` 里公式/图表全部变成占位文本。现改用 `Buffer.from()` 转换。
222
+ - **🐛 修复 Word 公式字形错乱** — KaTeX 字体以 base64 内联进截图页(相对 `fonts/*.woff2` 路径无法解析),公式以正确的 KaTeX 字体渲染。
223
+ - **🎨 导出正文颜色与预览一致** — 引擎 colamd.css 中各主题的正文差异化规则(加粗/行内代码/标题配色)被翻译为语义化选择器并注入 HTML/PDF 导出,覆盖全部 12 套主题。
224
+
225
+ ### v0.3.1
226
+
227
+ - **🔧 引擎升级 — ColaMD 2.7.11** — 表格单元格内的行内公式成图、列表缩进纯 CSS 分派、块级 widget 布局修复、回车/退格回归 CM6 官方命令。
228
+ - **🎨 Word 导出 Mermaid 配色跟随主题** — 图表配色从当前预览主题令牌推导(深色主题回落浅色),替代原来写死的 mermaid `neutral`。
229
+ - **🐛 修复 Windows 下 Word 代码块乱码** — 等宽字体写入全部四个 `w:rFonts` 槽位 + 单独的 CJK `eastAsia` 中文字体、显式左对齐、浅色边框、`noProof`(移植 ColaMD-extend #202)。
230
+ - **🐛 修复行内公式在 Word 导出中被折行** — 截图前测量视口加宽到 2000px。
231
+ - **🐛 HTML/PDF 导出图表配色跟随主题 + 不再带缩放控件** — 导出 CSS 命中序列化后的 pele SVG 包裹结构恢复 `--pele-*` 变量映射;纸面上隐藏编辑器专属缩放控件。
232
+
233
+ ### v0.3.0
220
234
 
221
235
  - **📝 Word 导出(`.docx`)** — 从 ColaMD-extend 移植。高保真 Word 导出,支持标题、段落、行内样式、代码块、列表、表格、引用块、水平线、图片、脚注,以及 KaTeX/Mermaid 转图。
222
236
  - **🎨 导出保留主题样式** — 新增 `theme-style.ts` 转换模块,将编辑器专属选择器(`#editor .cm-content .cm-md-*`)映射为语义化 HTML 选择器,PDF/HTML/Word 导出继承当前预览主题的字体、强调色、表格表头样式和引用块内边距。
package/RELEASE_NOTES.md CHANGED
@@ -1,5 +1,96 @@
1
1
  # Release Notes
2
2
 
3
+ ## v0.3.2 (2026-11-07)
4
+
5
+ ### 🐛 PDF/HTML Export Fixed: `md is not defined`
6
+
7
+ Exporting to PDF (or HTML) failed with "PDF export failed: md is not defined".
8
+
9
+ **Root cause:** the export CSS injected by `patchExportHTML` is built as a JavaScript template literal, and a CSS comment inside it contained unescaped backticks (`` `.cm-md-mermaid` ``). The first backtick closed the template literal early, so the rest of the comment was parsed as JavaScript (`…template.cm - md - mermaid…`), throwing `ReferenceError: md is not defined` the moment an export ran.
10
+
11
+ **Fix:** the backticks in the comment are escaped. The comment stays a comment and the export CSS is emitted verbatim.
12
+
13
+ ### 🐛 PDF/HTML Export: Mermaid Diagrams Centered Again
14
+
15
+ Mermaid diagrams looked centered in the preview but sat flush against the left edge on paper.
16
+
17
+ **Root cause:** the engine serializes a mermaid block as a class-stripped `<p><svg class="pele pele-…">…</svg></p>`. The export CSS added in v0.3.1 targeted `div:has(> svg.pele)`, which can never match a `<p>` wrapper, so its `text-align: center` was inert.
18
+
19
+ **Fix:** centering now lives on `svg.pele` itself (`display: block; margin: 0 auto`), so it works regardless of whether the serializer emits a `<p>` or a `<div>`.
20
+
21
+ ### 🎨 Mermaid Diagram Background Matches ColaMD-extend
22
+
23
+ Diagram colors are derived from the theme's code-block background (`--code-block-bg`), and in ColaMD the diagram is drawn on that block background. ColaView's preview and exports instead floated the diagram on the plain page background — most visible with Elegant and Bear, whose light pages pair with dark code blocks, so the dark diagram stood on white instead of on the dark block.
24
+
25
+ The preview (`index.html`) now paints `.cm-md-mermaid` with the code-block background (6px radius, `0.8em 1em` padding), and the export CSS (`preview-manager.ts`) applies the same block to the serialized mermaid wrapper, so preview, PDF and HTML exports match ColaMD.
26
+
27
+ ### 🎨 Mermaid Colors Now Match the Preview in Every Theme
28
+
29
+ With non-Elegant themes, diagrams in exported PDF/HTML used a different color set than the preview — nodes, edges and labels drifted toward pele's built-in light palette instead of the theme's own tones.
30
+
31
+ **Root cause:** the export stylesheet re-declared the `--pele-*` color tokens on `div:has(> svg.pele)`, a selector that never matches the serialized `<p><svg class="pele">…</svg></p>` markup. The declarations were dead, and diagrams fell back to pele's defaults.
32
+
33
+ **Fix:** exports now use the tokens that `buildExportHTML` already collects from the preview's `.cm-md-mermaid` into `:root` — those are the exact colors the preview renders with, including any explicit overrides from custom themes. The derived token block is injected only when the runtime values are missing (e.g. no rendered mermaid node at export time), so no theme-aware value is ever overwritten.
34
+
35
+ ### 🧹 Removed Ineffective Settings
36
+
37
+ Four entries in the settings page did nothing, and they are now gone:
38
+
39
+ - `colaview.plugins.math` / `colaview.plugins.mermaid` — no-ops since v0.3.0, because math and Mermaid are built into the engine and cannot be toggled.
40
+ - `colaview.pdfMethod` / `colaview.customThemesPath` — never read by the extension (PDF always uses the local Chrome pipeline, themes always come from the workspace `.themes` directory).
41
+
42
+ The dead `togglePlugin` message plumbing and no-op configuration listeners were removed with them. The settings page now shows only `colaview.theme`, `colaview.autoPreview` and `colaview.scrollSync`.
43
+
44
+ ### 🐛 Preview: Blocks No Longer Vanish After Viewing Their Source
45
+
46
+ Clicking a rendered mermaid diagram or block formula reveals its source (per ColaMD-extend's block-widget rule); clicking away is supposed to re-render it — but the whole block silently disappeared instead.
47
+
48
+ **Root cause:** the engine rendered mermaid diagrams and multi-line block math as *inline* replace decorations spanning multiple lines. CodeMirror 6 only honors such decorations when the tree is built from scratch (initial load); on incremental updates the widget is never recreated — the decoration comparison even reports the change, but the render layer skips it, leaving an empty block.
49
+
50
+ **Fix:** whole-line-covering replace decorations now use `block: true` (mermaid always; block math when the range covers full lines). Verified in a headless browser: mermaid / multi-line math / tables all reveal source and restore correctly. Applied via `patch-package` (`patches/@bytechain.cn+colamd+2.7.11.patch`, wired through `postinstall`) and committed upstream to ColaMD-extend's `live-preview.ts`.
51
+
52
+ ### 🐛 Word Export: Formulas & Diagrams Now Render Correctly
53
+
54
+ Two independent bugs made every formula/diagram image in the exported `.docx` broken:
55
+
56
+ 1. **Corrupt image data** — puppeteer v25's `screenshot()` returns a `Uint8Array`; `Uint8Array.toString('base64')` ignores the argument and emits a comma-joined decimal byte string (`137,80,78,…`), which is not base64. The `.docx` image parser rejected it, so formulas/diagrams appeared as `[公式 1]` placeholder text. Screenshots are now converted with `Buffer.from()`.
57
+ 2. **Wrong glyph fonts** — the screenshot page inlines `katex.min.css`, but its relative `url(fonts/*.woff2)` references cannot resolve on a `page.setContent` page (about:blank base URL), so KaTeX fell back to system fonts. KaTeX fonts are now inlined as base64 data URIs at render time; the build also copies the font files to `out/assets/katex-fonts/` for packaged installs.
58
+
59
+ ### 🎨 Exports Match the Preview's Theme Colors
60
+
61
+ The engine's `colamd.css` carries per-theme body rules (`body.theme-x .cm-content .cm-md-strong`, inline code colors, heading colors, table header styling) that the exported semantic HTML could not match. These rules are now extracted from `colamd.css`, translated to semantic selectors (`body.theme-x .colamd-document strong` …), and injected into HTML/PDF exports — so exports match the preview (and ColaMD-extend) for all 12 built-in themes, including the ones whose accent rules only exist in the engine layer (sepia / dark / notion / midnight / writer).
62
+
63
+ ---
64
+
65
+ ## v0.3.1 (2026-11-07)
66
+
67
+ ### 🔧 Engine Upgrade — ColaMD 2.7.11
68
+
69
+ `@bytechain.cn/colamd` bumped from 2.7.9 to 2.7.11, bringing upstream fixes: inline math inside table cells rendered as formulas, list indent handled purely by CSS, cursor alignment with multi-digit ordered lists, block-level widget layout (diagram height re-measured after async render), and Enter/Backspace restored to official CodeMirror commands.
70
+
71
+ ### 🐛 Windows Word Code Blocks Fixed (ColaMD-extend #202)
72
+
73
+ Three Windows-only symptoms, one module:
74
+
75
+ 1. **Garbled code** — the mono font was written into all four `w:rFonts` slots; a macOS-only font made Word substitute the whole run with symbol glyphs. Now uses a platform mono font (Menlo / Consolas / DejaVu Sans Mono) plus a dedicated CJK `eastAsia` font so Chinese comments render properly.
76
+ 2. **Explicit left alignment** — code paragraphs inherited justified alignment, stretching every line to full width. Now explicitly left-aligned, single line spacing, with a light border and shading.
77
+ 3. **No spell-check squiggles** — `noProof` added to inline code and code block runs.
78
+
79
+ ### 🎨 Word Mermaid Diagrams Follow the Preview Theme
80
+
81
+ Exported diagrams were hardcoded to mermaid's `neutral` theme. Diagram colors are now derived from the current theme's tokens — surface/border mixes at 18% / 28% / 45%, the same ratios the editor uses — with dark themes falling back to the light palette (same rule as body text).
82
+
83
+ ### 🐛 Inline Formulas No Longer Wrap in Word
84
+
85
+ The rasterization viewport was widened to 2000px before measuring, so slightly-wide formulas are no longer line-wrapped by KaTeX inside the capture (port of ColaMD-extend's `MEASURE_WIDTH` fix).
86
+
87
+ ### 🐛 HTML/PDF Diagrams Follow Theme + No Zoom Controls
88
+
89
+ - Export CSS now matches the serialized `<div><svg class="pele pele-…">` wrappers to restore the `--pele-*` variable mapping, so diagrams keep the theme's colors (port of ColaMD-extend a25b3f8).
90
+ - The editor-only diagram zoom controls (`.pele-zoom`) are hidden in exports — Chromium print doesn't run scripts, so pele never gets the chance to remove them and they overlapped diagrams in PDFs (port of `print-layout.ts`).
91
+
92
+ ---
93
+
3
94
  ## v0.3.0 (2026-11-06)
4
95
 
5
96
  ### 🎨 Theme-Faithful Export
package/esbuild.js CHANGED
@@ -70,6 +70,12 @@ function copyResources() {
70
70
  if (fs.existsSync(katexCss)) {
71
71
  copies.push({ src: katexCss, dst: 'out/assets/katex.min.css' });
72
72
  }
73
+ // KaTeX 字体:Word 导出的公式截图页会把 katex.min.css 内联进 data: 页面,
74
+ // 相对字体 URL 解析不到,必须带上字体文件(运行时转 base64 内联)。
75
+ const katexFonts = 'node_modules/katex/dist/fonts';
76
+ if (fs.existsSync(katexFonts)) {
77
+ copies.push({ src: katexFonts, dst: 'out/assets/katex-fonts' });
78
+ }
73
79
  const mermaidJs = 'node_modules/mermaid/dist/mermaid.min.js';
74
80
  if (fs.existsSync(mermaidJs)) {
75
81
  copies.push({ src: mermaidJs, dst: 'out/assets/mermaid.min.js' });
package/package.json CHANGED
@@ -1,186 +1,164 @@
1
- {
2
- "name": "vscode-colaview",
3
- "displayName": "ColaView MD",
4
- "version": "0.3.0",
5
- "publisher": "bytechain",
6
- "description": "ColaMD Preview — Rich Markdown Preview & PDF/HTML Export for VSCode",
7
- "icon": "icon.png",
8
- "repository": {
9
- "type": "git",
10
- "url": "https://github.com/bytechain/vscode-colaview.git"
11
- },
12
- "license": "MIT",
13
- "engines": {
14
- "vscode": "^1.85.0"
15
- },
16
- "categories": [
17
- "Other"
18
- ],
19
- "activationEvents": [
20
- "onLanguage:markdown",
21
- "onCommand:colaview.showPreview",
22
- "onCommand:colaview.exportPDF",
23
- "onCommand:colaview.exportHTML",
24
- "onCommand:colaview.exportWord"
25
- ],
26
- "main": "./out/extension.js",
27
- "contributes": {
28
- "commands": [
29
- {
30
- "command": "colaview.showPreview",
31
- "title": "Show Preview",
32
- "icon": "$(open-preview)"
33
- },
34
- {
35
- "command": "colaview.exportPDF",
36
- "title": "Export to PDF...",
37
- "icon": "$(export)"
38
- },
39
- {
40
- "command": "colaview.exportHTML",
41
- "title": "Export to HTML...",
42
- "icon": "$(export)"
43
- },
44
- {
45
- "command": "colaview.exportWord",
46
- "title": "Export to Word...",
47
- "icon": "$(export)"
48
- },
49
- {
50
- "command": "colaview.switchTheme",
51
- "title": "Switch Preview Theme..."
52
- },
53
- {
54
- "command": "colaview.importTheme",
55
- "title": "Import Custom Theme..."
56
- }
57
- ],
58
- "menus": {
59
- "editor/title": [
60
- {
61
- "command": "colaview.showPreview",
62
- "group": "navigation"
63
- }
64
- ],
65
- "editor/context": [
66
- {
67
- "command": "colaview.showPreview",
68
- "group": "1_colaview"
69
- },
70
- {
71
- "command": "colaview.exportPDF",
72
- "group": "1_colaview"
73
- },
74
- {
75
- "command": "colaview.exportHTML",
76
- "group": "1_colaview"
77
- },
78
- {
79
- "command": "colaview.exportWord",
80
- "group": "1_colaview"
81
- }
82
- ],
83
- "explorer/context": [
84
- {
85
- "command": "colaview.exportPDF",
86
- "group": "1_colaview"
87
- },
88
- {
89
- "command": "colaview.exportHTML",
90
- "group": "1_colaview"
91
- },
92
- {
93
- "command": "colaview.exportWord",
94
- "group": "1_colaview"
95
- }
96
- ]
97
- },
98
- "configuration": {
99
- "title": "ColaView MD",
100
- "properties": {
101
- "colaview.theme": {
102
- "type": "string",
103
- "default": "elegant",
104
- "enum": [
105
- "light",
106
- "dark",
107
- "elegant",
108
- "sepia",
109
- "notion",
110
- "bear",
111
- "writer",
112
- "solarized-dark",
113
- "nord",
114
- "gruvbox",
115
- "dracula",
116
- "midnight"
117
- ],
118
- "description": "Visual theme for preview and export"
119
- },
120
- "colaview.plugins.math": {
121
- "type": "boolean",
122
- "default": true,
123
- "description": "Enable KaTeX math formula rendering"
124
- },
125
- "colaview.plugins.mermaid": {
126
- "type": "boolean",
127
- "default": true,
128
- "description": "Enable Mermaid diagram rendering"
129
- },
130
- "colaview.pdfMethod": {
131
- "type": "string",
132
- "default": "puppeteer",
133
- "enum": [
134
- "puppeteer",
135
- "webviewPrint"
136
- ],
137
- "description": "PDF export method"
138
- },
139
- "colaview.autoPreview": {
140
- "type": "boolean",
141
- "default": false,
142
- "description": "Auto show preview on opening Markdown"
143
- },
144
- "colaview.customThemesPath": {
145
- "type": "string",
146
- "default": "",
147
- "description": "Custom theme CSS directory path"
148
- },
149
- "colaview.scrollSync": {
150
- "type": "boolean",
151
- "default": false,
152
- "description": "Enable scroll sync between editor and preview"
153
- }
154
- }
155
- }
156
- },
157
- "scripts": {
158
- "vscode:prepublish": "npm run esbuild-base -- --production",
159
- "esbuild-base": "node esbuild.js",
160
- "build": "node esbuild.js",
161
- "watch": "node esbuild.js --watch",
162
- "pretest": "npm run build",
163
- "test": "node ./out/test/runTest.js",
164
- "package": "vsce package"
165
- },
166
- "dependencies": {
167
- "@bytechain.cn/colamd": "^2.7.9",
168
- "docx": "^9.15.2",
169
- "katex": "^0.16.47",
170
- "mermaid": "^11.15.0",
171
- "puppeteer-core": "^25.1.0",
172
- "remark-gfm": "^4.0.1",
173
- "remark-parse": "^11.0.0",
174
- "unified": "^11.0.5"
175
- },
176
- "devDependencies": {
177
- "@types/katex": "^0.16.8",
178
- "@types/node": "^20.0.0",
179
- "@types/vscode": "^1.85.0",
180
- "@vscode/test-electron": "^2.4.0",
181
- "@vscode/vsce": "^3.0.0",
182
- "esbuild": "^0.28.0",
183
- "eslint": "^9.0.0",
184
- "typescript": "^5.7.0"
185
- }
186
- }
1
+ {
2
+ "name": "vscode-colaview",
3
+ "displayName": "ColaView MD",
4
+ "version": "0.3.2",
5
+ "publisher": "bytechain",
6
+ "description": "ColaMD Preview — Rich Markdown Preview & PDF/HTML Export for VSCode",
7
+ "icon": "icon.png",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/bytechain/vscode-colaview.git"
11
+ },
12
+ "license": "MIT",
13
+ "engines": {
14
+ "vscode": "^1.85.0"
15
+ },
16
+ "categories": [
17
+ "Other"
18
+ ],
19
+ "activationEvents": [
20
+ "onLanguage:markdown",
21
+ "onCommand:colaview.showPreview",
22
+ "onCommand:colaview.exportPDF",
23
+ "onCommand:colaview.exportHTML",
24
+ "onCommand:colaview.exportWord"
25
+ ],
26
+ "main": "./out/extension.js",
27
+ "contributes": {
28
+ "commands": [
29
+ {
30
+ "command": "colaview.showPreview",
31
+ "title": "Show Preview",
32
+ "icon": "$(open-preview)"
33
+ },
34
+ {
35
+ "command": "colaview.exportPDF",
36
+ "title": "Export to PDF...",
37
+ "icon": "$(export)"
38
+ },
39
+ {
40
+ "command": "colaview.exportHTML",
41
+ "title": "Export to HTML...",
42
+ "icon": "$(export)"
43
+ },
44
+ {
45
+ "command": "colaview.exportWord",
46
+ "title": "Export to Word...",
47
+ "icon": "$(export)"
48
+ },
49
+ {
50
+ "command": "colaview.switchTheme",
51
+ "title": "Switch Preview Theme..."
52
+ },
53
+ {
54
+ "command": "colaview.importTheme",
55
+ "title": "Import Custom Theme..."
56
+ }
57
+ ],
58
+ "menus": {
59
+ "editor/title": [
60
+ {
61
+ "command": "colaview.showPreview",
62
+ "group": "navigation"
63
+ }
64
+ ],
65
+ "editor/context": [
66
+ {
67
+ "command": "colaview.showPreview",
68
+ "group": "1_colaview"
69
+ },
70
+ {
71
+ "command": "colaview.exportPDF",
72
+ "group": "1_colaview"
73
+ },
74
+ {
75
+ "command": "colaview.exportHTML",
76
+ "group": "1_colaview"
77
+ },
78
+ {
79
+ "command": "colaview.exportWord",
80
+ "group": "1_colaview"
81
+ }
82
+ ],
83
+ "explorer/context": [
84
+ {
85
+ "command": "colaview.exportPDF",
86
+ "group": "1_colaview"
87
+ },
88
+ {
89
+ "command": "colaview.exportHTML",
90
+ "group": "1_colaview"
91
+ },
92
+ {
93
+ "command": "colaview.exportWord",
94
+ "group": "1_colaview"
95
+ }
96
+ ]
97
+ },
98
+ "configuration": {
99
+ "title": "ColaView MD",
100
+ "properties": {
101
+ "colaview.theme": {
102
+ "type": "string",
103
+ "default": "elegant",
104
+ "enum": [
105
+ "light",
106
+ "dark",
107
+ "elegant",
108
+ "sepia",
109
+ "notion",
110
+ "bear",
111
+ "writer",
112
+ "solarized-dark",
113
+ "nord",
114
+ "gruvbox",
115
+ "dracula",
116
+ "midnight"
117
+ ],
118
+ "description": "Visual theme for preview and export"
119
+ },
120
+ "colaview.autoPreview": {
121
+ "type": "boolean",
122
+ "default": false,
123
+ "description": "Auto show preview on opening Markdown"
124
+ },
125
+ "colaview.scrollSync": {
126
+ "type": "boolean",
127
+ "default": false,
128
+ "description": "Enable scroll sync between editor and preview"
129
+ }
130
+ }
131
+ }
132
+ },
133
+ "scripts": {
134
+ "vscode:prepublish": "npm run esbuild-base -- --production",
135
+ "esbuild-base": "node esbuild.js",
136
+ "build": "node esbuild.js",
137
+ "watch": "node esbuild.js --watch",
138
+ "pretest": "npm run build",
139
+ "test": "node ./out/test/runTest.js",
140
+ "package": "vsce package",
141
+ "postinstall": "patch-package"
142
+ },
143
+ "dependencies": {
144
+ "@bytechain.cn/colamd": "2.7.11",
145
+ "docx": "^9.15.2",
146
+ "katex": "^0.16.47",
147
+ "mermaid": "^11.15.0",
148
+ "puppeteer-core": "^25.1.0",
149
+ "remark-gfm": "^4.0.1",
150
+ "remark-parse": "^11.0.0",
151
+ "unified": "^11.0.5"
152
+ },
153
+ "devDependencies": {
154
+ "@types/katex": "^0.16.8",
155
+ "@types/node": "^20.0.0",
156
+ "@types/vscode": "^1.85.0",
157
+ "@vscode/test-electron": "^2.4.0",
158
+ "@vscode/vsce": "^3.0.0",
159
+ "esbuild": "^0.28.0",
160
+ "eslint": "^9.0.0",
161
+ "patch-package": "^8.0.1",
162
+ "typescript": "^5.7.0"
163
+ }
164
+ }
@@ -0,0 +1,22 @@
1
+ diff --git a/node_modules/@bytechain.cn/colamd/dist/lib/colamd-renderer.js b/node_modules/@bytechain.cn/colamd/dist/lib/colamd-renderer.js
2
+ index 371c127..b629313 100644
3
+ --- a/node_modules/@bytechain.cn/colamd/dist/lib/colamd-renderer.js
4
+ +++ b/node_modules/@bytechain.cn/colamd/dist/lib/colamd-renderer.js
5
+ @@ -25981,7 +25981,7 @@ function NF(t, e) {
6
+ e.push({
7
+ from: n.from,
8
+ to: n.to,
9
+ - deco: Wt.replace({ widget: new jF(n.code, n.block, n.from, n.to) })
10
+ + deco: Wt.replace({ widget: new jF(n.code, n.block, n.from, n.to), block: n.block && (function(t, e, r) { return t.doc.lineAt(e).from === e && t.doc.lineAt(Math.min(r, t.doc.length)).to === r; })(t, n.from, n.to) })
11
+ });
12
+ }
13
+ }
14
+ @@ -26071,7 +26071,7 @@ function KF(t, e, r) {
15
+ O.trim() && e.push({
16
+ from: n.from,
17
+ to: n.to,
18
+ - deco: Wt.replace({ widget: new FF(O, `${n.from}:${O.length}`, n.from, n.to) })
19
+ + deco: Wt.replace({ widget: new FF(O, `${n.from}:${O.length}`, n.from, n.to), block: !0 })
20
+ });
21
+ });
22
+ }
@@ -112,6 +112,14 @@ interface DocxContext {
112
112
  style: DocxStyle;
113
113
  bodyFont: string;
114
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 };
115
123
  bodySizeHalf: number;
116
124
  paragraphLine: number;
117
125
  codeSizeHalf: number;
@@ -240,6 +248,15 @@ function halfPoints(px: number): number {
240
248
  return Math.max(2, Math.round(px * 1.5));
241
249
  }
242
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
+
243
260
  /** em 距离 → twips(1px = 15 twips)。 */
244
261
  function emTwips(px: number, em: number): number {
245
262
  return Math.round(px * em * 15);
@@ -387,9 +404,10 @@ function inlineRuns(
387
404
  } else if (node.type === 'inlineCode') {
388
405
  runs.push(new TextRun({
389
406
  text: node.value ?? '',
390
- font: context.monoFont,
407
+ font: context.codeFont,
391
408
  size: context.codeSizeHalf,
392
409
  shading: { fill: context.style.inlineCodeBackground },
410
+ noProof: true, // 变量名不再带拼写红波浪线
393
411
  ...style,
394
412
  }));
395
413
  } else if (node.type === 'strong') {
@@ -570,6 +588,7 @@ function tableForNode(node: MarkdownNode, context: DocxContext): Table {
570
588
  }
571
589
 
572
590
  function codeParagraph(node: MarkdownNode, context: DocxContext, extra: IParagraphOptions = {}): Paragraph {
591
+ // 每一行自己一个 run,行间用 `<w:br/>`;空行也要留一个 break,不然空行会被吃掉。
573
592
  const lines = (node.value ?? '').replace(/\n+$/, '').split('\n');
574
593
  const children: ParagraphChild[] = lines.map((line, index) => (
575
594
  line === ''
@@ -577,17 +596,28 @@ function codeParagraph(node: MarkdownNode, context: DocxContext, extra: IParagra
577
596
  : new TextRun({
578
597
  text: line,
579
598
  break: index > 0 ? 1 : undefined,
580
- font: context.monoFont,
599
+ font: context.codeFont,
581
600
  size: context.codeSizeHalf,
582
601
  color: context.style.codeBlockText,
602
+ noProof: true, // 变量名不再带拼写红波浪线
583
603
  })
584
604
  ));
585
605
  const codeLine = Math.round(context.style.bodySize * 0.875 * 1.6 * 15);
586
606
  const codePad = emTwips(context.style.bodySize, 1.0);
607
+ const codeBorder = { color: context.style.border, space: 4, style: BorderStyle.SINGLE, size: 4 };
587
608
  return new Paragraph({
588
609
  ...extra,
610
+ // 显式左对齐:不写的话继承默认样式,默认是两端对齐时每一行都会被拉满行宽,
611
+ // 键留在左边、值被顶到右边(镜像 colamd-extend aad3bf6)。
612
+ alignment: AlignmentType.LEFT,
589
613
  shading: { fill: context.style.codeBlockBackground },
590
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
+ },
591
621
  children,
592
622
  });
593
623
  }
@@ -860,10 +890,17 @@ export async function markdownToDocx(input: DocxExportInput): Promise<Buffer> {
860
890
  prepareLists(tree.children, listState);
861
891
  const remoteImages = await remoteImagesFor(tree);
862
892
 
893
+ const monoFont = fontName(style.monoFontStack, true);
863
894
  const context: DocxContext = {
864
895
  style,
865
896
  bodyFont: fontName(style.bodyFontStack, false),
866
- monoFont: fontName(style.monoFontStack, true),
897
+ monoFont,
898
+ codeFont: {
899
+ ascii: monoFont,
900
+ hAnsi: monoFont,
901
+ cs: monoFont,
902
+ eastAsia: codeEastAsiaFont(),
903
+ },
867
904
  bodySizeHalf: halfPoints(style.bodySize),
868
905
  paragraphLine: Math.round(style.lineHeight * style.bodySize * 15),
869
906
  codeSizeHalf: halfPoints(style.bodySize * 0.875),
@@ -906,9 +943,11 @@ export async function exportWord(document: vscode.TextDocument): Promise<void> {
906
943
  const markdown = document.getText();
907
944
  const sourcePath = document.fileName;
908
945
 
909
- const { content, images, imageSizes } = await renderMathAndMermaidToImages(markdown);
946
+ // 先取主题令牌:Mermaid 图的配色跟随当前预览主题(浅色跟随、深色回落浅色),
947
+ // 再用同一份令牌构建 Word 文档样式,两边保持一致。
910
948
  const themeCss = ThemeManager.loadThemeCSS(ThemeManager.getCurrentTheme());
911
949
  const style = buildDocxStyleFromThemeCss(themeCss);
950
+ const { content, images, imageSizes } = await renderMathAndMermaidToImages(markdown, style);
912
951
  const buffer = await markdownToDocx({ content, sourcePath, images, imageSizes, style });
913
952
 
914
953
  const defaultName = document.fileName.replace(/\.md$/i, '.docx');
@@ -55,11 +55,154 @@ function readIfExists(p: string | null): string | null {
55
55
  }
56
56
  }
57
57
 
58
+ /**
59
+ * 把 katex.min.css 里相对路径的字体 URL 换成 base64 data URI。
60
+ *
61
+ * 公式截图页通过 page.setContent 加载(about:blank 基准),CSS 内联后
62
+ * `url(fonts/KaTeX_*.woff2)` 解析不到任何文件 —— KaTeX 全部退回回退字体,
63
+ * 公式字形错乱(问题表现就是「导出到 Word 时公式没有正确渲染」)。
64
+ * 字体优先取 CSS 同级的 fonts/ 目录,其次 out/assets/katex-fonts/,
65
+ * 最后回退 node_modules 的 katex 发行目录。
66
+ */
67
+ function inlineKatexFonts(css: string, cssPath: string): string {
68
+ const candidates = [
69
+ path.resolve(path.dirname(cssPath), 'fonts'),
70
+ path.resolve(__dirname, 'assets', 'katex-fonts'),
71
+ ];
72
+ try {
73
+ const katexDist = path.dirname(require.resolve('katex/package.json'));
74
+ candidates.push(path.join(katexDist, 'dist', 'fonts'), path.join(katexDist, 'fonts'));
75
+ } catch {
76
+ /* ignore */
77
+ }
78
+ const fontDir = candidates.find((dir) => fs.existsSync(dir));
79
+ if (!fontDir) return css;
80
+
81
+ const cache = new Map<string, string>();
82
+ const load = (file: string): string | null => {
83
+ if (cache.has(file)) return cache.get(file)!;
84
+ let dataUri: string | null = null;
85
+ try {
86
+ const buf = fs.readFileSync(path.join(fontDir, file));
87
+ dataUri = `data:font/woff2;base64,${buf.toString('base64')}`;
88
+ } catch {
89
+ /* ignore */
90
+ }
91
+ cache.set(file, dataUri ?? '');
92
+ return dataUri;
93
+ };
94
+
95
+ return css.replace(/url\(\s*['"]?(fonts\/[^)'"]+)['"]?\s*\)/g, (match, file: string) => {
96
+ const dataUri = load(file);
97
+ return dataUri ? `url(${dataUri})` : match;
98
+ });
99
+ }
100
+
58
101
  /** 是否为纯数字/货币式内容(避免把 "$5.99" 之类误判为行内公式)。 */
59
102
  function isPlainNumber(s: string): boolean {
60
103
  return /^[\d\s.,%\-+()]*$/.test(s);
61
104
  }
62
105
 
106
+ /** sRGB 按权重混合,等价于 `color-mix(in srgb, a w%, b)`。入参出参都不带 `#`。 */
107
+ function mixSrgb(a: string, b: string, weightA: number): string {
108
+ const parse = (hex: string) => [0, 2, 4].map((index) => Number.parseInt(hex.slice(index, index + 2), 16) || 0);
109
+ const [ra, ga, ba] = parse(a);
110
+ const [rb, gb, bb] = parse(b);
111
+ const mix = (x: number, y: number) => Math.max(0, Math.min(255, Math.round(x * weightA + y * (1 - weightA))));
112
+ return [mix(ra, rb), mix(ga, gb), mix(ba, bb)]
113
+ .map((value) => value.toString(16).padStart(2, '0'))
114
+ .join('')
115
+ .toUpperCase();
116
+ }
117
+
118
+ /**
119
+ * Mermaid 画图用的调色板令牌(镜像 colamd-extend diagramPrintPalette 的推导规则)。
120
+ * 令牌与 DocxStyle 同源:「浅色跟随主题、深色整体回落浅色」,混合比例照抄
121
+ * colamd.css 的 `.cm-md-mermaid`(18% / 28% / 45% 三档),两边要一起改。
122
+ */
123
+ export interface DiagramPalette {
124
+ background: string;
125
+ foreground: string;
126
+ accent: string;
127
+ }
128
+
129
+ /** 没有主题令牌时按浅色默认画(与 docx-exporter 的 DEFAULT_STYLE 同源)。 */
130
+ const DEFAULT_DIAGRAM_PALETTE: DiagramPalette = {
131
+ background: 'F6F8FA',
132
+ foreground: '24292F',
133
+ accent: '0969DA',
134
+ };
135
+
136
+ function normalizeHex(value: unknown, fallback: string): string {
137
+ if (typeof value !== 'string') return fallback;
138
+ const raw = value.trim().replace(/^#/, '');
139
+ if (/^[0-9a-f]{6}$/i.test(raw)) return raw.toUpperCase();
140
+ if (/^[0-9a-f]{3}$/i.test(raw)) return raw.split('').map((digit) => digit + digit).join('').toUpperCase();
141
+ if (/^[0-9a-f]{8}$/i.test(raw)) return raw.slice(0, 6).toUpperCase();
142
+ return fallback;
143
+ }
144
+
145
+ /** 从主题令牌推导 Mermaid 的 themeVariables(theme: 'base')。 */
146
+ function mermaidThemeVariables(palette: DiagramPalette): Record<string, string> {
147
+ const { background: bg, foreground: fg } = palette;
148
+ const surface = mixSrgb(fg, bg, 0.18);
149
+ const surfaceAlt = mixSrgb(fg, bg, 0.28);
150
+ const border = mixSrgb(fg, bg, 0.45);
151
+ return {
152
+ background: `#${bg}`,
153
+ textColor: `#${fg}`,
154
+ primaryTextColor: `#${fg}`,
155
+ secondaryTextColor: `#${fg}`,
156
+ tertiaryTextColor: `#${fg}`,
157
+ primaryColor: `#${surface}`,
158
+ secondaryColor: `#${surfaceAlt}`,
159
+ tertiaryColor: `#${bg}`,
160
+ mainBkg: `#${surface}`,
161
+ clusterBkg: `#${surface}`,
162
+ clusterBorder: `#${border}`,
163
+ primaryBorderColor: `#${border}`,
164
+ secondaryBorderColor: `#${border}`,
165
+ tertiaryBorderColor: `#${border}`,
166
+ lineColor: `#${fg}`,
167
+ edgeLabelBackground: `#${bg}`,
168
+ noteBkgColor: `#${surfaceAlt}`,
169
+ noteTextColor: `#${fg}`,
170
+ noteBorderColor: `#${border}`,
171
+ actorBkg: `#${surface}`,
172
+ actorBorder: `#${border}`,
173
+ actorTextColor: `#${fg}`,
174
+ actorLineColor: `#${border}`,
175
+ signalColor: `#${fg}`,
176
+ signalTextColor: `#${fg}`,
177
+ labelBoxBkgColor: `#${surface}`,
178
+ labelBoxBorderColor: `#${border}`,
179
+ labelTextColor: `#${fg}`,
180
+ loopTextColor: `#${fg}`,
181
+ activationBkgColor: `#${surfaceAlt}`,
182
+ sequenceNumberColor: `#${bg}`,
183
+ sectionBkgColor: `#${surface}`,
184
+ altSectionBkgColor: `#${bg}`,
185
+ sectionBkgColor2: `#${surfaceAlt}`,
186
+ taskBkgColor: `#${surfaceAlt}`,
187
+ taskBorderColor: `#${border}`,
188
+ taskTextColor: `#${fg}`,
189
+ taskTextOutsideColor: `#${fg}`,
190
+ activeTaskBkgColor: `#${mixSrgb(palette.accent, bg, 0.28)}`,
191
+ activeTaskBorderColor: `#${palette.accent}`,
192
+ doneTaskBkgColor: `#${bg}`,
193
+ doneTaskBorderColor: `#${border}`,
194
+ critBkgColor: `#${mixSrgb(fg, bg, 0.45)}`,
195
+ critBorderColor: `#${fg}`,
196
+ todayLineColor: `#${palette.accent}`,
197
+ pie1: `#${surface}`,
198
+ pie2: `#${surfaceAlt}`,
199
+ pie3: `#${mixSrgb(palette.accent, bg, 0.18)}`,
200
+ pieTitleTextColor: `#${fg}`,
201
+ pieSectionTextColor: `#${fg}`,
202
+ pieStrokeColor: `#${border}`,
203
+ };
204
+ }
205
+
63
206
  /** 扫描 Markdown,用占位图重写公式/Mermaid 并收集各自内容。 */
64
207
  function scan(markdown: string): { content: string; items: RenderItem[] } {
65
208
  const items: RenderItem[] = [];
@@ -96,13 +239,30 @@ function scan(markdown: string): { content: string; items: RenderItem[] } {
96
239
  return { content: rewritten, items };
97
240
  }
98
241
 
99
- export async function renderMathAndMermaidToImages(markdown: string): Promise<RichImageResult> {
242
+ /**
243
+ * 公式/Mermaid 光栅化。`paletteTokens` 来自主题令牌(DocxStyle 的子集),
244
+ * Mermaid 图配色跟随当前预览主题;不传或令牌不全时按浅色默认画。
245
+ */
246
+ export async function renderMathAndMermaidToImages(
247
+ markdown: string,
248
+ paletteTokens?: { codeBlockBackground?: unknown; codeBlockText?: unknown; link?: unknown },
249
+ ): Promise<RichImageResult> {
250
+ const palette: DiagramPalette = paletteTokens
251
+ ? {
252
+ background: normalizeHex(paletteTokens.codeBlockBackground, DEFAULT_DIAGRAM_PALETTE.background),
253
+ foreground: normalizeHex(paletteTokens.codeBlockText, DEFAULT_DIAGRAM_PALETTE.foreground),
254
+ accent: normalizeHex(paletteTokens.link, DEFAULT_DIAGRAM_PALETTE.accent),
255
+ }
256
+ : DEFAULT_DIAGRAM_PALETTE;
100
257
  const { content, items } = scan(markdown);
101
258
  if (items.length === 0) {
102
259
  return { content, images: {}, imageSizes: {} };
103
260
  }
104
261
 
105
- const katexCss = readIfExists(assetPath('katex', path.join('dist', 'katex.min.css')));
262
+ const katexCssPath = assetPath('katex', path.join('dist', 'katex.min.css'));
263
+ const katexCssRaw = readIfExists(katexCssPath);
264
+ // 字体转 base64 内联:page.setContent 的页面解析不到相对字体路径
265
+ const katexCss = katexCssRaw && katexCssPath ? inlineKatexFonts(katexCssRaw, katexCssPath) : null;
106
266
  const mermaidJs = readIfExists(assetPath('mermaid', path.join('dist', 'mermaid.min.js')));
107
267
  const useMathml = !katexCss;
108
268
 
@@ -136,7 +296,7 @@ ${mermaidJs ? `<script>${mermaidJs}</script>` : ''}
136
296
  <script>
137
297
  (function () {
138
298
  if (!window.mermaid) { document.documentElement.dataset.ready = '1'; return; }
139
- mermaid.initialize({ startOnLoad: false, theme: 'neutral', securityLevel: 'loose' });
299
+ mermaid.initialize({ startOnLoad: false, theme: 'base', themeVariables: ${JSON.stringify(mermaidThemeVariables(palette))}, securityLevel: 'loose' });
140
300
  var els = Array.prototype.slice.call(document.querySelectorAll('pre.mermaid'));
141
301
  var remaining = els.length;
142
302
  if (remaining === 0) { document.documentElement.dataset.ready = '1'; return; }
@@ -167,7 +327,10 @@ ${mermaidJs ? `<script>${mermaidJs}</script>` : ''}
167
327
  const browser = await puppeteer.launch({ headless: true, executablePath: chromePath });
168
328
  try {
169
329
  const page = await browser.newPage();
170
- await page.setViewport({ width: 1200, height: 900, deviceScaleFactor: 1 });
330
+ // 测量用的窗口宽度。太窄的话稍宽的行内公式会在 KaTeX 内部折行,截出来的 PNG
331
+ // 本身就是两行(导出 Word 后看到「公式换行」,镜像 colamd-extend MEASURE_WIDTH)。
332
+ const MEASURE_WIDTH = 2000;
333
+ await page.setViewport({ width: MEASURE_WIDTH, height: 900, deviceScaleFactor: 1 });
171
334
  await page.setContent(html, { waitUntil: 'load' });
172
335
  // 等待 mermaid 渲染完成(无 mermaid 时页面立即置 ready)
173
336
  await page.waitForFunction("document.documentElement.dataset.ready === '1'", { timeout: 15000 })
@@ -182,7 +345,11 @@ ${mermaidJs ? `<script>${mermaidJs}</script>` : ''}
182
345
  if (!handle) continue;
183
346
  const box = await handle.boundingBox();
184
347
  if (!box || box.width < 1 || box.height < 1) continue;
185
- const shot = (await handle.screenshot({ type: 'png' })) as Buffer;
348
+ // puppeteer v25 起截图返回 Uint8Array(TypedArray 的 toString 会输出
349
+ // 「137,80,78,…」逗号十进制串而不是 base64),必须先转 Buffer,
350
+ // 否则 Word 里的图片数据全是坏的 —— 表现为图表/公式没有被正确渲染。
351
+ const raw = (await handle.screenshot({ type: 'png' })) as Buffer | Uint8Array;
352
+ const shot = Buffer.isBuffer(raw) ? raw : Buffer.from(raw as Uint8Array);
186
353
  if (!shot || shot.length === 0) continue;
187
354
 
188
355
  images[item.name] = `data:image/png;base64,${shot.toString('base64')}`;
@@ -100,6 +100,27 @@ export function translateThemeCssForExport(themeCss: string): string {
100
100
  return css.trim();
101
101
  }
102
102
 
103
+ /**
104
+ * 从 colamd.css(引擎内置样式)里提取主题作用域的正文规则并翻译成导出可用的语义选择器。
105
+ *
106
+ * 背景:各主题的正文差异化规则(加粗/行内代码/标题配色、表格表头、引用块等)以
107
+ * `body.theme-x .cm-content .cm-md-*` 形式写在引擎的 colamd.css 里,导出 HTML 虽然原样
108
+ * 内联了 colamd.css,但导出文档是语义化结构(.colamd-document strong 等),这些规则
109
+ * 全部无法命中 —— 表现为导出的加粗、行内代码等颜色与预览/ColaMD-extend 不一致。
110
+ * 这里按主题抽出这些规则,套用与 translateThemeCssForExport 相同的映射翻译后返回。
111
+ */
112
+ export function translateEngineThemeCssForExport(colamdCss: string): string {
113
+ if (!colamdCss) return '';
114
+
115
+ // 抽出所有 body.theme-* 作用域、且作用于编辑器内容层的规则块
116
+ const ruleRe = /body\.theme-[a-z0-9-]+[^{}]*\.cm-content[^{}]*\{[^}]*\}/g;
117
+ const rules = colamdCss.match(ruleRe);
118
+ if (!rules || rules.length === 0) return '';
119
+
120
+ const out = rules.join('\n');
121
+ return translateThemeCssForExport(out);
122
+ }
123
+
103
124
  /**
104
125
  * 从主题 CSS 构造 Word 导出用的样式令牌(docx 的 DocxStyle)。只覆盖能可靠取到的字段,
105
126
  * 其余由 markdownToDocx 的 normalizeStyle 回退到默认浅色样式。颜色返回原始值(hex),
package/src/extension.ts CHANGED
@@ -42,17 +42,6 @@ export function activate(context: vscode.ExtensionContext) {
42
42
  }
43
43
  }
44
44
 
45
- vscode.workspace.onDidChangeConfiguration(e => {
46
- if (!previewManager) return;
47
- const cfg = vscode.workspace.getConfiguration('colaview');
48
- if (e.affectsConfiguration('colaview.plugins.math')) {
49
- previewManager.togglePlugin('math', cfg.get('plugins.math', true));
50
- }
51
- if (e.affectsConfiguration('colaview.plugins.mermaid')) {
52
- previewManager.togglePlugin('mermaid', cfg.get('plugins.mermaid', true));
53
- }
54
- });
55
-
56
45
  console.log('ColaView: activated');
57
46
  }
58
47
 
@@ -6,7 +6,7 @@ import { ThemeManager } from '../themes/theme-manager';
6
6
  import { exportHTML } from '../export/html-exporter';
7
7
  import { exportPDF } from '../export/pdf-exporter';
8
8
  import { exportWord } from '../export/docx-exporter';
9
- import { translateThemeCssForExport } from '../export/theme-style';
9
+ import { translateThemeCssForExport, translateEngineThemeCssForExport } from '../export/theme-style';
10
10
 
11
11
  function getNonce(): string {
12
12
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
@@ -44,7 +44,6 @@ export class PreviewManager {
44
44
  constructor(private context: vscode.ExtensionContext) {
45
45
  this.registerActiveEditorListener();
46
46
  this.registerScrollSyncListeners();
47
- this.registerConfigurationListener();
48
47
  }
49
48
 
50
49
  private registerActiveEditorListener(): void {
@@ -135,18 +134,6 @@ export class PreviewManager {
135
134
  }
136
135
  }
137
136
 
138
- private registerConfigurationListener(): void {
139
- try {
140
- vscode.workspace.onDidChangeConfiguration((event) => {
141
- if (event.affectsConfiguration('colaview.scrollSync')) {
142
- // config changed, no action needed — will be checked on next scroll event
143
- }
144
- }, null, this.disposables);
145
- } catch (e) {
146
- console.error('[ColaView] registerConfigurationListener failed:', e);
147
- }
148
- }
149
-
150
137
  private isScrollSyncEnabled(): boolean {
151
138
  try {
152
139
  return vscode.workspace.getConfiguration('colaview').get<boolean>('scrollSync', false);
@@ -404,8 +391,69 @@ export class PreviewManager {
404
391
  // 翻译成语义选择器后注入到 </head> 前,保证优先级最高。
405
392
  const themeOverrideCss = translateThemeCssForExport(ThemeManager.loadThemeCSS(theme));
406
393
  const THEME_FIX = themeOverrideCss ? `<style>${themeOverrideCss}</style>` : '';
394
+ // colamd.css 里还有一批 body.theme-X .cm-content .cm-md-* 的正文差异化规则
395
+ // (sepia/dark/notion/midnight/writer 等主题的加粗、行内代码、标题配色只存在于
396
+ // 这一层),导出文档的语义化结构无法命中原选择器 —— 抽取并翻译后一并注入,
397
+ // 导出的正文颜色才能跟预览一致。
398
+ const ENGINE_THEME_FIX = `<style>${translateEngineThemeCssForExport(this.loadEngineColamdCss())}</style>`;
407
399
  const PRINT_FIX = `<style>@media print { body > article.colamd-document:not(#_) { display: block !important; } }</style>`;
408
- return patched.replace('</head>', PRINT_FIX + '\n' + THEME_FIX + '\n</head>');
400
+ // 导出文档里 mermaid 块被引擎序列化成不带类名的 `<p><svg class="pele pele-…">…</svg></p>`
401
+ // (实测 block widget 以非 .cm-line 子节点进入序列化,走段落分支,不是
402
+ // `hte('mermaid')` 的 `<div>` 分支)—— .cm-md-mermaid 上的居中、--pele-* 令牌、
403
+ // 代码块底色都随之丢掉。所以这里按导出文档的实际结构再补一份:<p> 容器给代码块底色
404
+ // (图和代码块共用一块底,和 ColaMD 导出一致),SVG 用 block + 左右 auto 外边距居中。
405
+ // 图上的缩放控件(.pele-zoom)是编辑器的东西,不是文档内容 —— 导出纸面上藏掉
406
+ // (镜像 colamd-extend print-layout.ts 的修复;Chromium 打印不执行脚本,
407
+ // pele 没机会收回它们,控件会叠在图上进 PDF)。
408
+ const MERMAID_FIX = `<style>
409
+ /* 图表配色不要在这里重新推导:buildExportHTML 已经把预览里 \`.cm-md-mermaid\` 上
410
+ 实际生效的 --pele-* 变量(含自定义主题显式覆盖的值)收进导出文档的 :root,
411
+ 那才是“预览中的配色”。导出端只需要补两件引擎序列化时丢掉的东西:
412
+ 代码块底色背景(图和代码块共用一块底)与居中。 */
413
+ .colamd-document .cm-md-mermaid,
414
+ .colamd-document p:has(> svg.pele) {
415
+ background: var(--code-block-bg);
416
+ border-radius: 6px;
417
+ padding: 0.8em 1em;
418
+ text-align: center;
419
+ }
420
+ .colamd-document svg.pele {
421
+ display: block; margin: 0 auto; max-width: 100%; height: auto;
422
+ }
423
+ .colamd-document .pele-zoom { display: none !important; }
424
+ </style>`;
425
+ // 兜底:导出那一刻文档里没有已渲染的 mermaid 节点(虚拟滚动把它们卸载了)时,
426
+ // 引擎收集不到 --pele-*,SVG 只能落回 pele 的浅色兜底色 —— 深色主题下整张图
427
+ // 会明显偏离预览。仅在 :root 确实缺这组令牌时按引擎同一份公式补一次;
428
+ // 已有运行时值的场景一律不动,避免覆盖预览里的真实配色。
429
+ const PELE_TOKEN_FALLBACK = /:root\s*\{[^}]*--pele-bg\s*:/i.test(patched)
430
+ ? ''
431
+ : `<style>:root {
432
+ --pele-bg: var(--code-block-bg);
433
+ --pele-fg: var(--code-block-text, var(--text-color));
434
+ --pele-muted: color-mix(in srgb, var(--code-block-text, var(--text-color)) 70%, var(--code-block-bg));
435
+ --pele-line: var(--code-block-text, var(--text-color));
436
+ --pele-surface: color-mix(in srgb, var(--code-block-text, var(--text-color)) 18%, var(--code-block-bg));
437
+ --pele-surface-alt: color-mix(in srgb, var(--code-block-text, var(--text-color)) 28%, var(--code-block-bg));
438
+ --pele-border: color-mix(in srgb, var(--code-block-text, var(--text-color)) 45%, var(--code-block-bg));
439
+ --pele-accent: var(--link-color);
440
+ --pele-radius: 6px;
441
+ }</style>`;
442
+ return patched.replace('</head>', PRINT_FIX + '\n' + MERMAID_FIX + '\n' + PELE_TOKEN_FALLBACK + '\n' + ENGINE_THEME_FIX + '\n' + THEME_FIX + '\n</head>');
443
+ }
444
+
445
+ /**
446
+ * 读取引擎自带的 colamd.css(与 WebView 加载的是同一份),供导出侧抽取主题规则。
447
+ */
448
+ private loadEngineColamdCss(): string {
449
+ const outDir = path.join(this.context.extensionPath, 'out', 'preview', 'webview');
450
+ const srcDir = path.join(this.context.extensionPath, 'src', 'preview', 'webview');
451
+ const webviewDir = fs.existsSync(outDir) ? outDir : srcDir;
452
+ try {
453
+ return fs.readFileSync(path.join(webviewDir, 'colamd.css'), 'utf-8');
454
+ } catch {
455
+ return '';
456
+ }
409
457
  }
410
458
 
411
459
  sendTheme(theme: string): void {
@@ -430,11 +478,6 @@ export class PreviewManager {
430
478
  this.panel.webview.postMessage({ type: 'themeList', ...list });
431
479
  }
432
480
 
433
- togglePlugin(id: string, enabled: boolean): void {
434
- if (!this.panel) return;
435
- this.panel.webview.postMessage({ type: 'togglePlugin', id, enabled });
436
- }
437
-
438
481
  private handleScrollSync(msg: { scrollPercent: number }): void {
439
482
  if (!this.isScrollSyncEnabled()) { return; }
440
483
 
@@ -198,11 +198,6 @@ window.addEventListener('message', async (event: MessageEvent) => {
198
198
  handle.applyTheme('custom:' + themeName, data.css);
199
199
  break;
200
200
  }
201
- case 'togglePlugin': {
202
- // 2.7.9 不再支持 togglePlugin — math 和 mermaid 是内置的
203
- // 此消息保留但不再执行操作,避免旧配置项报错
204
- break;
205
- }
206
201
  case 'themeList': {
207
202
  themeListData = {
208
203
  builtins: data.builtins || [],
@@ -50,6 +50,13 @@
50
50
  #editor .cm-scroller {
51
51
  overflow: auto;
52
52
  }
53
+ /* mermaid 图要画在代码块的深色底上(和 ColaMD 一致):图表配色是按
54
+ --code-block-bg 推出来的,浮在浅色页面上时整块底色和那边对不上。 */
55
+ #editor .cm-md-mermaid {
56
+ background: var(--code-block-bg);
57
+ border-radius: 6px;
58
+ padding: 0.8em 1em;
59
+ }
53
60
 
54
61
  /* ── Context Menu ── */
55
62
  .ctx-menu {