This is a small library for generating railroad diagrams (like what JSON.org uses) using SVG or Unicode/ASCII text, with both JS and Python ports. Here’s an online dingus for you to play with and get SVG code from!
(This is the README for the Python port; see the main README for other ports, and for more non-Python-specific information.)
Requires Python 3.12+.
pip install railroad-diagrams
Constructing a diagram is a set of nested calls. To create an SVG diagram:
import sys
from railroad import Diagram, Choice
d = Diagram("foo", Choice(0, "bar", "baz"))
# Stream directly to a file/writer:
d.writeSvg(sys.stdout.write)
# Or get a string directly:
svg = d.toSvg() # or str(d)
To create a text-format diagram:
import sys
from railroad import Diagram, Choice
d = Diagram("foo", Choice(0, "bar", "baz"))
d.writeText(sys.stdout.write)
# Or get a string directly:
text = d.toText()
A railroad diagram must be started as a Diagram (or ComplexDiagram) object,
which takes a list of diagram items,
defined below.
The Diagram() constructor also optionally takes a type keyword argument:
type: JSON.org, the inspiration for these diagram’s styling, technically has two varieties of Diagrams: a "simple" kind it uses for “leaf” types like numbers, and a "complex" kind which is used for container types like arrays. The only difference is the shape of the start/end indicators of the diagram.
Diagrams default to being "simple", but you can choose by passing type="simple" or type="complex", or by using ComplexDiagram(...) directly.
After constructing a Diagram, you can call .format(*paddings) on it, specifying 0-4 padding values (just like CSS) for some additional “breathing space” around the diagram (the paddings default to 20px).
Output methods on Diagram (and .writeText() / .toText() / .toTextDiagram() on any DiagramItem):
.writeSvg(cb) / .toSvg() / str(diagram): produces an SVG fragment appropriate to include directly in HTML. For .writeSvg(cb), pass a callback such as sys.stdout.write or any file object’s .write..writeStandalone(cb, css=None) / .toStandalone(css=None): formats the SVG as a standalone SVG document (including XML namespaces and an embedded <style> element). If css is omitted or None, DEFAULT_STYLE is included; pass your own CSS string to override it, or "" to omit <style> altogether..writeText(cb) / .toText(): renders the diagram (or any sub-component) as pre-formatted Unicode (or ASCII) text. Use TextDiagram.setFormatting(TextDiagram.PARTS_ASCII) to switch to pure ASCII box characters..toTextDiagram() (alias .textDiagram()): returns the underlying TextDiagram object..walk(cb): walks the component tree in pre-order depth-first traversal (the node first, then each child).You can also render diagrams from the command line via railroad-diagrams (or python -m railroad), accepting Python expressions (default), Bikeshed’s indentation DSL (-s dsl), KDL 2.0 (-s kdl), or auto-detected DSL/KDL (-s auto):
railroad-diagrams svg -e 'Diagram("foo", Choice(0, "bar", "baz"))'
railroad-diagrams unicode -s dsl -e 'Choice: 0
T: bar
T: baz'
railroad-diagrams svg -s kdl -e 'choice 0 { t bar; t baz }'
In addition to constructing diagrams programmatically, you can parse either Bikeshed’s indentation DSL or KDL 2.0. See the Input Syntaxes section of the main README for the full grammar, supported commands/nodes, properties, and auto-detection rules.
import railroad
# Auto-detect Bikeshed DSL vs KDL 2.0:
d1 = railroad.parse("""
Stack:
Or: 1
T: --
Seq:
Opt: skip
T: -
N: ident
""")
d2 = railroad.parse("""
stack {
choice 1 {
t "--"
seq {
opt skip { t "-" }
n ident
}
}
}
""")
Available helpers:
parse(source, syntax="auto"): parses "dsl" ("bikeshed"), "kdl", or "auto" (auto-detect via detectSyntax()). Raises ParseError on invalid input.parseDsl(source): parses Bikeshed’s significant-whitespace DSL.parseKdl(source): parses KDL 2.0 (supports PascalCase, kebab-case, and short aliases like t, n, c, s, seq, or, opt, plus, star).detectSyntax(source): returns "dsl" or "kdl".ParseError: ValueError subclass raised on syntax or validation errors (with optional .line).Components are either leaves (containing only text or similar) or containers (containing other components).
The leaves:
Terminal(text, href=None, title=None, cls="") or a bare string - represents literal text.
All arguments past the first are optional:
href makes the text a hyperlink with the given URLtitle adds an SVG <title> element to the element,
giving it “hover text”
and a description for screen-readers and other assistive techcls is additional classes to apply to the element,
beyond the default 'terminal'NonTerminal(text, href=None, title=None, cls="") - represents an instruction or another production.
The optional arguments have the same meaning as for Terminal,
except that the default class is 'non-terminal'.
Comment(text, href=None, title=None, cls="") - a comment.
The optional arguments have the same meaning as for Terminal,
except that the default class is 'comment'.
Skip() - an empty line
Block(width=50, up=15, height=25, down=15, needsSpace=True) - a generic rectangular placeholder block (useful for layout testing or custom components)
Start(type="simple", label=None) and End(type="simple") - the start/end shapes. These are supplied by default, but if you want to supply a label to the diagram, you can create a Start() explicitly (as the first child of the Diagram!). The type argument takes either "simple" (the default) or "complex", a la Diagram() and ComplexDiagram(). All arguments are optional.
The containers:
Sequence(*children) - like simple concatenation in a regex.
Stack(*children) - identical to a Sequence, but the items are stacked vertically rather than horizontally. Best used when a simple Sequence would be too wide; instead, you can break the items up into a Stack of Sequences of an appropriate width.
OptionalSequence(*children) - a Sequence where every item is individually optional, but at least one item must be chosen
Choice(index, *children) - like | in a regex. The index argument specifies which child is the “normal” choice and should go in the middle (starting from 0 for the first child).
MultipleChoice(index, type, *children) - like || or && in a CSS grammar; it’s similar to a Choice, but more than one branch can be taken. The index argument specifies which child is the “normal” choice and should go in the middle, while the type argument must be either "any" (1+ branches can be taken) or "all" (all branches must be taken).
HorizontalChoice(*children) - Identical to Choice, but the items are stacked horizontally rather than vertically. There’s no “straight-line” choice, so it just takes a list of children. Best used when a simple Choice would be too tall; instead, you can break up the items into a HorizontalChoice of Choices of an appropriate height.
Optional(child, skip=False) - like ? in a regex. A shorthand for Choice(1, Skip(), child). If the optional skip parameter is True (or "skip"), it instead puts the Skip() in the straight-line path, for when the “normal” behavior is to omit the item.
OneOrMore(child, repeat=None) - like + in a regex. The repeat argument is optional, and specifies something that must go between the repetitions (usually a Comment(), but sometimes things like ",", etc.)
AlternatingSequence(option1, option2) - similar to a OneOrMore, where you must alternate between the two choices, but allows you to start and end with either element. (OneOrMore requires you to start and end with the “child” node.)
ZeroOrMore(child, repeat=None, skip=False) - like * in a regex. A shorthand for Optional(OneOrMore(child, repeat), skip). Both repeat (same as in OneOrMore()) and skip (same as in Optional()) are optional.
Group(child, label=None) - highlights its child with a dashed outline, and optionally labels it. Passing a string as the label constructs a Comment, or you can build one yourself (to give an href or title).
There are a few options you can tweak, living as UPPERCASE_CONSTANTS at the top of the module (and mirrored on railroad.Options to match the JS API); these can be adjusted via either railroad.OPTION_NAME_HERE = ... or railroad.Options.OPTION_NAME_HERE = ....
Note that if you change the text sizes in the CSS,
you’ll have to adjust the text metrics here as well.
VS - sets the minimum amount of vertical separation between two items, in CSS px. Note that the stroke width isn’t counted when computing the separation; this shouldn’t be relevant unless you have a very small separation or very large stroke width. Defaults to 8. Ignored for text diagrams.AR - the radius of the arcs, in CSS px, used in the branching containers like Choice. This has a relatively large effect on the size of non-trivial diagrams. Both tight and loose values look good, depending on what you’re going for. Defaults to 10. Ignored for text diagrams.DIAGRAM_CLASS - the class set on the root <svg> element of each diagram, for use in the CSS stylesheet. Defaults to "railroad-diagram". Ignored for text diagrams.STROKE_ODD_PIXEL_LENGTH - the default stylesheet uses odd pixel lengths for ‘stroke’. Due to rasterization artifacts, they look best when the item has been translated half a pixel in both directions. If you change the styling to use a stroke with even pixel lengths, you’ll want to set this variable to False. Ignored for text diagrams.INTERNAL_ALIGNMENT - when some branches of a container are narrower than others, this determines how they’re aligned in the extra space. Defaults to "center", but can be set to "left" or "right".CHAR_WIDTH - the approximate width, in CSS px, of characters in normal text (Terminal and NonTerminal). Defaults to 8.5. Ignored for text diagrams.COMMENT_CHAR_WIDTH - the approximate width, in CSS px, of character in Comment text, which by default is smaller than the other textual items. Defaults to 7. Ignored for text diagrams.DEBUG - if True, writes some additional “debug information” into the attributes of elements in the output, to help debug sizing issues. Defaults to False. Ignored for text diagrams.ESCAPE_HTML - if True, causes Diagram.writeText() and Diagram.toText() to replace "&", "<", ">", '"', and "'" with their HTML-entity equivalents, so text diagram output can be placed in HTML files unchanged. Defaults to True.