mermaid

package module
v0.1.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 14, 2026 License: MIT Imports: 30 Imported by: 0

README

go-mermaid

CI codecov Go Reference Go Report Card

Render Mermaid diagrams to SVG in pure Go — no headless browser, no Node.js, no JavaScript runtime. Just a library and a single static binary.

Status: pre-1.0, actively developed. 20 diagram types supported (see the table below). Not affiliated with the Mermaid project; this is an independent, compatible renderer.

Rendered by go-mermaid (PNG at 2x):

Flowchart Sequence Class
flowchart sequence class
State ER Pie
state er pie
Gantt Git graph Mindmap
gantt gitgraph mindmap

Why

Every existing Go path to Mermaid SVG shells out to headless Chrome or a Node sidecar. That's heavy, slow, and hard to deploy. go-mermaid does the parse → layout → SVG pipeline natively, so you can render diagrams inside any Go service or CLI with zero external dependencies.

Install

Library:

go get github.com/zkrebbekx/go-mermaid

CLI:

go install github.com/zkrebbekx/go-mermaid/cmd/mermaid@latest

Homebrew:

brew install zkrebbekx/tap/mermaid

Docker:

echo "graph LR; A-->B" | docker run -i --rm ghcr.io/zkrebbekx/go-mermaid > out.svg

Prebuilt binaries for Linux/macOS/Windows (amd64/arm64) are attached to each GitHub release.

Usage

Library
package main

import (
	"os"

	mermaid "github.com/zkrebbekx/go-mermaid"
)

func main() {
	svg, err := mermaid.Render("graph TD\n  A[Start] --> B{OK?}\n  B -->|yes| C([Done])")
	if err != nil {
		panic(err)
	}
	os.WriteFile("diagram.svg", svg, 0o644)
}

With options:

svg, err := mermaid.Render(src,
	mermaid.WithTheme(mermaid.Dark),
	mermaid.WithFont("Inter", 14),
	mermaid.WithPadding(24),
	mermaid.WithSpacing(50, 60),
)
CLI
mermaid diagram.mmd > diagram.svg
echo "graph LR; A-->B-->C" | mermaid -theme dark -o out.svg
mermaid a.mmd b.mmd c.mmd      # batch: writes a.svg, b.svg, c.svg
mermaid -list-types            # list supported diagram types
mermaid -list-themes           # list themes
mermaid serve -addr :8080      # HTTP endpoint (POST source / GET ?src=, ?format=png)
mermaid -png -scale 2 -o d.png d.mmd   # PNG output (rasterized)
PNG output

The core library is dependency-free and emits SVG. PNG rasterization lives in a separate package so only PNG users pull the rasterizer dependency:

import "github.com/zkrebbekx/go-mermaid/raster"

img, err := raster.PNG("graph TD\n A --> B", 2) // 2 = scale factor

PNG is also available from the CLI (-png -scale N) and the HTTP server (?format=png&scale=N). Output formats: SVG (core) and PNG (raster).

Error handling

Render wraps stage-specific sentinels so you can branch on the failure, and parse errors carry source position:

svg, err := mermaid.Render(src)
if errors.Is(err, mermaid.ErrParse) {
	var pe *mermaid.ParseError
	if errors.As(err, &pe) {
		log.Printf("syntax error at line %d col %d: %s", pe.Line, pe.Col, pe.Msg)
	}
}

Sentinels: ErrParse, ErrLayout, ErrRender, ErrUnsupported.

Diagram types

The renderer dispatches on the diagram header. Status vs. Mermaid:

