d2

command module
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: MPL-2.0 Imports: 2 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

D2 render example

Source code
vars: {
  d2-config: {
    layout-engine: elk
    theme-id: Terminal
  }
}
network: {
  cell tower: {
    satellites: {
      shape: stored_data
      style.multiple: true
    }

    transmitter

    satellites -> transmitter: send
    satellites -> transmitter: send
    satellites -> transmitter: send
  }

  online portal: {
    ui: {shape: hexagon}
  }

  data processor: {
    storage: {
      shape: cylinder
      style.multiple: true
    }
  }

  cell tower.transmitter -> data processor.storage: phone logs
}

user: {
  shape: person
  width: 130
}

user -> network.cell tower: make call
user -> network.online portal.ui: access {
  style.stroke-dash: 3
}

api server -> network.online portal.ui: display
api server -> logs: persist
logs: {shape: page; style.multiple: true}

network.data processor -> api server

Open in Playground · Browse more examples

Trusted by

Organizations around the world use D2 to power blog posts and docs both internally and externally. D2 is also integrated into many popular tools and services.

NVIDIA Google Amazon GitLab Samsung Stripe Alibaba Group LangChain UK Ministry of Justice

Quickstart

On macOS or Linux, run the install script.

curl -fsSL https://d2lang.com/install.sh | sh -s --

On x64 Windows, download the MSI installer from the latest release. The installation guide covers other platforms, package managers, and uninstalling.

Save x -> y -> z in a file named hello.d2, then run the following command to create hello.svg.

d2 hello.d2

With uv, run the native CLI directly with uvx d2lang hello.d2.

For a live preview in your browser, run d2 --watch hello.d2 and edit the file.

D2 as a library

You can render diagrams from Go with d2lib or from JavaScript and TypeScript with @d2lang/d2.

Go examples · D2.js usage guide

Themes

D2 includes a variety of official themes to style your diagrams beautifully right out of the box. See ./d2themes to browse the available themes and make or contribute your own creation.

Fonts

D2 ships with "Source Sans Pro" as the font in renders. If you wish to use a different one, please see ./d2renderers/d2fonts.

Export file types

D2 renders SVG, PNG, GIF, PDF, PowerPoint (.pptx), and text diagrams (.txt) without a browser. For example, d2 hello.d2 hello.txt draws the diagram with Unicode characters. Use --ascii-mode=standard for plain ASCII. Export guide

For animated SVG and GIF, set animate-interval and animate-duration in vars.d2-config. With TALA, newly appended SQL rows can drop into place while existing rows and connections stay anchored. Appending a sequence message can extend the activation bar and draw the arrow from sender to recipient. Animated TALA example · D2 source

Layout engines

D2 bundles three layout engines. Select one with --layout=dagre, --layout=elk, or --layout=tala. You can also set D2_LAYOUT or vars.d2-config.layout-engine in D2 source. Run d2 layout to list the engines or d2 layout <name> for their configuration options.

  • Dagro (default, bundled): A native Go port of the Dagre directed graph layout engine that produces layered/hierarchical layouts. Based on Graphviz's DOT algorithm.
  • elk-go (bundled): A native Go port of the ELK directed graph layout engine, particularly suited for node-link diagrams with an inherent direction and ports.
  • TALA (bundled): Native layout and edge-routing engine designed specifically for software architecture diagrams.

D2 also handles specialized layouts such as sequence diagrams and grids. Go applications can use the layout packages directly or provide layout and routing functions through d2lib.

Sketch-mode rendering uses rough-go, a native Go compatibility port of the Rough.js 4.6.6 rendering surface used by D2.

LaTeX labels use mathjax-go, a native Go port of the MathJax 3.2.2 TeX-to-SVG pipeline.

Comparison

For a comparison against other popular text-to-diagram tools, see https://text-to-diagram.com.

Contributing

Contributions are welcome! See ./docs/CONTRIBUTING.md. Parser and editor authors can use the structural grammar, lexical grammar, and conformance cases.

D2 is an independent open-source project fiscally sponsored by Hack Club. Sponsor D2

License

Open sourced under the Mozilla Public License 2.0. See ./LICENSE.txt.

We are constantly working on new plugins, integrations, extensions. Contributions are welcome in any official or community plugins. If you have somewhere in your workflow that you want to use D2, feel free to open a discussion. We have limited bandwidth and usually choose the most high-demand ones to work on. If you make something cool with D2 yourself, let us know and we'll be happy to include it here!

Official plugins

Community integrations

Libraries and publishing

  • Astro D2 — Render D2 code blocks in Astro or remark.
  • MkDocs D2 — Embed D2 diagrams in MkDocs pages.
  • d2-python — Build D2 source from typed Python. Includes a migration guide for py-d2.
  • VitePress D2 — Render D2 code blocks in VitePress.
  • mdBook D2 — Render D2 code blocks in mdBook.

