A fast Mermaid renderer written in C (-std=gnu2y).
It turns Mermaid source into SVG. It works as a command-line tool (mmd) and as a small C library (libmmd).
It needs no browser, no Node.js, no JavaScript engine and no dependencies beyond libc and libm.
- About 0.3–0.9 ms per diagram from the CLI. mermaid-cli takes about 0.4–1.1 s for the same diagrams (see Benchmarks).
- Library renders take about 18 µs for a small flowchart and about 0.7 ms for a 4 KB one.
- Flowchart layout follows dagre's algorithm, so node positions match mermaid's closely (mean node-centre error 1.6 px on the fixture set).
- All 432 syntax examples from mermaid's documentation render here (mermaid itself renders each of them).
Status: this is a young project. Output is meant to look like mermaid-cli 11.17's classic look (agentflow and use case, new in mermaid 12, like mermaid-cli 12.0.0), not to match it pixel for pixel. See Status and limitations.
| Family | Keywords |
|---|---|
| Flowchart | flowchart, graph (all directions, subgraphs, per-subgraph direction, every node shape, markdown strings, fa: icons, edge ids and animation, classDef/style/linkStyle) |
| Sequence | sequenceDiagram (actors and participant types, boxes, activations, notes, loop/alt/opt/par/critical/break blocks, autonumber) |
| Class | classDiagram, classDiagram-v2 |
| State | stateDiagram, stateDiagram-v2 |
| Entity relationship | erDiagram |
| Gantt | gantt |
| Pie | pie |
| User journey | journey |
| Timeline | timeline |
| Mindmap | mindmap |
| Quadrant | quadrantChart |
| XY chart | xychart, xychart-beta |
| Git graph | gitGraph |
| C4 | C4Context, C4Container, C4Component, C4Dynamic, C4Deployment |
| Requirement | requirementDiagram |
| Architecture | architecture, architecture-beta |
| Block | block, block-beta |
| Sankey | sankey, sankey-beta |
| Packet | packet, packet-beta |
| Kanban | kanban |
| Radar | radar, radar-beta |
| Treemap | treemap, treemap-beta |
| ZenUML | zenuml (native renderer in ZenUML's style) |
| Ishikawa (fishbone) | ishikawa, ishikawa-beta |
| Cynefin | cynefin, cynefin-beta |
| Venn | venn, venn-beta |
| Tree view | treeView, treeView-beta |
| Swimlane | swimlane-beta |
| Event modeling | eventmodeling |
| Railroad | railroad-beta, railroad-ebnf-beta, railroad-abnf-beta, railroad-peg-beta |
| Wardley map | wardley-beta |
| Agent flow | agentflow-beta (mermaid 12's neo look; look: classic with a classic theme draws a flowchart) |
| Use case | usecase-beta (actors, system boundaries and packages, include/extend/generalization, notes, JSON tables; mermaid 12's neo look, or look: classic with a classic theme) |
Every type also supports:
- the
default,base,dark,forestandneutralthemes; %%{init}%%and YAML front-matter config, withthemeVariablesderived as mermaid derives them when the source names a theme (theme: basewith aprimaryColorrecolours everything computed from it); without one, as in mermaid with a classic theme, a variable changes only what the diagram's styles read directly (flowchart, class and ER boxes readmainBkgandnodeBorder, state boxesstateBkg, soprimaryColoralone leaves them as they are). Values are whitelisted;accTitle/accDescr, which become<title>/<desc>plus ARIA attributes.
Per-type feature notes are in docs/dev/INTERNALS.md.
You need GNU make 4.3 or later and a C compiler that takes -std=gnu2y (e.g. GCC 15+ or Clang 23+).
make # build/release/mmd, build/release/libmmd.a, build/release/libmmd.so
make LINK=shared # mmd uses libmmd.so instead of holding a copy of libmmd.a
make CC=clang CFLAGS='-O2 -march=native' LDFLAGS=-fuse-ld=mold
make pgo # profile-guided build in build/pgo/
make install PREFIX=/usr DESTDIR=pkg # mmd, mmd.h, both libraries, mmd.pc (make uninstall removes them)
make test # what a change has to pass; about a secondPersistent build settings go in config.mk (recommended workflow):
# this configuration yields the best performance on my machine
CC = clang
CFLAGS = -O3 -march=native
LDFLAGS = -fuse-ld=wild
PREFIX = /usrbuild/release/mmd in.mmd -o out.svg
build/release/mmd -i in.mmd -o out.svg -t dark # themes: default | dark | forest | neutral (wins over the file's)
cat in.mmd | build/release/mmd > out.svg # stdin -> stdout
build/release/mmd in.mmd -o out.svg --no-avoid # flowchart: skip obstacle re-routing (fastest)On a syntax error the tool exits with a non-zero status and prints line:col: message.
The API is in include/mmd.h:
#include <stdio.h>
#include <string.h>
#include "mmd.h"
int main(void) {
const char *src = "flowchart LR\n A[Start] --> B{Ok?}\n B -- yes --> C[Done]\n";
mmd_buffer svg = {};
mmd_error err = {};
if (mmd_render_svg(strlen(src), src, nullptr, &svg, &err) != MMD_OK) {
fprintf(stderr, "%u:%u: %s\n", err.line, err.col, err.message);
return 1;
}
fwrite(svg.data, 1, svg.len, stdout);
mmd_buffer_free(&svg);
}cc -std=gnu23 -Iinclude example.c build/release/libmmd.a -lm # or: $(pkg-config --cflags --libs mmd)mmd_options(which may benullptr) sets node and rank spacing, font size, theme, and theMMD_F_*layout flags. A theme set there (or withmmd -t) wins over the one the diagram names; mermaid-cli's-tis only a default that the file'sthemeoverrides.- For batch rendering,
mmd_context_new()/mmd_context_render_svg()/mmd_context_free()reuse the arena and output buffer between calls, and the theme last derived from a named theme plusthemeVariables: a batch that repeats one such configuration derives it once (17–50 µs a render otherwise). Use one context per thread. - Errors come back as
mmd_statustogether withmmd_error(code, 1-based line and column, message). - The shared library exports only
mmd_*symbols. - Output does not depend on the host's
setlocale(): each render runs in the C locale on the calling thread only (uselocale), then restores the host's.
To write diagrams (test data, benchmark results), the writer half of include/mmd.h
builds the text and escapes every value for its context, so a label can hold any character:
mmd_writer *w = mmd_writer_new();
mmd_xy_begin(w, "Latency", false);
mmd_xy_x_cats(w, nullptr, 3, (const char *[]){"1 KiB", "64 KiB", "1 MiB"});
mmd_xy_bar(w, "p50 µs", 3, (double[]){12.5, 40.25, 610}, nullptr);
const char *text; size_t len;
if (mmd_writer_text(w, &text, &len, nullptr) == MMD_OK) /* save it as a .mmd... */
fwrite(text, 1, len, stdout);
if (mmd_writer_render_svg(w, nullptr, &svg, &err) == MMD_OK) /* ...or render it in memory */
use(svg.data, svg.len);
mmd_writer_free(w);Chart config is the same text mermaid reads. mmd_w_config writes an %%{init}%% directive
before the diagram (mmd_w_config(w, "xyChart.showDataLabel", "true")). XY chart keys:
xyChart.showDataLabel, xyChart.showDataLabelOutsideBar (value inside the bar, or past its
end), xyChart.barOverlap (libmmd only: several bar series share the full band, and a 0
draws nothing, so one series per group colours the bars; mermaid.js still parses the text and
draws the series side by side), xyChart.yAxis.scale: log (libmmd only: a log10 value axis, for
values that span orders of magnitude; mermaid.js draws a linear one), xyChart.width /
xyChart.height. A point label (mmd_xy_bar(w, name, n, v, labels), text 540 "PaLM") is
drawn past a line's point, and by libmmd past a bar's end too. A vertical chart wraps a
category label at spaces when it is wider than its band.
Typed helpers cover xychart (mmd_xy_*), pie, flowchart, sequence (mmd_seq_*), gantt, state,
sankey, mindmap, treeView, ER and gitGraph; they also handle each type's own traps (keywords at the
start of a statement, ER names with -, branch-name rules, gantt dates). Blocks they open (sequence
loop/alt, state groups, ER entities) close with mmd_end():
mmd_seq_begin(w, "Login", false);
mmd_seq_message(w, "client", "endpoint", MMD_ARROW_SOLID, "POST /login");
mmd_seq_block(w, "alt", "ok");
mmd_seq_message(w, "endpoint", "client", MMD_ARROW_DOTTED, "200; token");
mmd_seq_block(w, "else", "bad password");
mmd_seq_message(w, "endpoint", "client", MMD_ARROW_DOTTED, "401");
mmd_end(w);Errors are sticky (checked once at the end), numbers are written shortest-round-trip, and
mmd_w_str / mmd_w_text / mmd_w_id / mmd_w_csv / mmd_w_line cover every other diagram type
(MMD_W_LINESTART when text starts a statement, e.g. a timeline period or wardley component).
Which context each diagram slot takes is in docs/dev/writer.md.
All numbers below were measured on an AMD Ryzen 9 7945HX. Times are wall-clock for a whole process run, including process start-up. Each value is the best of 3 runs. Both native renderers were built with native CPU instructions and maximum optimization (libmmd: clang -O3 -march=native; mmdr: cargo release target-cpu=native).
The tools compared are:
mmd: this project;- mermaid-rs-renderer (
mmdr0.3.1, Rust); - mermaid-cli (
mmdc12.0.0, headless Chrome).
The run was made on 2026-11-17.
The chart shows each tool's CLI time on a log axis, each rival's bar labelled with how many times slower than libmmd it is; the table has the same numbers. Data: bench/cli_times.csv. build/release/bench/chart writes both, and libmmd draws the chart.
| input | libmmd | mmdr 0.3.1 | mermaid-cli 12.0 |
|---|---|---|---|
| flowchart_small (mmdr fixture) | 0.44 ms | 27.9 ms (63×) | 608 ms (1382×) |
| flowchart_medium (mmdr fixture) | 0.45 ms | 98.5 ms (219×) | 720 ms (1600×) |
| flowchart_large (mmdr fixture) | 0.89 ms | 276 ms (310×) | 1095 ms (1230×) |
| flowchart_mega_event_mesh (mmdr fixture) | 0.56 ms | 388 ms (692×) | 748 ms (1336×) |
| seq_full (tests/cases) | 0.31 ms | 1.67 ms (5.4×) | 455 ms (1468×) |
| class_full (tests/cases) | 0.42 ms | 5.95 ms (14×) | 831 ms (1979×) |
Rendering in-process through the library, timed with build/release/bench/render (minimum over repeated renders, clang build, from bench/results_v14.txt and bench/results_libmmd_inproc.txt):
| input | size in → SVG out | time |
|---|---|---|
bench/inputs/small.mmd |
376 B → 8.2 KB | 17.5 µs |
bench/inputs/medium.mmd |
4.4 KB → 66 KB | 703 µs |
bench/mmdr_fixtures/flowchart_large.mmd |
6.4 KB → 67 KB | 430 µs |
bench/inputs/large.mmd |
44 KB → 641 KB | 13.4 ms |
bench/inputs/xlarge.mmd |
143 KB → 2.0 MB | 80.6 ms |
bench/results_fixtures.txt has library and CLI times against mmdr for all 31 mmdr flowchart fixtures. To reproduce:
make build/release/bench/render build/release/bench/compare
build/release/bench/render bench/inputs/medium.mmd 30
MMDR=/path/to/mmdr build/release/bench/compare bench/mmdr_fixtures/*.mmdmermaid-cli spends most of its time starting Chrome. Its per-diagram cost is lower when it renders many diagrams in one process. The comparison is still useful for the common case of one CLI call per diagram.
Each image puts libmmd on the left and mermaid-cli on the right (11.17; 12.0.0 for agent flow and use case, which 11.17 lacks), rendered from the same source in tests/cases/. To regenerate them, run build/release/tools/sbs --gallery tests/cases/<name>.mmd.
| Flowchart with subgraphs |
Flowchart |
| Sequence |
Class |
| State |
ER |
| Gantt |
Git graph |
| Mindmap |
Architecture |
| C4 |
Sankey |
| Pie |
Timeline |
| XY chart |
Quadrant |
| Journey |
Agent flow |
| Use case |
More before/after pairs from development are in samples/sbs/.
| what | how |
|---|---|
The corpus through the CLI: 204 cases, mermaid's 432 documentation examples, 400 random flowcharts, the benchmark inputs. No crash; well-formed XML; everything drawn inside the viewBox; errors that name line and column; output byte-identical to the goldens (tests/golden/, tests/sums); every example mermaid renders, rendered; no CSS selector that matches nothing |
make test (UPDATE_GOLDEN=1 make test accepts changed output) |
Locale independence: the corpus rendered under a comma-decimal locale must match the C locale byte for byte (where none is installed the test compiles one with localedef) |
make test |
| Writer round trip: random labels through 102 slots of every diagram type, every typed helper (keyword-like ids included), number round trip, error paths | make test (build/release/tests/writer [iterations]) |
| Number formats and theme colours against values taken from d3-format and mermaid | make test |
Allocation failure: each malloc fails in turn; make oom also fails arena allocations, sampled, under ASan |
make test, make oom |
| All of the above under ASan + UBSan; then the corpus again with malloc'd memory filled with a byte, so that output read from an unwritten arena changes | make asan |
| All of the above under MemorySanitizer (clang) | make msan |
Fuzzing (mutational, under ASan + UBSan; crashing inputs are saved under TMPDIR and printed) |
make fuzz [N=1000] [SEED=1] |
| Writer vs mermaid.js: the writer test's corpus (~400 diagrams per seed) must parse in mermaid and show every label (skips without mermaid-cli) | build/release/tools/writer_check [-v] [--seeds=N] |
Which documentation examples mermaid itself renders (tests/docs/mermaid_status.txt) |
build/release/tools/docs status |
| Stress generator (every type, density 1×–5×) | build/release/tools/gen stress OUT 2 SEED SCALE |
| Visual quality scanner (edges through nodes, label overlaps, labels on edges, out-of-bounds…) | build/release/tools/quality_scan [files…] |
| Layout agreement with mermaid: node order along each axis, node-centre error, diagram proportions | build/release/tools/agree flow, build/release/tools/agree state, build/release/tools/agree size |
| Pictures beside mermaid's, before and after a change | build/release/tools/sbs [--base REV] files… |
make tools builds the programs of the lower rows. Those that compare with mermaid need node, mermaid-cli and Chrome: MMDC, MMDC_PUPPETEER and CHROME name them where PATH does not.
- Similar, not identical. Output follows mermaid-cli 11.17 in style and, for flowcharts, in layout (mermaid/dagre ordering and ranking). mermaid 12 draws flowcharts, sequence, class, state and ER in a new neo look by default, laid out with ELK; libmmd keeps the classic look and dagre layout for them, which mermaid 12 still draws with
look: classic,theme: defaultandlayout: dagre. Mermaid-generated CSS selectors and pixel-exact SVGs are not goals. Where mermaid's own output is broken (an invalid colour, data left out, a failed render, a setting it silently drops), libmmd draws what the source asks for rather than copy the fault; those cases are listed in docs/dev/INTERNALS.md. - Mindmap does not use mermaid's cose-bilkent layout. It uses its own radial and spring layout, so mindmaps look different from mermaid's.
- Architecture also has its own grid layout, not fcose.
- Text is measured with built-in Helvetica/Arial-compatible advance tables, not a real font engine. Unusual fonts can be sized imperfectly. CJK ideographs, kana and fullwidth forms are 1em (as in Noto Sans CJK, YaHei and PingFang); halfwidth forms are half an em; combining marks have no advance of their own; other letters use a Latin average.
- Dense charts. Pie, sankey, quadrant and Wardley move labels so they do not sit on each other, and gantt labels only every few ticks where mermaid's would overprint. Wardley draws a short leader when a label has to sit farther from its node, and a halo in the background colour when it still crosses a link. Labels with user-given coordinates stay where the author put them, so those can still overlap.
- Known differences from mermaid include xychart tick density. See docs/dev/INTERNALS.md.
fa:icons in flowcharts need the Font Awesome font where the SVG is viewed. Architecture and mindmap icons are embedded as paths.- Not supported: interactivity (
clickcallbacks, tooltips) and PNG/PDF output. To get a raster image, convert the SVG with any SVG rasteriser.
MIT. See LICENSE.
Embedded icon data comes from Font Awesome Free (CC BY 4.0) and simple-icons (CC0 1.0). See THIRD_PARTY_NOTICES.
libmmd 是一个用 C 语言(gnu2y)编写的高速 Mermaid 渲染器,可作为命令行工具 mmd 或 C 库 libmmd 使用。它把 Mermaid 源码直接渲染成 SVG,不需要浏览器、Node.js 或任何第三方依赖。
- 支持上表列出的全部 30 多种图表类型。
- 单个图表的命令行渲染约 1 毫秒,mermaid-cli 约 1 秒。
- 流程图采用与 mermaid(dagre)一致的布局算法。
构建只需 make,用法为 build/release/mmd in.mmd -o out.svg。效果对比见上方 Gallery。
许可证:MIT(见 LICENSE)。内嵌图标数据来自 Font Awesome Free(CC BY 4.0)和 simple-icons(CC0 1.0),详见 THIRD_PARTY_NOTICES。