Type Header Notes
Flowchart graph / flowchart 12 shapes, subgraphs, styling, orthogonal edges
Sequence sequenceDiagram notes, activations, loop/alt/opt frames, autonumber
Class classDiagram members, 6 relationship types
State stateDiagram-v2 start/end, composite states
Entity-relationship erDiagram attributes, crow's-foot cardinality
Pie pie legend with percentages
User journey journey scored tasks, section bands
Quadrant quadrantChart axes, 4 quadrants, points
Git graph gitGraph branches, merges, tags
Timeline timeline sections, periods, events
Mindmap mindmap indentation hierarchy
Gantt gantt dates, durations, after deps
C4 C4Context / C4Container people, systems, relationships
Requirement requirementDiagram requirements, elements, typed relations
Sankey sankey-beta proportional flow bands
XY chart xychart-beta bar and line charts
Block block-beta column grid of labeled blocks
Kanban kanban columns of cards by indentation
Packet packet-beta bit/byte field table
Radar radar-beta polar chart with data curves

Flowchart extras: curved edges (WithCurvedEdges), clickable nodes (click ID href).

Unsupported types return ErrUnsupported. A ---/title: front-matter block and accTitle:/accDescr: (SVG <title>/<desc>) are honored for all types. Themes: default, dark, neutral, forest, base, plus custom palettes (WithCustomTheme). Background is configurable (WithBackground, WithTransparentBackground).

Rendering is fast — roughly 10–50µs per diagram with no external processes.

Flowchart syntax
Feature Example
Directions graph TD, TB, BT, LR, RL
Rectangle A[Label]
Rounded A(Label)
Stadium A([Label])
Circle A((Label))
Diamond A{Label}
Hexagon A{{Label}}
Subroutine A[[Label]]
Cylinder A[(Label)]
Parallelogram A[/Label/], A[\Label\]
Trapezoid A[/Label\], A[\Label/]
Arrow / open / dotted / thick A --> B, A --- B, A -.-> B, A ==> B
Edge label A -->|text| B, A -- text --> B
Subgraph subgraph Tend
Styling classDef, class, style, A:::cls
Link click A href "url"
Separators / comments A-->B; B-->C, %% comment
Sequence syntax
Feature Example
Participant participant A / actor A
Alias participant A as Alice
Message + arrowhead A->>B: text
Reply (dashed) B-->>A: text
Plain line A->B / A-->B
Cross end A-xB / A--xB
Self-message A->>A: text
Note Note right of A: text, Note over A,B: text
Activation A->>+B: ..., B-->>-A: ..., activate/deactivate
Frames loop/alt/opt/parend, autonumber

Roadmap

Done
  • 20 diagram types (see table above)
  • Sugiyama flowchart layout: crossing minimization, dummy-node bends, barycenter positioning, orthogonal + curved edges
  • Flowchart: 12 shapes, subgraphs, classDef/style/:::, clickable nodes
  • Sequence: notes, activations, loop/alt/opt frames, autonumber
  • Front-matter titles, accessibility (role/title/desc/accTitle), 5 themes, configurable/transparent background
  • SVG + PNG output (PNG via the raster subpackage)
  • CLI (stdin/file/batch, serve HTTP, -list-*), Render/RenderTo API
  • goconvey BDD tests, golden SVGs, fuzz-tested parsers, ~92% coverage
  • README examples gallery (sample PNG per diagram type)
  • Font-metric-aware label sizing (Helvetica advance widths)
  • Custom theme registration (WithCustomTheme)
  • Distribution: prebuilt binaries, Homebrew cask, ghcr.io Docker image
Later
  • Network-simplex ranking (tighter flowchart layouts)
  • Spline edge routing
  • Richer fidelity: class generics/annotations, sequence create/destroy/ highlight, ER attribute keys
  • More diagram types (architecture-beta, treemap, zenuml)
  • Toward v1.0: freeze the public API

Architecture

Each diagram type has a self-contained pipeline; the public Render dispatches on the header. The flowchart pipeline is:

source → lexer → parser → domain.Graph → layout → render → SVG

internal/domain holds the flowchart model; internal/sequence is the self-contained sequence pipeline; internal/theme and internal/svgutil are shared by all renderers. See CONTRIBUTING.md.

Releasing

Releases are automated with release-please + GoReleaser, driven by Conventional Commits. See RELEASING.md for the versioning policy and the optional AI code-review setup.

