---
name: d2-diagram
description: Generate diagrams using the D2 diagramming language. Use when the user requests diagrams.
---

# D2 Diagram

## Instructions

Generate D2 code following these guidelines.

### Basic Syntax

```d2
# Nodes and labels
node1
node2: Custom Label

# Connections
a -> b: label     # directed arrow (left to right)
a <- b: label     # directed arrow (right to left)
a <-> b: label    # bidirectional arrow
a -- b: label     # line (no arrows)

# Chained connections
a -> b -> c -> d
```

### Containers

```d2
# Dot notation (quick)
aws.ec2.instance

# Map syntax (structured)
aws: {
  ec2: {
    instance
  }
}

# Reference children with full path
aws.ec2.instance -> database
```

### Shapes

Available shapes: `rectangle`, `square`, `circle`, `oval`, `diamond`, `hexagon`, `parallelogram`, `cylinder`, `queue`, `package`, `step`, `page`, `document`, `callout`, `stored_data`, `person`, `cloud`

```d2
server: Web Server {shape: cylinder}
user: {shape: person}
cdn: {shape: cloud}
```

### UML Class Diagrams

```d2
MyClass: {
  shape: class
  +publicField: string
  -privateField: int
  #protectedField: bool
  +publicMethod(): void
  -privateMethod(arg: string): int
}
```

### SQL Tables

```d2
users: {
  shape: sql_table
  id: int {constraint: primary_key}
  email: varchar {constraint: unique}
  org_id: int {constraint: foreign_key}
}

orgs: {
  shape: sql_table
  id: int {constraint: primary_key}
  name: varchar
}

users.org_id -> orgs.id
```

### Markdown and Code Blocks

```d2
# Markdown content
readme: |`
# Title
- List item
- Another item
`|

# Code block with syntax highlighting
snippet: |`go
func main() {
    fmt.Println("Hello")
}
`|
```

## Guidelines

1. Write D2 code to `.d2` files
2. Use descriptive node IDs (e.g., `web_server` not `ws`)
3. Group related nodes in containers
4. Add labels to connections when they clarify relationships
5. Choose appropriate shapes for the domain (e.g., cylinder for databases, cloud for external services, person for users)
6. Render to PNG by default unless vector format is specifically requested

### Rendering

Render diagrams using the `d2` CLI. The output format is determined by the file extension.

```sh
# Render to SVG (vector)
d2 input.d2 output.svg

# Render to PNG (raster)
d2 input.d2 output.png

# Set layout engine (dagre is default, elk for complex diagrams)
d2 --layout=elk input.d2 output.png

# Set theme (0-8, or use theme name)
d2 --theme=3 input.d2 output.png

# Set padding around diagram
d2 --pad=50 input.d2 output.png

# Sketch mode (hand-drawn look)
d2 --sketch input.d2 output.png
```
