构建一个 C++ 为主导、Rust 工具为辅助 的高性能 Markdown 文档工具链,支持:
- 批处理模式:Markdown → HTML(含内联 SVG 图表)→ PDF
- Serve 模式:HTTP 服务器 + 文件监控 + WebSocket 推送,实现保存即刷新预览
核心目标:199 页含 200+ 图表的文档,首次构建 ≤ 20 秒,增量构建 ≤ 2 秒,serve 模式热更新 < 500ms。
| 组件 | 技术选型 | 版本要求 | 用途 |
| 主语言 | C++ | C++17 或更高 | 业务逻辑、解析调度、服务器 |
| 构建系统 | CMake | 3.15+ | 跨平台构建管理 |
| 包管理 | vcpkg / conan | 最新稳定版 | 管理 C++ 依赖(可选) |
| 辅助语言 | Rust | 1.70+ | 外部工具(mmdr, plantuml-little) |
| 库名称 | 用途 | 集成方式 |
| cmark | Markdown 解析 (CommonMark) | CMake + vcpkg,或源码编译 |
| cpp-httplib | HTTP 服务器(Serve 模式) | Header-only,下载即用 |
| websocketpp | WebSocket 通信(推送刷新信号) | Header-only,需链接 OpenSSL |
| efsw | 跨平台文件监控 | CMake + vcpkg,或源码编译 |
| nlohmann/json | JSON 序列化(配置文件/状态) | Header-only |
| {fmt} | 格式化输出/日志 | Header-only 或 CMake |
| openssl | WebSocket 依赖(可选 wss) | 系统安装或 vcpkg |
| Catch2 | 单元测试(可选) | Header-only |
| 工具 | 用途 | 安装命令 | 输出格式 |
| mmdr | Mermaid → SVG | cargo install mmdr | SVG |
| plantuml-little | PlantUML → SVG | cargo install plantuml-little | SVG |
| typst | Typst → SVG/PDF | cargo install typst-cli | SVG/PDF |
| tectonic | LaTeX → PDF | 包管理器或官网下载 | PDF |
| pdf2svg | PDF → SVG | apt install pdf2svg (Linux)
brew install pdf2svg (macOS) | SVG |
| wkhtmltopdf | HTML → PDF | 官网下载安装包 | PDF |
| 文件 | 用途 |
livereload.js | 客户端 WebSocket 连接与页面重载逻辑 |
style.css | 默认主题样式(可复用 mdbook 主题) |
highlight.js 或类似 | 语法高亮(可选) |
my-md-tool/
├── CMakeLists.txt # 主构建文件
├── README.md
├── .clang-format
├── .gitignore
├── build/ # 构建输出(CMake 生成)
│
├── src/
│ ├── main.cpp # CLI 入口
│ ├── config.cpp/h # 配置管理(解析 CLI 参数)
│ ├── markdown_parser.cpp/h # cmark 封装,提取代码块
│ ├── render_engine.cpp/h # 渲染调度器(主逻辑)
│ ├── renderers/
│ │ ├── mermaid_renderer.cpp/h # 调用 mmdr
│ │ ├── plantuml_renderer.cpp/h # 调用 plantuml-little
│ │ ├── typst_renderer.cpp/h # 调用 typst
│ │ └── latex_renderer.cpp/h # 调用 tectonic + pdf2svg
│ ├── cache_manager.cpp/h # 基于 SHA-256 的 SVG 缓存
│ ├── html_generator.cpp/h # AST → HTML(内联 SVG)
│ ├── pdf_generator.cpp/h # 调用 wkhtmltopdf 生成 PDF
│ ├── serve_server.cpp/h # HTTP + WebSocket 服务器
│ ├── file_watcher.cpp/h # efsw 封装,监听文件变化
│ ├── incremental_builder.cpp/h # 增量构建逻辑(哈希追踪)
│ └── utils.cpp/h # 工具函数(哈希、文件操作等)
│
├── include/ # 公共头文件(可选)
│ └── tool_common.h
│
├── third_party/ # 第三方依赖源码(若不用包管理)
│ ├── cmark/ # cmark 源码
│ ├── cpp-httplib/ # httplib.h
│ └── websocketpp/ # websocketpp 源码
│
├── resources/ # 前端资源(serve 模式用)
│ ├── livereload.js
│ ├── default.css
│ └── other static files
│
├── scripts/
│ ├── install_deps.sh # Linux/macOS 依赖安装脚本
│ ├── install_deps.ps1 # Windows 依赖安装脚本
│ └── test_deps.sh # 检测外部工具是否安装
│
└── tests/
├── test_parser.cpp
├── test_renderer.cpp
└── test_incremental.cpp
# CMakeLists.txt
cmake_minimum_required(VERSION 3.15)
project(my-md-tool VERSION 0.1.0 LANGUAGES CXX C)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# 寻找依赖
find_package(PkgConfig REQUIRED)
# cmark (通过 pkg-config 或 vcpkg)
pkg_check_modules(CMARK REQUIRED libcmark)
# 或者使用 vcpkg:
# find_package(cmark CONFIG REQUIRED)
# 添加子目录或头文件路径
add_subdirectory(third_party/cmark)
# 添加可执行文件
add_executable(my-md-tool src/main.cpp ...)
target_include_directories(my-md-tool PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/include
${CMARK_INCLUDE_DIRS}
)
target_link_libraries(my-md-tool
${CMARK_LIBRARIES}
pthread
stdc++fs # 或 experimental::filesystem,取决于编译器
)
# 如果是 HTTP/WS 模式,需要链接 OpenSSL
target_link_libraries(my-md-tool PRIVATE ssl crypto)
#!/bin/bash
# scripts/install_deps.sh - Linux/macOS
echo "Installing external rendering tools..."
# Rust 工具
if ! command -v cargo &> /dev/null; then
echo "Installing Rust..."
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
source "$HOME/.cargo/env"
fi
cargo install mmdr
cargo install plantuml-little
cargo install typst-cli
# 系统包
if [[ "$OSTYPE" == "linux-gnu"* ]]; then
sudo apt update
sudo apt install -y tectonic pdf2svg wkhtmltopdf
elif [[ "$OSTYPE" == "darwin"* ]]; then
brew install tectonic pdf2svg wkhtmltopdf
fi
echo "All dependencies installed."
// src/markdown_parser.h
#pragma once
#include <string>
#include <vector>
struct CodeBlock {
std::string lang; // "mermaid", "plantuml", "typst", "latex"
std::string content; // 代码块内容
size_t position; // 在文档中的位置(用于替换)
std::string hash; // 内容的 SHA-256 哈希
};
std::vector<CodeBlock> extract_code_blocks(const std::string& md_content);
std::string parse_markdown_to_html(const std::string& md_content,
const std::vector<CodeBlock>& blocks);
// src/markdown_parser.cpp
#include <cmark.h>
#include <unordered_map>
#include "markdown_parser.h"
#include "utils.h" // SHA-256
std::vector<CodeBlock> extract_code_blocks(const std::string& md_content) {
std::vector<CodeBlock> blocks;
auto* doc = cmark_parse_document(md_content.c_str(), md_content.size(), CMARK_OPT_DEFAULT);
auto* node = cmark_node_first_child(doc);
while (node) {
if (cmark_node_get_type(node) == CMARK_NODE_CODE_BLOCK) {
CodeBlock block;
block.lang = cmark_node_get_fence_info(node);
block.content = cmark_node_get_literal(node);
block.hash = sha256(block.content);
blocks.push_back(block);
}
node = cmark_node_next(node);
}
cmark_node_free(doc);
return blocks;
}
// src/render_engine.h
#pragma once
#include <string>
#include <vector>
#include <filesystem>
class RenderEngine {
public:
RenderEngine(const std::filesystem::path& cache_dir);
// 渲染单个图表,返回 SVG 字符串(若缓存命中则直接返回)
std::string render(const CodeBlock& block);
// 批量渲染,支持并行
std::vector<std::string> render_batch(const std::vector<CodeBlock>& blocks);
private:
std::filesystem::path cache_dir_;
std::string render_mermaid(const std::string& code);
std::string render_plantuml(const std::string& code);
std::string render_typst(const std::string& code);
std::string render_latex(const std::string& code);
bool get_from_cache(const std::string& hash, std::string& svg);
void save_to_cache(const std::string& hash, const std::string& svg);
};
// src/render_engine.cpp - 关键实现片段
std::string RenderEngine::render_mermaid(const std::string& code) {
// 1. 写入临时文件
fs::path tmp_file = fs::temp_directory_path() / (random_string() + ".mmd");
write_file(tmp_file, code);
// 2. 执行 mmdr
fs::path svg_file = tmp_file; svg_file.replace_extension(".svg");
std::string cmd = "mmdr " + tmp_file.string() + " -o " + svg_file.string();
int ret = system(cmd.c_str());
if (ret != 0) throw std::runtime_error("mmdr failed");
// 3. 读取 SVG
std::string svg = read_file(svg_file);
// 4. 清理临时文件
fs::remove(tmp_file);
fs::remove(svg_file);
return svg;
}
// src/cache_manager.cpp
#include <fstream>
#include <filesystem>
#include "utils.h"
bool RenderEngine::get_from_cache(const std::string& hash, std::string& svg) {
fs::path cache_path = cache_dir_ / (hash + ".svg");
if (fs::exists(cache_path)) {
svg = read_file(cache_path);
return true;
}
return false;
}
void RenderEngine::save_to_cache(const std::string& hash, const std::string& svg) {
fs::path cache_path = cache_dir_ / (hash + ".svg");
fs::create_directories(cache_dir_);
write_file(cache_path, svg);
}
// src/html_generator.cpp
std::string generate_html(const std::string& md_content,
const std::vector<CodeBlock>& blocks,
const std::vector<std::string>& svgs,
const std::string& title = "Document") {
// 1. 解析 Markdown 为 HTML(用 cmark)
// 2. 在 HTML 中按 position 插入 SVG 内联
// 3. 包装为完整 HTML 页面(含 head/body)
std::string html = cmark_markdown_to_html(md_content.c_str(), md_content.size(), CMARK_OPT_DEFAULT);
// 替换代码块占位为 SVG
// 这里简化:直接用 cmark 无法定位,需自定义解析或使用 marker
// 实践建议:在 Markdown 中插入标记如 <!-- BLOCK_0 -->,再用 replace
// ...
// 包装 HTML
return "<!DOCTYPE html><html><head><title>" + title + "</title></head><body>" + html + "</body></html>";
}
// src/pdf_generator.cpp
bool generate_pdf(const std::string& html_file, const std::string& pdf_file) {
std::string cmd = "wkhtmltopdf --enable-local-file-access "
+ html_file + " " + pdf_file;
return system(cmd.c_str()) == 0;
}
// src/serve_server.h
#pragma once
#include <httplib.h>
#include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.hpp>
class ServeServer {
public:
ServeServer(int port, const std::string& doc_path);
void start();
void broadcast_reload();
private:
int port_;
std::string doc_path_;
httplib::Server http_server_;
websocketpp::server<websocketpp::config::asio> ws_server_;
std::vector<websocketpp::connection_hdl> clients_;
std::mutex clients_mutex_;
void setup_http_routes();
void setup_websocket();
};
// src/serve_server.cpp - 部分实现
#include "serve_server.h"
ServeServer::ServeServer(int port, const std::string& doc_path)
: port_(port), doc_path_(doc_path) {
setup_http_routes();
setup_websocket();
}
void ServeServer::setup_http_routes() {
// 服务生成的 HTML
http_server_.Get("/", [this](const httplib::Request& req, httplib::Response& res) {
// 读取或生成 HTML
std::string html = generate_html_from_doc(doc_path_);
res.set_content(html, "text/html");
});
// 服务静态资源
http_server_.Get("/static/(.*)", [](const httplib::Request& req, httplib::Response& res) {
std::string file = "resources/" + req.matches[1];
if (fs::exists(file)) {
res.set_content(read_file(file), "text/css");
} else {
res.status = 404;
}
});
// WebSocket 升级路径
http_server_.Get("/ws", [this](const httplib::Request& req, httplib::Response& res) {
// websocketpp 需要单独处理
// 实际集成较复杂,建议用 websocketpp 独立监听端口或使用另一个库
// 简化:使用 httplib 的 WebSocket 支持(需修改版)或单独服务
});
}
// src/file_watcher.h
#pragma once
#include <efsw/efsw.hpp>
#include <functional>
#include <string>
class FileWatcher : public efsw::FileWatchListener {
public:
using Callback = std::function<void(const std::string& file)>;
FileWatcher(const std::string& path, Callback cb);
~FileWatcher();
void handleFileAction(efsw::WatchID watchid,
const std::string& dir,
const std::string& filename,
efsw::Action action,
std::string oldFilename) override;
private:
efsw::FileWatcher* watcher_;
Callback callback_;
};
// src/file_watcher.cpp
#include "file_watcher.h"
FileWatcher::FileWatcher(const std::string& path, Callback cb)
: callback_(cb) {
watcher_ = new efsw::FileWatcher();
watcher_->addWatch(path, this);
watcher_->watch();
}
FileWatcher::~FileWatcher() {
watcher_->removeAllWatches();
delete watcher_;
}
void FileWatcher::handleFileAction(efsw::WatchID watchid,
const std::string& dir,
const std::string& filename,
efsw::Action action,
std::string oldFilename) {
if (action == efsw::Actions::Modified || action == efsw::Actions::Add) {
callback_(dir + "/" + filename);
}
}
// src/incremental_builder.h
#pragma once
#include <string>
#include <unordered_map>
#include <filesystem>
struct BuildState {
std::unordered_map<std::string, std::string> file_hash; // path -> hash
std::vector<CodeBlock> last_blocks;
};
class IncrementalBuilder {
public:
IncrementalBuilder(const std::filesystem::path& state_file);
// 检查是否需要重建:返回 true 表示有变化
bool check_and_update(const std::string& md_file);
// 获取变更的代码块(相比上次)
std::vector<CodeBlock> get_changed_blocks(const std::vector<CodeBlock>& current);
private:
BuildState state_;
std::filesystem::path state_file_;
void load_state();
void save_state();
};
// src/incremental_builder.cpp
bool IncrementalBuilder::check_and_update(const std::string& md_file) {
load_state();
std::string new_hash = sha256_file(md_file);
auto it = state_.file_hash.find(md_file);
if (it == state_.file_hash.end() || it->second != new_hash) {
state_.file_hash[md_file] = new_hash;
save_state();
return true;
}
return false;
}
// resources/livereload.js
(function() {
const ws = new WebSocket('ws://' + window.location.host + '/ws');
ws.onopen = function() {
console.log('LiveReload connected');
};
ws.onmessage = function(event) {
if (event.data === 'reload') {
console.log('Reloading...');
location.reload();
}
};
ws.onclose = function() {
console.log('LiveReload disconnected, reconnecting in 3s...');
setTimeout(() => {
window.location.reload();
}, 3000);
};
})();
// src/main.cpp
#include <iostream>
#include <cxxopts.hpp> // 或者 getopt_long
int main(int argc, char** argv) {
// 解析参数
// 模式: build 或 serve
if (mode == "build") {
// 批处理模式
build_document(input, output_html, output_pdf);
} else if (mode == "serve") {
// Serve 模式
ServeServer server(port, input);
FileWatcher watcher(input, [&](const std::string& file) {
// 增量构建
IncrementalBuilder builder(".build_state.json");
if (builder.check_and_update(file)) {
auto blocks = extract_code_blocks(read_file(file));
auto changed = builder.get_changed_blocks(blocks);
// 只重新渲染 changed 块
RenderEngine engine(".cache");
for (auto& block : changed) {
engine.render(block);
}
// 重新生成 HTML
generate_and_save_html(file);
// 推送 WebSocket 刷新
server.broadcast_reload();
}
});
server.start();
}
return 0;
}
// 示例配置文件 .my-md-tool.json
{
"input": "book.md",
"output_html": "book.html",
"output_pdf": "book.pdf",
"cache_dir": ".cache",
"state_file": ".build_state.json",
"serve": {
"port": 3000,
"open_browser": true
},
"render": {
"parallel": true,
"threads": 4
}
}
# 开发构建(Linux/macOS)
mkdir build && cd build
cmake .. -DCMAKE_BUILD_TYPE=Release
make -j8
# 安装
sudo make install
# 使用
my-md-tool --input docs/book.md --output-html docs/book.html --output-pdf docs/book.pdf
# Serve 模式
my-md-tool --serve --input docs/book.md --port 8080
| 场景 | 测量指标 | 目标值 | 验证方法 |
| 首次全量构建(199页) | 总时间 | ≤ 20s | 计时 + 性能日志 |
| 缓存命中构建 | 总时间 | ≤ 10s | 重复运行两次,第二次计时 |
| 文本修改增量构建 | 解析+HTML生成时间 | < 500ms | 修改文本后计时 |
| 图表修改增量构建 | 渲染+重建时间 | < 2s | 修改图表源码后计时 |
| Serve 模式响应 | 文件变化到浏览器刷新 | < 1s | 浏览器控制台 + 计时 |
| 内存占用 | 峰值内存 | < 500MB | 监控工具(如 htop) |
| 生成的 PDF 大小 | 文件大小 | < 15MB(原 28MB) | 统计文件系统 |
- 支持多文件书籍:监听
SUMMARY.md,解析章节依赖图,仅重建变更章节。
- WebSocket 局部更新:不刷新整页,只替换变化的 DOM 元素(需前后端配合)。
- 接入更多图表工具:如
D2、Graphviz,统一抽象渲染接口。
- PDF 后台异步生成:大文档 PDF 不阻塞预览服务。
- 自定义模板系统:支持用户替换 HTML 模板与 CSS 主题。
| 风险 | 影响 | 缓解方案 |
| 外部工具未安装 | 功能不可用 | 启动时检测并给出清晰错误提示,提供自动安装脚本 |
| 跨平台路径差异 | 文件路径错误 | 使用 std::filesystem 统一处理 |
| 缓存目录膨胀 | 磁盘空间耗尽 | 提供 --clean 命令,或 LRU 淘汰策略 |
| 并行渲染冲突 | 临时文件名冲突 | 使用 mkstemp 或 std::random_device 生成唯一名 |
| wkhtmltopdf 不支持复杂 CSS | PDF 样式失真 | 备选 Qt WebEngine 或使用 Puppeteer 服务 |
- 二进制发布:使用 CMake 的
cpack 生成各平台安装包(.deb, .rpm, .dmg, .exe)。
- 源码发布:GitHub Release 包含源码与依赖安装脚本。
- 容器化:提供 Dockerfile,预装所有依赖,一键运行。
本方案通过 C++ 主导 + 原生渲染工具链 + 智能缓存与增量构建 + HTTP 热重载服务,实现了高性能的 Markdown 文档处理与实时预览工具。核心优势在于:
- 批处理模式:相比 mdbook + headless Chrome,速度提升 3~9 倍。
- Serve 模式:500ms 级增量刷新,接近 VS Code Live Preview 体验。
- 跨平台:C++ + CMake 保障 Windows/Linux/macOS 一致性。
- 可扩展:模块化设计,便于增加新图表类型或 PDF 引擎。
该方案可作为技术文档 CI/CD 工具链的核心组件,显著提升大型文档的构建与编辑效率。