License

MIT © Zac Krebbekx

Documentation

Overview

Package mermaid renders Mermaid diagrams to SVG in pure Go, with no headless browser or JavaScript runtime required.

Supported diagram types are detected from the source header: flowchart (graph/flowchart), sequenceDiagram, classDiagram, stateDiagram-v2, erDiagram, pie, journey, quadrantChart, gitGraph, timeline, mindmap, gantt, C4 (C4Context/C4Container), requirementDiagram, sankey-beta, and xychart-beta. Unsupported types return ErrUnsupported; see DiagramTypes.

Render returns SVG. For PNG, use the github.com/zkrebbekx/go-mermaid/raster subpackage, which keeps the rasterizer dependency out of the core library.

Basic use:

svg, err := mermaid.Render("graph TD\n  A --> B")
if err != nil {
    log.Fatal(err)
}
os.Stdout.Write(svg)

Rendering is configured with functional options:

svg, err := mermaid.Render(src,
    mermaid.WithTheme(mermaid.Dark),
    mermaid.WithPadding(24),
)

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrParse indicates the source could not be lexed or parsed.
	ErrParse = errors.New("mermaid: parse error")
	// ErrLayout indicates the graph could not be laid out.
	ErrLayout = errors.New("mermaid: layout error")
	// ErrRender indicates the laid-out graph could not be rendered to SVG.
	ErrRender = errors.New("mermaid: render error")
	// ErrUnsupported indicates a diagram type or feature not yet implemented.
	ErrUnsupported = errors.New("mermaid: unsupported feature")
)

Sentinel errors returned by Render, wrapped around the underlying cause. Match them with errors.Is. For parse failures, errors.As can additionally recover a *parser.ParseError carrying source line/column.

Functions

func DiagramTypes

func DiagramTypes() []string

DiagramTypes returns the diagram header keywords this library can render.

func Render

func Render(src string, opts ...Option) (out []byte, err error)

Render parses a Mermaid source document and returns the rendered SVG.

Errors are wrapped so callers can match the failing stage with errors.Is (ErrParse, ErrLayout, ErrRender, ErrUnsupported) and, for parse failures, recover source position with errors.As(&ParseError{}).

Example

Render a simple flowchart to SVG.

package main

import (
	"fmt"
	"strings"

	mermaid "github.com/zkrebbekx/go-mermaid"
)

func main() {
	svg, err := mermaid.Render("graph TD\n  A[Start] --> B[End]")
	if err != nil {
		panic(err)
	}
	fmt.Println(strings.HasPrefix(string(svg), "<svg"))
}
Output:
true
Example (ErrorHandling)

Recover the source position of a parse error.

package main

import (
	"errors"
	"fmt"

	mermaid "github.com/zkrebbekx/go-mermaid"
)

func main() {
	_, err := mermaid.Render("graph TD\n  A[unterminated")
	fmt.Println(errors.Is(err, mermaid.ErrParse))

	var pe *mermaid.ParseError
	if errors.As(err, &pe) {
		fmt.Printf("error on line %d\n", pe.Line)
	}
}
Output:
true
error on line 2
Example (Options)

Configure rendering with functional options.

package main

import (
	"fmt"
	"strings"

	mermaid "github.com/zkrebbekx/go-mermaid"
)

func main() {
	svg, _ := mermaid.Render("graph LR\n  A --> B",
		mermaid.WithTheme(mermaid.Dark),
		mermaid.WithPadding(24),
	)
	fmt.Println(strings.Contains(string(svg), "#1e1e1e")) // dark background
}
Output:
true
Example (Sequence)

Render a sequence diagram; the diagram type is detected from the header.

package main

import (
	"fmt"
	"strings"

	mermaid "github.com/zkrebbekx/go-mermaid"
)

func main() {
	svg, _ := mermaid.Render("sequenceDiagram\n  Alice->>Bob: Hello")
	fmt.Println(strings.Contains(string(svg), ">Alice<"))
}
Output:
true