Editors and notes

  • Zed — Add D2 language support in Zed.
  • JetBrains IDEs — Edit, format, and preview D2 diagrams.
  • Emacs Org Babel — Evaluate D2 source blocks in Org documents.
  • Logseq D2 — Render D2 diagrams offline in Logseq using WebAssembly.

Tools with D2 support

Misc

FAQ

  • Does D2 collect telemetry?
    • No, D2 does not use an internet connection after installation, except to check for version updates from Github periodically.
  • Does D2 need a browser to run?
    • No, D2 can run entirely server-side.
  • What's coming in the next release?
  • I have a question or need help.
    • The best way to get help is to ask on D2 Discord
  • I have a feature request, proposal, or bug report.
    • Please open up a Github Issue.
  • I have a private inquiry.

Documentation

The Go Gopher

There is no documentation for this package.

Directories

Path Synopsis
ci
tala-performance command
Command tala-performance measures TALA callbacks on an external D2 corpus and fingerprints complete layout outputs.
Command tala-performance measures TALA callbacks on an external D2 corpus and fingerprints complete layout outputs.
wasm-size command
wasm-size checks the D2.js WebAssembly module against ci/wasm-size-budget.txt: its size in bytes, and its size once compressed with Brotli at quality 11, which is close to what a browser downloads.
wasm-size checks the D2.js WebAssembly module against ci/wasm-size-budget.txt: its size in bytes, and its size once compressed with Brotli at quality 11, which is close to what a browser downloads.
wasm-strip command
wasm-strip removes the custom sections of a WebAssembly module in place.
wasm-strip removes the custom sections of a WebAssembly module in place.
TODO: Remove boxes and cleanup like d2ir
TODO: Remove boxes and cleanup like d2ir
Package d2compiler implements a parser, compiler and autoformatter for the Terrastruct d2 diagramming language.
Package d2compiler implements a parser, compiler and autoformatter for the Terrastruct d2 diagramming language.
Package d2ir implements a tree data structure to keep track of the resolved value of D2 keys.
Package d2ir implements a tree data structure to keep track of the resolved value of D2 keys.
d2elklayout
Package d2elklayout adapts D2 graphs to the native Go port of ELK.
Package d2elklayout adapts D2 graphs to the native Go port of ELK.
d2near
d2near applies near keywords when they're constants Intended to be run as the last stage of layout after the diagram has already undergone layout
d2near applies near keywords when they're constants Intended to be run as the last stage of layout after the diagram has already undergone layout
d2talalayout
Package d2talalayout adapts D2 graphs to TALA's layout and edge-routing engine.
Package d2talalayout adapts D2 graphs to TALA's layout and edge-routing engine.
d2talalayout/internal/engine
Package engine composes TALA's layout stages into one deterministic layout.
Package engine composes TALA's layout stages into one deterministic layout.
d2talalayout/internal/graphbounds
Package graphbounds computes work-accounted bounds for mutable TALA nodes.
Package graphbounds computes work-accounted bounds for mutable TALA nodes.
d2talalayout/internal/graphjson
Package graphjson serializes and reconstructs TALA layout graphs.
Package graphjson serializes and reconstructs TALA layout graphs.
d2talalayout/internal/grouping
Package grouping discovers and manages layout groups that temporarily move as a single vessel.
Package grouping discovers and manages layout groups that temporarily move as a single vessel.
d2talalayout/internal/hierarchy
Package hierarchy discovers DAG-like subgraphs, ranks their nodes, and places them in layers.
Package hierarchy discovers DAG-like subgraphs, ranks their nodes, and places them in layers.
d2talalayout/internal/invariant
Package invariant classifies violations of TALA's internal layout invariants.
Package invariant classifies violations of TALA's internal layout invariants.
d2talalayout/internal/labelgeom
Package labelgeom contains renderer-compatible label geometry that is shared by the mutable graph bounds and label-placement domains.
Package labelgeom contains renderer-compatible label geometry that is shared by the mutable graph bounds and label-placement domains.
d2talalayout/internal/labeling
Package labeling places node, icon, edge, and arrowhead labels on a routed layout graph.
Package labeling places node, icon, edge, and arrowhead labels on a routed layout graph.
d2talalayout/internal/layoutgraph
Package layoutgraph defines the mutable state used by TALA's layout algorithms.
Package layoutgraph defines the mutable state used by TALA's layout algorithms.
d2talalayout/internal/limits
Package limits provides the engine's topology ceilings and reusable work accounting primitives.
Package limits provides the engine's topology ceilings and reusable work accounting primitives.
d2talalayout/internal/loops
Package loops computes deterministic self-edge routes and the node extents those routes reserve during placement.
Package loops computes deterministic self-edge routes and the node extents those routes reserve during placement.
d2talalayout/internal/nodeshape
Package nodeshape defines the shape-specific port and label-placement policy used by TALA nodes.
Package nodeshape defines the shape-specific port and label-placement policy used by TALA nodes.
d2talalayout/internal/packing
Package packing arranges and compacts disconnected graph components without changing their internal layout or routed edge geometry.
Package packing arranges and compacts disconnected graph components without changing their internal layout or routed edge geometry.
d2talalayout/internal/placement
Package placement positions nodes and refines their geometry before routing.
Package placement positions nodes and refines their geometry before routing.
d2talalayout/internal/placementcost
Package placementcost evaluates candidate node geometry for placement and refinement algorithms.
Package placementcost evaluates candidate node geometry for placement and refinement algorithms.
d2talalayout/internal/proximity
Package proximity discovers layout relationships between nearby nodes.
Package proximity discovers layout relationships between nearby nodes.
d2talalayout/internal/quality
Package quality evaluates completed TALA layouts.
Package quality evaluates completed TALA layouts.
d2talalayout/internal/routing
Package routing builds orthogonal visibility graphs, searches them for edge routes, and applies the routing post-processing stages.
Package routing builds orthogonal visibility graphs, searches them for edge routes, and applies the routing post-processing stages.
d2talalayout/internal/trees
Package trees owns TALA's tree discovery, preprocessing, orientation, and placement algorithms.
Package trees owns TALA's tree discovery, preprocessing, orientation, and placement algorithms.
d2talalayout/internal/typedpool
Package typedpool provides a type-safe wrapper around sync.Pool.
Package typedpool provides a type-safe wrapper around sync.Pool.
internal/layoutguard
Package layoutguard protects layout engines that cannot be interrupted once their native layout call begins.
Package layoutguard protects layout engines that cannot be interrupted once their native layout call begins.
Completion implements lsp autocomplete features Currently handles: - Complete dot and inside maps for reserved keyword holders (style, labels, etc) - Complete discrete values for keywords like shape - Complete suggestions for formats for keywords like opacity
Completion implements lsp autocomplete features Currently handles: - Complete dot and inside maps for reserved keyword holders (style, labels, etc) - Complete discrete values for keywords like shape - Complete suggestions for formats for keywords like opacity
lspserver
Package lspserver implements the stdio language server for D2.
Package lspserver implements the stdio language server for D2.
d2renderers
d2ascii
Set DEBUG_ASCII=1 environment variable to enable verbose ASCII rendering debug logs.
Set DEBUG_ASCII=1 environment variable to enable verbose ASCII rendering debug logs.
d2fonts
Package d2fonts holds the fonts used to measure and render diagrams.
Package d2fonts holds the fonts used to measure and render diagrams.
d2raster
Package d2raster renders the supported d2scene subset with a pure-Go raster kernel.
Package d2raster renders the supported d2scene subset with a pure-Go raster kernel.
d2raster/internal/scanline
Package scanline rasterizes D2's closed vector paths with non-zero winding.
Package scanline rasterizes D2's closed vector paths with non-zero winding.
d2scene
Package d2scene defines the renderer-neutral scene representation used by D2's raster export pipeline.
Package d2scene defines the renderer-neutral scene representation used by D2's raster export pipeline.
d2scenebuild
Package d2scenebuild converts D2's typed export model into the immutable scene consumed by d2raster.
Package d2scenebuild converts D2's typed export model into the immutable scene consumed by d2raster.
d2svg
d2svg implements an SVG renderer for d2 diagrams.
d2svg implements an SVG renderer for d2 diagrams.
d2svg/appendix
Package appendix adds numbered footnotes to D2 SVGs and animation frames.
Package appendix adds numbered footnotes to D2 SVGs and animation frames.
d2svgimport
Package d2svgimport imports the bounded, network-free SVG subset used by D2 assets and MathJax into d2scene.
Package d2svgimport imports the bounded, network-free SVG subset used by D2 assets and MathJax into d2scene.
internal/codestyle
Package codestyle selects the Chroma palettes used to highlight diagram labels.
Package codestyle selects the Chroma palettes used to highlight diagram labels.
internal/fontface
Package fontface owns the renderer-internal OpenType parsing, shaping, and color-glyph pipeline shared by scene construction and native raster output.
Package fontface owns the renderer-internal OpenType parsing, shaping, and color-glyph pipeline shared by scene construction and native raster output.
internal/fontfallback
Package fontfallback contains the renderer-internal handoff used to retain trusted fallback assets across multiple scene builds without widening D2's public font resolver interface.
Package fontfallback contains the renderer-internal handoff used to retain trusted fallback assets across multiple scene builds without widening D2's public font resolver interface.
internal/patternassets
Package patternassets owns the canonical built-in texture definitions shared by D2's SVG and scene renderers.
Package patternassets owns the canonical built-in texture definitions shared by D2's SVG and scene renderers.
internal/scenepaint
Package scenepaint translates authored D2 paints into renderer-independent scenes.
Package scenepaint translates authored D2 paints into renderer-independent scenes.
internal/svgframe
Package svgframe reads the outer group emitted by d2svg for an animation.
Package svgframe reads the outer group emitted by d2svg for an animation.
d2themes defines themes to make d2 diagrams pretty Color codes: darkest (N1) -> lightest (N7)
d2themes defines themes to make d2 diagrams pretty Color codes: darkest (N1) -> lightest (N7)
docs
e2etests
report command
internal
bundledfont
Package bundledfont identifies the font files compiled into D2.
Package bundledfont identifies the font files compiled into D2.
d2layoutfeatures
Package d2layoutfeatures checks graph features against D2's built-in layouts.
Package d2layoutfeatures checks graph features against D2's built-in layouts.
d2string
Package d2string contains string syntax shared by the D2 parser and formatter.
Package d2string contains string syntax shared by the D2 parser and formatter.
geomath
Package geomath holds the arithmetic of lib/geo's segment intersection on plain coordinates, so that lib/shape and the layout code can intersect segments without allocating points or slices.
Package geomath holds the arithmetic of lib/geo's segment intersection on plain coordinates, so that lib/shape and the layout code can intersect segments without allocating points or slices.
grammartest
Package grammartest checks parser and end-to-end test fixtures against the syntax reference.
Package grammartest checks parser and end-to-end test fixtures against the syntax reference.
htmlentity
Package htmlentity unescapes HTML character references exactly as the standard library's html.UnescapeString does, without linking its entity table.
Package htmlentity unescapes HTML character references exactly as the standard library's html.UnescapeString does, without linking its entity table.
rasterimage
Package rasterimage decodes a deterministic still image from supported raster formats.
Package rasterimage decodes a deterministic still image from supported raster formats.
testlog
Package testlog adapts testing-style loggers to slog.
Package testlog adapts testing-style loggers to slog.
testutil/imagediff
Package imagediff compares rendered images and produces deterministic visual diagnostics suitable for test failures.
Package imagediff compares rendered images and produces deterministic visual diagnostics suitable for test failures.
testversion
Package testversion pins version metadata in the existing diagram goldens.
Package testversion pins version metadata in the existing diagram goldens.
lib
compression
d2 uses compression for compressing large static assets when its built into WASM for d2.js
d2 uses compression for compressing large static assets when its built into WASM for d2.js
env
geo
imageasset
Package imageasset resolves bounded local, HTTP, and data-URI image resources without depending on a renderer or scene representation.
Package imageasset resolves bounded local, HTTP, and data-URI image resources without depending on a renderer or scene representation.
imgbundler
Package imgbundler embeds generated SVG image references as data URIs.
Package imgbundler embeds generated SVG image references as data URIs.
localfile
Package localfile provides explicit policies for opening regular local files.
Package localfile provides explicit policies for opening regular local files.
log
Copied from https://pkg.go.dev/log/slog#Handler
Copied from https://pkg.go.dev/log/slog#Handler
memfs
memfs implements an in-memory fs.FS implementation This is useful in for running d2 in javascript environments where native file calls are not available
memfs implements an in-memory fs.FS implementation This is useful in for running d2 in javascript environments where native file calls are not available
netpolicy
Package netpolicy applies a network-boundary policy to HTTP clients used to fetch untrusted resources.
Package netpolicy applies a network-boundary policy to HTTP clients used to fetch untrusted resources.
pdf
png
pptx
pptx is a package to create slide presentations in pptx (Microsoft Power Point) format.
pptx is a package to create slide presentations in pptx (Microsoft Power Point) format.
simplelog
Package simplelog contains a very simple interface for logging strings at either Debug, Info, or Error levels
Package simplelog contains a very simple interface for logging strings at either Debug, Info, or Error levels
svg
xgif
Package xgif quantizes, normalizes, and encodes rendered animation frames as GIF.
Package xgif quantizes, normalizes, and encodes rendered animation frames as GIF.
xsort
Package xsort is the sorter of D2's own code: Func, StableFunc and Ordered are slices.SortFunc, slices.SortStableFunc and slices.Sort.
Package xsort is the sorter of D2's own code: Func, StableFunc and Ordered are slices.SortFunc, slices.SortStableFunc and slices.Sort.

Jump to

Keyboard shortcuts

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