DEV Community

Yanchen Chen
Yanchen Chen

Posted on

Building a Formatter for Mermaid Diagrams

The Problem

Mermaid diagrams in codebases tend to accumulate inconsistent formatting – misaligned indentation, irregular spacing around arrows, extra blank lines. When multiple developers edit the same diagrams, it gets worse.

Unlike code (which has Prettier, ESLint, gofmt), there was no dedicated formatter for Mermaid syntax.

The Solution

I built mermaid-formatter – a zero-dependency TypeScript tool that parses Mermaid diagrams into an AST and outputs clean, consistently formatted code.

Key features

  • Nested block indentation: alt, loop, par, subgraph etc. are indented based on nesting depth
  • Context-aware parsing: else is only treated as block control inside alt, and only inside par
  • Arrow normalization: A->>B:msgA ->> B: msg (works across diagram types)
  • Markdown support: format all Mermaid code blocks in a Markdown file
  • CLI + library: use as mermaidfmt command or import formatMermaid() in code

Quick start

npm install -g mermaid-formatter

# Format to stdout
mermaidfmt diagram.mmd

# Format in-place
mermaidfmt -w diagram.mmd

# Format from stdin
echo "sequenceDiagram
  A->>B: hello" | mermaidfmt
Enter fullscreen mode Exit fullscreen mode

Links

Feedback welcome!

Top comments (1)

Collapse
 
chenyanchen profile image
Yanchen Chen

Update: mermaid-formatter now ships with a Prettier plugin! You can format .mmd files and Mermaid code blocks in Markdown through Prettier.

Setup:

npm install -D prettier mermaid-formatter
Enter fullscreen mode Exit fullscreen mode
// .prettierrc
{
  "plugins": ["mermaid-formatter/prettier-plugin"]
}
Enter fullscreen mode Exit fullscreen mode

Then prettier --write "**/*.mmd" and prettier --write "**/*.md" just work. Mermaid fenced code blocks inside Markdown are formatted automatically.

Details: GitHub