func RenderTo

func RenderTo(w io.Writer, src string, opts ...Option) error

RenderTo renders src and writes the SVG to w. It is a convenience over Render for HTTP handlers and file pipelines.

func Themes

func Themes() []string

Themes returns the names of all built-in themes.

Types

type Option

type Option func(*config)

Option configures a Render call. Options are applied in order; later options override earlier ones.

func WithBackground

func WithBackground(color string) Option

WithBackground overrides the diagram background color (any CSS color).

func WithCurvedEdges

func WithCurvedEdges(on bool) Option

WithCurvedEdges renders flowchart edges as smooth curves instead of straight orthogonal segments.

func WithCustomTheme

func WithCustomTheme(name string, p Palette) Option

WithCustomTheme registers a palette under name and selects it for this render. Subsequent renders can also reference the name via WithTheme.

func WithFont

func WithFont(face string, size float64) Option

WithFont sets the font family and base size (in pixels) for labels.

func WithPadding

func WithPadding(px float64) Option

WithPadding sets the outer padding (in pixels) around the diagram.

func WithSpacing

func WithSpacing(nodeSep, rankSep float64) Option

WithSpacing sets the gap between sibling nodes (nodeSep) and between ranks (rankSep), in pixels.

func WithTheme

func WithTheme(t Theme) Option

WithTheme sets the color palette.

func WithTransparentBackground

func WithTransparentBackground() Option

WithTransparentBackground removes the background rect so the diagram blends with whatever it is embedded in.

type Palette

type Palette = theme.Palette

Palette is a custom color set for WithCustomTheme.

type ParseError

type ParseError = syntax.Error

ParseError reports a lexing or parsing failure with its source position (Line, Col). When Render fails during the parse stage, the returned error wraps a *ParseError recoverable with errors.As.

type Theme

type Theme string

Theme selects a built-in color palette for rendering.

const (
	// Default is the light theme used when no theme is set.
	Default Theme = "default"
	// Dark is a dark-background palette.
	Dark Theme = "dark"
	// Neutral is a grayscale palette suitable for print.
	Neutral Theme = "neutral"
	// Forest is a green palette.
	Forest Theme = "forest"
	// Base is a muted neutral palette.
	Base Theme = "base"
)

Directories

