Unicode Diagrams
Draw diagrams as plain text with Unicode box-drawing characters, in one house style.
Always build the diagram with the textdiagram.py grid engine below. Do not draw by hand:
hand-drawn diagrams drift out of alignment.
Style rules
- Plain text in a fenced code block. No Mermaid, SVG, images or emoji.
- Width: 80 columns by default. To change it, pass
max_widthto the constructor, for exampleD(max_width=100). The engine raises an error on a longer line. - All text is UPPER CASE. The engine does this for you: write normal text in the script.
Exception: units whose case changes the meaning stay as written, when you write them
exactly like this:
Hz kHz MHz GHz,kB MB GB TB KiB MiB GiB TiB,kb Mb Gb Tb kbps Mbps Gbps,ms µs ns. Other words, such as NGINX or K8S, are upper case. - COMPONENT box (a part of the system: service, client, database, queue, worker):
light lines
┌─┐ │ └─┘plus a light░shadow, one column right and one row down. To group parts, split one box into sections: light dividers├───┤, one frame, one shadow. - TITLE box (the main title of the doc, one per diagram): double lines
╔═╗ ║ ╚═╝, no shadow. One item per line (name, doc type, version), each line centered in the box. Make it withd.header(...): the engine centers the box over the whole diagram. Optional: a meta box on the left (company, RFC, date) and a stamp box on the right (status). All three get the same height; padding lines of the title box hold a centered dot·. No arrow can start or end at a header box. - FRAME box (section header, note, callout): light lines, no shadow.
Note / callout: put the name in the top border, like
┌─ NOTE ───┐. Do not add a legend: the style is the same in every diagram. - Free text (
d.annotate): a short remark with no box, beside the diagram. Use it rarely. A line must not cross it. - Horizontal arrow: label inside the line, one space each side:
── HTTPS ──▶. Both ends touch a box: the line starts on the shadow column of the sending box and the head touches the receiving box. - Vertical arrow: line starts from
┬on the bottom border, ends with▼. The label goes to the right of the line, one row below the shadow. Or cut the label into the line (inline=True): line, blank row, label lines centered on the line, blank row, line. - Bent arrow (
d.route): any number of bends, in any direction (▲ ▼ ◀ ▶). The label goes inside an across segment, or beside (or, withinline=True, cut into) an up/down segment. Lines that cross or join make a junction (┼ ├ ┤ ┬ ┴). A line never passes through a box. - Bus (
d.fan_out): one line from a box that splits into one arrow per target. The label goes on the shared line. - Arrow heads: filled
▶ ◀ ▲ ▼for the main flow. Hollow▷ ◁ △ ▽for a second kind of relation (asynchronous, optional, event). Use hollow only if the diagram needs two kinds, and name the meaning in a label or a note, not in a legend. - Label every arrow with what flows (protocol, event, data).
- If it is not clear which role a box has: COMPONENT for system parts, TITLE for the main title, FRAME for everything else.
Workflow
- List the components, frames and arrows before you draw.
- Write the engine to
/tmp/textdiagram/textdiagram.py(full source at the end of this file, copy it exactly). Write it again each session, so an old version is never used. - Write a short Python script that imports the engine and builds the diagram. Use the
layout helpers to place boxes (do not guess coordinates):
Diagram.x_right_of(a, label)— x for the next box to the right, with room for the arrow label.Diagram.x_left_of(a, lines, label)— x for a new box to the left ofa, with room for the label.Diagram.y_below(a)— y for a box belowa. With an inline label:Diagram.y_below(a, lines=N).Diagram.x_centered_under(a, lines)— x so a box sits centered undera(needed forarrow_v).- For route lanes, use the edges of the boxes:
a.right + 4,a.bottom + 2.
- Run it. If it raises
DiagramError, fix the layout as the message says and run again. - Paste the output into a code block exactly as printed. Do not edit it by hand. For a change, edit the script and run it again.
Example 1: header, sections, routes
import sys; sys.path.insert(0, "/tmp/textdiagram")
from textdiagram import Diagram as D
d = D() # max_width=80 is the default
t = d.header(["Order Platform", "Architecture"],
left=["Acme Inc", "RFC 9000", "Nov 2026"],
right=["*~~~~~~~~~*", "Deep Dive", "*~~~~~~~~~*"])
y = t.bottom + 2
cli = d.box(0, y, ["Client"]) # role="component" is default
gw = d.box(D.x_right_of(cli, "HTTPS"), y, ["Gateway"])
d.arrow_h(cli, gw, "HTTPS")
svc = d.box(gw.x + 16, D.y_below(gw) + 2, # sections: one box, one shadow
[["Auth"], ["Orders"], ["Billing"]], title="Services")
d.route(gw, "bottom", svc, "top", via=[gw.bottom + 3], label="Calls") # S shape
cache = d.box(D.x_left_of(svc, ["Cache"], "Reads"), svc.rows[1] - 1, ["Cache"])
d.arrow_h(svc, cache, "Reads", row=svc.rows[1]) # attach to one section
aud = d.box(svc.right + 9, y, ["Audit"])
d.route(svc, "right", aud, "bottom", a_row=svc.rows[0], label="Events") # one bend
d.route(svc, "right", cli, "bottom", a_row=svc.rows[2], # loop around: 3 bends
via=[svc.right + 4, svc.bottom + 2], label="Retry")
print(d.render())
Output:
┌────────────┐ ╔══════════════════╗ ┌───────────────┐
│ ACME INC │ ║ ORDER PLATFORM ║ │ *~~~~~~~~~* │
│ RFC 9000 │ ║ ARCHITECTURE ║ │ DEEP DIVE │
│ NOV 2026 │ ║ · ║ │ *~~~~~~~~~* │
└────────────┘ ╚══════════════════╝ └───────────────┘
┌──────────┐ ┌───────────┐ ┌─────────┐
│ CLIENT │── HTTPS ──▶│ GATEWAY │░ │ AUDIT │░
└──────────┘░ └─────┬─────┘░ └─────────┘░
░░░░░▲░░░░░░ ░░░░░│░░░░░░░ ░░░░▲░░░░░░
│ │ │
│ │ │
│ └───── CALLS ─────┐ │
│ │ │
│ ▼ │
│ ┌─ SERVICES ────┐ │
│ │ AUTH │─── EVENTS ───┘
│ ┌─────────┐ ├───────────────┤░
│ │ CACHE │◀─ READS ───│ ORDERS │░
│ └─────────┘░ ├───────────────┤░
│ ░░░░░░░░░░░ │ BILLING │────┐
│ └───────────────┘░ │
│ ░░░░░░░░░░░░░░░░░ │
│ │
└─────────────────────── RETRY ────────────────────────┘
Example 2: bus, hollow heads, inline label, free text
import sys; sys.path.insert(0, "/tmp/textdiagram")
from textdiagram import Diagram as D
d = D()
t = d.header(["Event Bus", "Design"], left=["Acme Inc", "ADR 12", "Nov 2026"],
right=["*~~~~~~~*", "Draft", "*~~~~~~~*"])
y = t.bottom + 4
pub = d.box(0, y, ["Publisher"])
s1 = d.box(36, y - 2, ["Billing"])
s2 = d.box(36, y + 4, ["Audit"])
s3 = d.box(36, y + 10, ["Search"])
d.fan_out(pub, [s1, s2, s3], trunk=28, label="Events", head="hollow") # bus, hollow heads
arc = d.box(D.x_centered_under(pub, ["Archive"]), D.y_below(pub, lines=2), ["Archive"])
d.arrow_v(pub, arc, "Nightly\nbackup", inline=True) # label cut into the line
d.annotate(46, y + 16, ["At-least-once", "delivery"]) # free text, no box
print(d.render())
Output:
┌────────────┐ ╔═════════════╗ ┌─────────────┐
│ ACME INC │ ║ EVENT BUS ║ │ *~~~~~~~* │
│ ADR 12 │ ║ DESIGN ║ │ DRAFT │
│ NOV 2026 │ ║ · ║ │ *~~~~~~~* │
└────────────┘ ╚═════════════╝ └─────────────┘
┌───────────┐
┌──────▷│ BILLING │░
┌─────────────┐ │ └───────────┘░
│ PUBLISHER │── EVENTS ───┤ ░░░░░░░░░░░░░
└──────┬──────┘░ │
░░░░░░│░░░░░░░░ │
│ ┌─────────┐
NIGHTLY ├──────▷│ AUDIT │░
BACKUP │ └─────────┘░
│ ░░░░░░░░░░░
│ │
▼ │
┌───────────┐ │ ┌──────────┐
│ ARCHIVE │░ └──────▷│ SEARCH │░
└───────────┘░ └──────────┘░
░░░░░░░░░░░░░ ░░░░░░░░░░░░
AT-LEAST-ONCE
DELIVERY
API reference
D(max_width=80)— create a diagram;max_widthis the column limit.d.box(x, y, lines, role="component"|"frame"|"title", title=None, w=None, align="left")→Box(.x .y .w .h .right .bottom .cx .rows;right/bottominclude the shadow).linesis a list of lines, or a list of sections (lists of lines) to split the box.box.rowsholds the arrow row of each section.align="center"centers the text.d.header(title, left=None, right=None, y=0)→ titleBox. Each argument is a list of lines. The boxes get their finalxat render time. One header per diagram.d.arrow_h(a, b, label="", row=None, head="filled")—aandbside by side; works in both directions.rowpicks a section row (a.rows[i]).headis"filled"or"hollow".d.arrow_v(a, b, label="", head="filled", inline=False)—bbelowa, centered under it. A label can have more than one line ("\n"). Withinline=True, leave room withDiagram.y_below(a, lines=N).d.route(a, a_side, b, b_side, via=(), label="", label_seg=None, a_row=None, b_row=None, head="filled", inline=False)— sides are"left" "right" "top" "bottom". The line leavesa_sideofaand entersb_sideofb. It haslen(via) + 2segments, which alternate across and up/down, starting with the direction that leavesa_side. Eachviavalue is the lane of one middle segment: an x for an up/down segment, a y for an across segment.via=[]is one bend, one value is two bends (S or U shape), two values are three bends (a loop around).a_row/b_rowpick a section row.label_segpicks the segment (from 0) that carries the label.d.fan_out(a, targets, trunk, a_side="right", b_side="left", label="", head="filled", a_row=None, inline=False)— a bus.trunkis the lane of the shared line: an x for left/right sides, a y for top/bottom.d.arrow_elbow(a, b, label="", mode="vh"|"hv", head="filled")— one bend, a short form ofroute.vh: leave the bottom ofa, turn into the side ofb.hv: leave the side ofa, turn down into the top ofb. The direction follows the position ofb.d.annotate(x, y, lines, align="left")→Box(role"text") — free text, upper-cased.linesis a str ("\n"starts a new line) or a list.d.text(x, y, s)— raw text (not upper-cased).d.render()— returns the diagram; places the header; checks width and wide characters.- The engine raises
DiagramErroron overlaps, small gaps, wrong lane values, or lines over max width.
If no shell is available
Draw by hand with the same rules. Then count the columns on each line and check that: the right shadow is one column right of the box; the bottom shadow row starts one column right of the box's left edge and ends in the shadow column; all box edges line up.
Engine source: textdiagram.py
"""textdiagram: draw aligned Unicode box diagrams on a character grid.
Style:
All text is upper case, except the units in KEEP.
COMPONENT box: light lines + light shadow (░) one column right, one row down.
TITLE box: double lines, no shadow, centred over the diagram (placed at render).
FRAME box: light lines, no shadow (note, callout).
Header: title box with an optional meta box (left) and stamp box (right);
padding lines of the title box hold a centred dot.
Sections: one box split by light dividers, one shadow for the whole box.
Horizontal arrow: label inside the line, both ends touch a box: ── LABEL ──▶
Vertical arrow: label right of the line, one row below the shadow.
Route: arrow with any number of bends, set by lane coordinates (via).
Head: filled (▶) or hollow (▷). fan_out: one line that splits into several arrows.
Label on an up/down line: beside the line, or cut into it (inline=True).
annotate: free text with no box.
"""
import re
import unicodedata
SHADOW = "░"
MIN_DASH = 2 # dashes on each side of an arrow label
HEADER_GAP = 2 # columns between the header boxes
# Units whose case changes the meaning (MB = byte, Mb = bit, ms = milli, MS = mega).
# A word is kept only if it is written exactly like one of these.
KEEP = {
"Hz", "kHz", "MHz", "GHz",
"kB", "MB", "GB", "TB", "KiB", "MiB", "GiB", "TiB",
"kb", "Mb", "Gb", "Tb", "kbps", "Mbps", "Gbps",
"ms", "µs", "ns",
}
# Box-drawing characters as sets of arms: where two arrow lines meet, the arms
# are joined into one junction character (┼, ├, ...).
ARMS = {"─": "LR", "│": "UD", "┌": "RD", "┐": "LD", "└": "RU", "┘": "LU",
"├": "UDR", "┤": "UDL", "┬": "LRD", "┴": "LRU", "┼": "UDLR"}
BY_ARMS = {frozenset(v): k for k, v in ARMS.items()}
# Route directions: R = right, L = left, D = down, U = up.
STEP = {"R": (1, 0), "L": (-1, 0), "D": (0, 1), "U": (0, -1)}
CORNER = {("R", "D"): "┐", ("R", "U"): "┘", ("L", "D"): "┌", ("L", "U"): "└",
("D", "R"): "└", ("D", "L"): "┘", ("U", "R"): "┌", ("U", "L"): "┐"}
HEAD = {"R": "▶", "L": "◀", "D": "▼", "U": "▲"}
HOLLOW = {"R": "▷", "L": "◁", "D": "▽", "U": "△"} # second kind of arrow
LEAVE = {"right": "R", "left": "L", "bottom": "D", "top": "U"} # side of the first box
ENTER = {"left": "R", "right": "L", "top": "D", "bottom": "U"} # side of the last box
def cap(s):
"""Upper-case all text, except the words in KEEP: 'load 5 ms' -> 'LOAD 5 ms'."""
def fix(m):
w = m.group()
return w if w in KEEP else "".join(c.upper() if c.isascii() else c for c in w)
return re.sub(r"[A-Za-zµ]+", fix, s)
class DiagramError(Exception):
pass
class Box:
def __init__(self, x, y, w, h, role, rows=None):
self.x, self.y, self.w, self.h, self.role = x, y, w, h, role
self.rows = rows or [y + h // 2] # arrow row of each section
self.deferred = False # True: x is set at render time
@property
def right(self): # last column used, shadow included
return self.x + self.w - 1 + (1 if self.role == "component" else 0)
@property
def bottom(self): # last row used, shadow included
return self.y + self.h - 1 + (1 if self.role == "component" else 0)
@property
def cx(self):
return self.x + self.w // 2
class Diagram:
def __init__(self, max_width=80):
self.max_width = max_width
self.cells = {} # (x, y) -> (char, kind)
self._deferred = [] # header boxes: (box, sections, place, align)
# ---- low level -------------------------------------------------------
def _put(self, x, y, ch, kind, allow=()):
if x < 0 or y < 0:
raise DiagramError(f"negative position ({x},{y})")
old = self.cells.get((x, y))
if old and old[1] == "label" and old[0] != " " and kind == "arrow" and ch == "─":
return # the label cut this line
if old and old[0] != ch:
if old[1] == kind == "arrow" and old[0] in ARMS and ch in ARMS:
ch = BY_ARMS[frozenset(ARMS[old[0]]) | frozenset(ARMS[ch])]
elif old[1] not in allow:
raise DiagramError(
f"overlap at col {x}, row {y}: '{old[0]}' ({old[1]}) vs '{ch}' ({kind})"
)
self.cells[(x, y)] = (ch, kind)
def text(self, x, y, s, kind="text"):
for i, ch in enumerate(s):
if ch != " ":
self._put(x + i, y, ch, kind)
else:
self.cells.setdefault((x + i, y), (" ", kind))
@staticmethod
def _check_placed(*boxes):
for b in boxes:
if b.deferred:
raise DiagramError("header boxes are placed at render time: no arrows to or from them")
# ---- boxes -----------------------------------------------------------
@staticmethod
def _sections(lines):
"""Normalise lines to a list of sections, each a list of upper-cased lines."""
if isinstance(lines, str):
lines = [lines]
secs = lines if lines and isinstance(lines[0], list) else [lines]
return [[cap(l) for l in sec] for sec in secs]
@staticmethod
def size(lines, title=None, min_w=0):
inner = max([len(l) for l in lines] + [len(title) + 3 if title else 0])
return max(inner + 6, min_w), len(lines) + 2 # 2 spaces pad + 2 border
@staticmethod
def _size(lines, title=None, w=None):
"""Width and height of a box for lines (flat, list of sections, or str)."""
secs = Diagram._sections(lines)
flat = [l for sec in secs for l in sec]
bw, _ = Diagram.size(flat, cap(title) if title else None, w or 0)
return bw, len(flat) + len(secs) - 1 + 2
def box(self, x, y, lines, role="component", title=None, w=None, align="left"):
"""Draw a box. lines: list of text lines, or a list of sections (lists of
lines) to split the box with dividers. role: 'component' | 'frame' | 'title'."""
if role not in ("component", "frame", "title"):
raise DiagramError("role must be 'component', 'frame' or 'title'")
secs = self._sections(lines)
if role == "title" and len(secs) > 1:
raise DiagramError("title boxes have no sections")
bw, bh = self._size(lines, title, w)
rows, r = [], y + 1
for sec in secs:
rows.append(r + (len(sec) - 1) // 2)
r += len(sec) + 1
box = Box(x, y, bw, bh, role, rows)
if role == "title":
box.deferred = True
self._deferred.append((box, secs, "center", "center"))
else:
self._draw_box(box, secs, cap(title) if title else None, align)
return box
def _draw_box(self, box, secs, title, align):
tl, tr, bl, br, hz, vt = "┌┐└┘─│" if box.role != "title" else "╔╗╚╝═║"
x, y, bw, bh = box.x, box.y, box.w, box.h
top = tl + hz * (bw - 2) + tr
if title:
top = tl + hz + " " + title + " " + hz * (bw - 5 - len(title)) + tr
self.text(x, y, top, "border")
r = y + 1
for i, sec in enumerate(secs):
if i:
self.text(x, r, "├" + "─" * (bw - 2) + "┤", "border")
r += 1
for line in sec:
body = line.center(bw - 6) if align == "center" else line.ljust(bw - 6)
self.text(x, r, vt + " " + body + " " + vt, "border")
r += 1
self.text(x, y + bh - 1, bl + hz * (bw - 2) + br, "border")
if box.role == "component":
for rr in range(y + 1, y + bh):
self._put(x + bw, rr, SHADOW, "shadow")
for c in range(x + 1, x + bw + 1):
self._put(c, y + bh, SHADOW, "shadow")
def header(self, title, left=None, right=None, y=0):
"""Title box centred over the diagram, with an optional meta box (left,
left-aligned) and stamp box (right, centred). All get the same height.
Returns the title box; the side boxes sit in the same rows."""
def pad(lines, n, centre, fill=""):
extra = n - len(lines)
top = extra // 2 if centre else 0
return [fill] * top + list(lines) + [fill] * (extra - top)
n = max(len(title), len(left or []), len(right or []))
t = self.box(0, y, pad(title, n, True, "·"), role="title") # dot: padding looks planned
for lines, place, align, centre in ((left, "left", "left", False),
(right, "right", "center", True)):
if lines:
secs = self._sections(pad(lines, n, centre))
bw, bh = self._size(pad(lines, n, centre))
b = Box(0, y, bw, bh, "frame")
b.deferred = True
self._deferred.append((b, secs, place, align))
return t
def _place_deferred(self):
if not self._deferred:
return
places = [p for _, _, p, _ in self._deferred]
if len(set(places)) != len(places):
raise DiagramError("one header (title) per diagram")
items = {p: (b, secs, al) for b, secs, p, al in self._deferred}
t = items["center"][0]
left = items["left"][0] if "left" in items else None
right = items["right"][0] if "right" in items else None
w0 = max([x for x, _ in self.cells] + [-1]) + 1
lw = left.w + HEADER_GAP if left else 0
rw = right.w + HEADER_GAP if right else 0
total = max(w0, lw + t.w + rw)
t.x = min(max((total - t.w) // 2, lw), total - rw - t.w)
if left:
left.x = 0
if right:
right.x = total - right.w
for b, secs, _, al in self._deferred:
self._draw_box(b, secs, None, al)
self._deferred = []
# ---- layout helpers --------------------------------------------------
@staticmethod
def _need(label):
return (len(label) + 2 + 2 * MIN_DASH + 1) if label else 4
@staticmethod
def x_right_of(a, label=""):
"""Smallest x for a box to the right of a, with room for the arrow label."""
return a.right + Diagram._need(label)
@staticmethod
def x_left_of(a, lines, label="", title=None, w=None):
"""x for a new component box left of a, with room for the arrow label."""
bw, _ = Diagram._size(lines, title, w)
return a.x - bw - Diagram._need(label)
@staticmethod
def y_below(a, lines=0):
"""y for a box below a. lines: number of label lines to cut into the arrow
between them (arrow_v with inline=True)."""
if lines: # line, blank, text lines, blank, line, head
return a.bottom + lines + (5 if a.role == "component" else 6)
return a.bottom + (4 if a.role == "component" else 3)
@staticmethod
def x_centered_under(a, lines, title=None, w=None):
bw, _ = Diagram._size(lines, title, w)
return a.cx - bw // 2
# ---- arrows ----------------------------------------------------------
@staticmethod
def _head(head, d):
if head == "filled":
return HEAD[d]
if head == "hollow":
return HOLLOW[d]
raise DiagramError("head must be 'filled' or 'hollow'")
@staticmethod
def _lines(label):
"""Label as upper-case lines ('\\n' starts a new line)."""
return cap(label).split("\n") if label else []
@staticmethod
def _inline_v(x, lo, hi, lines):
"""A label cut into an up/down line at column x, in rows lo..hi: one blank
row, the text lines centred on x, one blank row. Returns (blank rows, text
cells), or None if there is no room."""
n, zone = len(lines), hi - lo + 1
if zone < n + 2:
return None
top = lo + (zone - n - 2) // 2 + 1
cells = {}
for i, line in enumerate(lines):
x0 = x - len(line) // 2
for j, ch in enumerate(line):
if ch != " ":
cells[(x0 + j, top + i)] = ch
return list(range(top - 1, top + n + 1)), cells
def arrow_h(self, a, b, label="", row=None, head="filled"):
"""Arrow from box a (left) to box b (right): ── label ──▶"""
self._check_placed(a, b)
reverse = b.x < a.x
left, right = (b, a) if reverse else (a, b)
y = row if row is not None else max(left.rows[0], right.rows[0])
for bx in (left, right):
if not (bx.y < y < bx.y + bx.h - 1):
raise DiagramError(f"arrow row {y} is not inside both boxes")
x0, x1 = left.x + left.w, right.x - 1 # both ends touch a box
n = x1 - x0 + 1
body = ["─"] * n
if label:
seg = " " + cap(label) + " "
if n < len(seg) + 2 * MIN_DASH + 1:
raise DiagramError(
f"gap too small for label '{label}': use Diagram.x_right_of()"
)
start = (n - len(seg)) // 2
body[start:start + len(seg)] = list(seg)
if reverse:
body[0] = self._head(head, "L")
else:
body[-1] = self._head(head, "R")
for i, ch in enumerate(body):
if ch != " ":
self._put(x0 + i, y, ch, "arrow", allow=("shadow",))
def arrow_v(self, a, b, label="", head="filled", inline=False):
"""Arrow from box a (top) down to box b (bottom). The label goes right of
the line, or cut into the line with inline=True (then leave room with
Diagram.y_below(a, lines=N))."""
self._check_placed(a, b)
x = a.cx
if not (b.x < x < b.x + b.w - 1):
raise DiagramError("box b is not under the center of box a: use x_centered_under()")
y0, y1 = a.y + a.h - 1, b.y - 1
first, last = a.bottom + 1, y1 - 1 # rows free for the label
if first > last:
raise DiagramError("vertical gap too small: use Diagram.y_below()")
lines = self._lines(label)
blanks, cells = [], {}
if lines and inline:
res = self._inline_v(x, first + (0 if a.role == "component" else 1), last - 1, lines)
if res is None:
raise DiagramError("vertical gap too small for label: use Diagram.y_below(a, lines=N)")
blanks, cells = res
elif lines:
row = (first + last - (len(lines) - 1)) // 2
if a.role == "component": # keep the label off the row under the shadow
row = max(row, first + 1)
if row + len(lines) - 1 > last:
raise DiagramError("vertical gap too small for label: use Diagram.y_below()")
cells = {(x + 2 + j, row + i): ch for i, line in enumerate(lines)
for j, ch in enumerate(line) if ch != " "}
self._put(x, y0, "┬", "arrow", allow=("border",))
for r in range(y0 + 1, y1):
if r not in blanks:
self._put(x, r, "│", "arrow", allow=("shadow",))
self._put(x, y1, self._head(head, "D"), "arrow")
for (cx, cy), ch in cells.items():
self._put(cx, cy, ch, "label")
@staticmethod
def _anchor(box, side, row, leaving):
"""Cell where a route leaves (leaving=True) or enters a box on the given side."""
if side not in LEAVE:
raise DiagramError("side must be 'left', 'right', 'top' or 'bottom'")
if row is not None and not (box.y < row < box.y + box.h - 1):
raise DiagramError(f"row {row} is not inside the box")
y = row if row is not None else box.rows[0]
if side == "right":
return (box.x + box.w, y)
if side == "left":
return (box.x - 1, y)
if side == "top":
return (box.cx, box.y if leaving else box.y - 1)
return (box.cx, box.y + box.h - 1 if leaving else box.y + box.h)
def route(self, a, a_side, b, b_side, via=(), label="", label_seg=None,
a_row=None, b_row=None, head="filled", inline=False):
"""Arrow from a side of box a to a side of box b, with any number of bends.
Segments alternate across and up/down, starting with the direction that
leaves a_side. via holds one lane coordinate for each middle segment:
an x for an up/down segment, a y for an across segment. So len(via) + 2
segments are drawn: via=[] is one bend, via=[x] two bends (S or U shape),
via=[x, y] three bends (a loop around). a_row / b_row pick the row of a
section. label_seg picks the segment (from 0) that carries the label.
A label goes inside an across segment, or beside an up/down segment; with
inline=True it is cut into an up/down segment (use '\\n' for more lines)."""
self._check_placed(a, b)
start = self._anchor(a, a_side, a_row, True)
end = self._anchor(b, b_side, b_row, False)
s = len(via) + 2
horiz = [(a_side in ("left", "right")) == (j % 2 == 0) for j in range(s)]
if horiz[-1] != (b_side in ("left", "right")):
raise DiagramError(
f"{s} segments cannot go from {a_side} of a to {b_side} of b: "
"add or remove one via value"
)
coord = [start[1] if horiz[0] else start[0]] + list(via) + \
[end[1] if horiz[-1] else end[0]]
pts = [start]
for j in range(s - 1):
pts.append((coord[j + 1], coord[j]) if horiz[j] else (coord[j], coord[j + 1]))
pts.append(end)
dirs = []
for p, q in zip(pts, pts[1:]):
dx, dy = q[0] - p[0], q[1] - p[1]
if (dx != 0) == (dy != 0):
raise DiagramError("a route segment has zero length: move a via value")
dirs.append(("R" if dx > 0 else "L") if dx else ("D" if dy > 0 else "U"))
if dirs[0] != LEAVE[a_side]:
raise DiagramError(f"route leaves the {a_side} of a backwards: move a via value")
if dirs[-1] != ENTER[b_side]:
raise DiagramError(f"route enters the {b_side} of b backwards: move a via value")
# walk the cells of the path: [x, y, direction in, direction out]
path = [[start[0], start[1], None, None]]
x, y = start
for k, d in enumerate(dirs):
while (x, y) != pts[k + 1]:
x, y = x + STEP[d][0], y + STEP[d][1]
path.append([x, y, d, None])
for i in range(len(path) - 1):
path[i][3] = path[i + 1][2]
chars = {}
for i, (x, y, din, dout) in enumerate(path):
if i == len(path) - 1:
ch = self._head(head, din)
elif din is None or din == dout:
ch = "─" if dout in "RL" else "│"
else:
ch = CORNER[(din, dout)]
chars[(x, y)] = ch
if a_side in ("top", "bottom"):
chars[start] = "┴" if a_side == "top" else "┬"
in_line, beside = set(), {}
if label:
in_line, beside = self._route_label(
chars, pts, dirs, self._lines(label), label_seg, a, a_side, inline)
for i, (x, y, _, _) in enumerate(path):
ch = chars[(x, y)]
old = self.cells.get((x, y))
if ch == " ": # gap cut into a line by a label
if old and old[1] == "arrow" and old[0] in "─│":
del self.cells[(x, y)]
continue
if (x, y) in in_line and old and old[1] == "arrow" and old[0] == "─":
del self.cells[(x, y)]
allow = ("shadow", "border") if i == 0 else ("shadow",)
self._put(x, y, ch, "label" if (x, y) in in_line else "arrow", allow=allow)
for (x, y), ch in beside.items():
self._put(x, y, ch, "label")
def _route_label(self, chars, pts, dirs, lines, label_seg, a, a_side, inline):
"""Choose a segment for the label. A label on an across segment replaces
cells of the line (changes chars, returns their positions); a label on an
up/down segment goes beside the line, or is cut into it (returned as a dict
of text cells; the line cells that it cuts are set to a space in chars)."""
s, n = len(dirs), len(lines)
label = lines[0] if n == 1 else ""
seg = " " + label + " "
options = [] # (kind, k, lo, hi)
for k, d in enumerate(dirs):
p, q = pts[k], pts[k + 1]
if d in "RL":
if n != 1 or inline:
continue
lo, hi = (p[0] + (k > 0), q[0] - (k < s - 1)) if d == "R" else \
(q[0] + (k < s - 1), p[0] - (k > 0))
need = len(seg) + 2 * MIN_DASH + (1 if k == s - 1 else 0)
if hi - lo + 1 >= need:
options.append(("h", k, lo, hi))
else:
lo, hi = (p[1] + 1, q[1] - 1) if d == "D" else (q[1] + 1, p[1] - 1)
shadowed = k == 0 and a_side == "bottom" and a.role == "component"
if inline: # keep one line cell next to the corner, head or shadow
lo, hi = lo + 1, hi - 1
elif shadowed:
lo += 2 # beside the line: not right under the shadow
if hi - lo + 1 >= (n + 2 if inline else n):
options.append(("v", k, lo, hi))
if label_seg is not None:
options = [o for o in options if o[1] == label_seg]
pool = [o for o in options if o[0] == "h"] or options
if not pool:
raise DiagramError(f"no room for the label: move the boxes or the via lanes")
kind, k, lo, hi = max(pool, key=lambda o: o[3] - o[2])
if kind == "h":
y = pts[k][1]
extra = (hi - lo + 1) - len(seg)
head_at_lo = k == s - 1 and dirs[k] == "L"
off = extra - extra // 2 if head_at_lo else extra // 2
in_line = set()
for i, ch in enumerate(seg):
chars[(lo + off + i, y)] = ch
if ch != " ":
in_line.add((lo + off + i, y))
return in_line, {}
x = pts[k][0]
if inline:
blanks, cells = self._inline_v(x, lo, hi, lines)
for r in blanks:
chars[(x, r)] = " "
return set(), cells
row = max((lo + hi - (n - 1)) // 2, lo)
return set(), {(x + 2 + j, row + i): ch for i, line in enumerate(lines)
for j, ch in enumerate(line) if ch != " "}
def arrow_elbow(self, a, b, label="", mode="vh", head="filled"):
"""Arrow with one bend (a route with no via lane).
mode 'vh': leave the bottom of a, go down, turn into the side of b.
mode 'hv': leave the side of a, go across, turn down into the top of b.
The direction (left or right) follows the position of b."""
if mode == "vh":
self.route(a, "bottom", b, "left" if b.x > a.cx else "right",
label=label, head=head)
elif mode == "hv":
self.route(a, "right" if b.cx > a.right else "left", b, "top",
label=label, head=head)
else:
raise DiagramError("mode must be 'vh' or 'hv'")
def fan_out(self, a, targets, trunk, a_side="right", b_side="left", label="",
head="filled", a_row=None, inline=False):
"""One line from a that splits at lane `trunk` into one arrow per target
(a bus). trunk is an x when a_side is left/right, a y when top/bottom. The
label goes on the shared line."""
for i, b in enumerate(targets):
last = i == len(targets) - 1 # draw the label last: it cuts the line
self.route(a, a_side, b, b_side, via=[trunk], a_row=a_row, head=head,
label=label if last else "", label_seg=0, inline=inline)
def annotate(self, x, y, lines, align="left"):
"""Free text with no box (a note beside the diagram). Returns a Box (role
'text') for layout. lines: a str ('\\n' starts a new line) or a list."""
lines = self._lines(lines) if isinstance(lines, str) else [cap(l) for l in lines]
w = max(len(l) for l in lines)
for i, line in enumerate(lines):
self.text(x, y + i, line.center(w) if align == "center" else line, "label")
return Box(x, y, w, len(lines), "text")
# ---- output ----------------------------------------------------------
def render(self):
self._place_deferred()
if not self.cells:
return ""
W = max(x for x, _ in self.cells) + 1
H = max(y for _, y in self.cells) + 1
grid = [[" "] * W for _ in range(H)]
for (x, y), (ch, _) in self.cells.items():
grid[y][x] = ch
out = "\n".join("".join(r).rstrip() for r in grid)
self.check(out)
return out
def check(self, out):
for n, line in enumerate(out.split("\n"), 1):
if len(line) > self.max_width:
raise DiagramError(f"line {n} is {len(line)} cols (max {self.max_width})")
for ch in line:
if unicodedata.east_asian_width(ch) in ("W", "F"):
raise DiagramError(f"wide character '{ch}' on line {n}")