Path Synopsis
cmd
mermaid command
Command mermaid renders Mermaid diagrams to SVG.
Command mermaid renders Mermaid diagrams to SVG.
internal
block
Package block parses and renders Mermaid block-beta diagrams to SVG as a column grid of labeled blocks.
Package block parses and renders Mermaid block-beta diagrams to SVG as a column grid of labeled blocks.
c4
Package c4 parses and renders Mermaid C4 diagrams (C4Context, C4Container, …) to SVG, reusing the shared layered layout engine.
Package c4 parses and renders Mermaid C4 diagrams (C4Context, C4Container, …) to SVG, reusing the shared layered layout engine.
class
Package class parses and renders Mermaid class diagrams to SVG.
Package class parses and renders Mermaid class diagrams to SVG.
domain
Package domain holds the pure diagram model: the types every other stage produces or consumes.
Package domain holds the pure diagram model: the types every other stage produces or consumes.
er
Package er parses and renders Mermaid entity-relationship diagrams (erDiagram) to SVG, reusing the shared layered layout engine.
Package er parses and renders Mermaid entity-relationship diagrams (erDiagram) to SVG, reusing the shared layered layout engine.
gantt
Package gantt parses and renders Mermaid gantt charts to SVG.
Package gantt parses and renders Mermaid gantt charts to SVG.
git
Package git parses and renders Mermaid gitGraph diagrams to SVG.
Package git parses and renders Mermaid gitGraph diagrams to SVG.
journey
Package journey parses and renders Mermaid user-journey diagrams to SVG.
Package journey parses and renders Mermaid user-journey diagrams to SVG.
kanban
Package kanban parses and renders Mermaid kanban diagrams to SVG as columns of cards, derived from indentation.
Package kanban parses and renders Mermaid kanban diagrams to SVG as columns of cards, derived from indentation.
layout
Package layout assigns coordinates to a domain.Graph using a layered (Sugiyama-style) approach: make the graph acyclic, rank nodes into layers, insert dummy nodes so long edges can bend, order within layers to reduce crossings, then assign positions with a barycenter heuristic.
Package layout assigns coordinates to a domain.Graph using a layered (Sugiyama-style) approach: make the graph acyclic, rank nodes into layers, insert dummy nodes so long edges can bend, order within layers to reduce crossings, then assign positions with a barycenter heuristic.
lexer
Package lexer turns Mermaid flowchart source into a flat token stream.
Package lexer turns Mermaid flowchart source into a flat token stream.
mindmap
Package mindmap parses and renders Mermaid mindmaps to SVG using an indentation-based hierarchy drawn as a left-to-right tree.
Package mindmap parses and renders Mermaid mindmaps to SVG using an indentation-based hierarchy drawn as a left-to-right tree.
packet
Package packet parses and renders Mermaid packet-beta diagrams to SVG as a bit/byte field table.
Package packet parses and renders Mermaid packet-beta diagrams to SVG as a bit/byte field table.
parser
Package parser turns a token stream into a domain.Graph.
Package parser turns a token stream into a domain.Graph.
pie
Package pie parses and renders Mermaid pie charts to SVG.
Package pie parses and renders Mermaid pie charts to SVG.
quadrant
Package quadrant parses and renders Mermaid quadrant charts to SVG.
Package quadrant parses and renders Mermaid quadrant charts to SVG.
radar
Package radar parses and renders Mermaid radar-beta charts to SVG as a polar plot with one polygon per data curve.
Package radar parses and renders Mermaid radar-beta charts to SVG as a polar plot with one polygon per data curve.
render
Package render turns a laid-out graph into SVG bytes.
Package render turns a laid-out graph into SVG bytes.
requirement
Package requirement parses and renders Mermaid requirement diagrams to SVG, reusing the shared layered layout engine.
Package requirement parses and renders Mermaid requirement diagrams to SVG, reusing the shared layered layout engine.
sankey
Package sankey parses and renders Mermaid sankey-beta diagrams to SVG as proportional flow bands between nodes arranged in columns.
Package sankey parses and renders Mermaid sankey-beta diagrams to SVG as proportional flow bands between nodes arranged in columns.
sequence
Package sequence parses, lays out, and renders Mermaid sequence diagrams to SVG.
Package sequence parses, lays out, and renders Mermaid sequence diagrams to SVG.
state
Package state parses and renders Mermaid state diagrams (stateDiagram-v2) to SVG, reusing the shared layered layout engine.
Package state parses and renders Mermaid state diagrams (stateDiagram-v2) to SVG, reusing the shared layered layout engine.
svgutil
Package svgutil holds small formatting helpers shared by the diagram renderers: deterministic number formatting and XML text escaping.
Package svgutil holds small formatting helpers shared by the diagram renderers: deterministic number formatting and XML text escaping.
syntax
Package syntax defines the positional error type shared by the lexer and parser.
Package syntax defines the positional error type shared by the lexer and parser.
theme
Package theme holds the color palettes shared by all diagram renderers.
Package theme holds the color palettes shared by all diagram renderers.
timeline
Package timeline parses and renders Mermaid timeline diagrams to SVG.
Package timeline parses and renders Mermaid timeline diagrams to SVG.
xychart
Package xychart parses and renders Mermaid xychart-beta diagrams (bar and line charts) to SVG.
Package xychart parses and renders Mermaid xychart-beta diagrams (bar and line charts) to SVG.
Package raster rasterizes go-mermaid SVG output to PNG.
Package raster rasterizes go-mermaid SVG output to PNG.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL