API
Parse and lay out diagrams, set limits, handle errors, and read the scene.
limu-rs is split into a few crates. limu reads and lays out diagrams, limu-scene holds what a backend needs to draw them, and each backend is a crate of its own. This page explains what each part is for and when you need it. docs.rs documents every name in full.
| Crate or module | What it does |
|---|---|
limu | Reads a diagram and lays it out. It holds the parsing options, the diagram types and the error type. |
limu::layout | Holds the options that change where things go. |
limu::roles | Names the role of every part of every diagram. See Theming. |
limu::scene | The limu-scene crate. It describes a laid-out diagram as a list of items, and holds the drawing every backend shares. |
limu::scene::text | Measures text and lays out labels. |
limu::scene::style | Holds themes and overrides. See Theming. |
limu::scene::svg | Renders a scene as SVG. See SVG. |
limu-tiny-skia | Draws a scene into a bitmap. See tiny-skia. |
limu-coregraphics | Draws a scene with Core Graphics, on Apple’s platforms. See Core Graphics. |
limu-gpui | Draws a scene in a GPUI window. See GPUI. |
limu-ascii | Draws a scene as text in a terminal’s cells. See Terminal. |
limu and limu-scene use only Rust’s standard library, and serde behind their optional serde feature. A backend that needs another crate is a crate of its own, so a program builds only the backends it uses.
limu is split into a few packages, one for each stage of drawing a diagram. This page explains what each one is for and when you need it. pkg.go.dev documents every name in full.
| Package | What it does |
|---|---|
limu | Reads a diagram and lays it out. |
diagram | Holds the parsing options, the diagram types and the error type. |
layout | Holds the options that change where things go. |
scene | Describes a laid-out diagram as a list of items. |
text | Measures text and lays out labels. |
style | Holds themes and overrides. See Theming. |
svg | Renders a scene as SVG. See SVG. |
limumygo | Draws a scene with MyGo’s native UI. It’s a separate module. See MyGo. |
Every package except limumygo uses only Go’s standard library.
Reading and laying out
| Name | What it does |
|---|---|
layout(src, o) | Reads a diagram and lays it out as a scene. |
parse(src, opt) | Reads a diagram into a Diagram to lay out later. |
Diagram::layout(o) | Lays out the diagram. You can call it many times, with different options, from several threads at once. |
Diagram::diagram_type() | Returns the diagram’s type, such as DiagramType::Flowchart. |
Diagram::mermaid_type() | Returns the type as Mermaid names it, such as flowchart-v2 for graph TD. |
Diagram::title() | Returns the title the diagram’s front matter gives it. |
Diagram::config() | Returns the diagram’s configuration, with its own settings over the ones it was parsed with. |
types() | Lists the diagram types limu supports, which are those whose features are on. |
supports(src) | Reports whether limu supports the type a text declares. It doesn’t parse the rest, so the text may still have errors. |
| Name | What it does |
|---|---|
Layout(src, o) | Reads a diagram and lays it out as a scene. |
Parse(src, opt) | Reads a diagram into a Diagram to lay out later. |
Diagram.Layout(o) | Lays out the diagram. You can call it many times, with different options, from several goroutines at once. |
Diagram.Type() | Returns the diagram’s type, such as diagram.Flowchart. |
Diagram.MermaidType() | Returns the type as Mermaid names it, such as flowchart-v2 for graph TD. |
Diagram.Config() | Returns the diagram’s configuration, with its own settings over the ones it was parsed with. |
Types() | Lists the diagram types limu supports. |
Supports(src) | Reports whether limu supports the type a text declares. It doesn’t parse the rest, so the text may still have errors. |
Laying out a text is the same as parsing it with default options and then laying out the diagram. If you lay out the same diagram more than once, for example when its width changes, parse it only once.
Parsing
The parsing options, limu::ParseOptions diagram.Options, set the limits for the text, and configuration that applies wherever the diagram doesn’t set its own.
1use limu::{Map, Value};23let flowchart = Map::from_iter([("curve", Value::from("linear"))]);4let d = limu::parse(5 src,6 &limu::ParseOptions {7 config: Map::from_iter([("flowchart", Value::from(flowchart))]),8 ..Default::default()9 },10)?;1d, err := limu.Parse(src, diagram.Options{2 Config: diagram.Config{"flowchart": diagram.Config{"curve": "linear"}},3})The configuration works like Mermaid’s. A diagram can also set configuration in its front matter or in an %%{init: …}%% directive, and its own settings win key by key. Values follow JSON. In Rust, values are a limu::Value, and objects are a limu::Map, which keeps its keys in the order JavaScript does. In Go, objects are diagram.Config, arrays are []any and numbers are float64.
Limits
| Limit | Default | Option |
|---|---|---|
| Length of the text | 50,000 UTF-16 code units, Mermaid’s maxTextSize | limit Limit |
| Edges in a flowchart or agent flow | 5,000 | max_edges MaxEdges |
Text over a limit gives an error with the code ErrorCode::Limit diagram.Limit. In Rust, None turns it off. In Go, a negative limit does. For untrusted text, keep the defaults or lower them. The edge limit matters because A & B --> C & D multiplies, so a few kilobytes of text can ask for millions of edges. limu can’t stop a layout once it has started, and the limits are what keep its work bounded.
Errors
Parsing and layout return an error, a limu::Error *diagram.Error, with these fields.
| Field | What it holds |
|---|---|
code Code | The kind of error. |
message Message | A description of the problem, which may quote the diagram. |
diagram Type | The diagram’s type, if known. |
mermaid_type MermaidType | The type as Mermaid names it, if known. |
line, column Line, Column | The position of the error, counted from 1, with the column in UTF-16 code units. Both are 0 when the error has no position. |
snippet Snippet | The line with the error and a caret under the position, when there is one. |
| Code | Meaning |
|---|---|
ErrorCode::UnsupportedDiagram diagram.UnsupportedDiagram | The text isn’t a type limu supports. |
ErrorCode::Syntax diagram.Syntax | The text doesn’t parse. |
ErrorCode::Semantic diagram.Semantic | The text parses but asks for something impossible, such as a shape that doesn’t exist. |
ErrorCode::Limit diagram.Limit | The text is over a limit, or layout would give a number that isn’t finite, where Pele would write NaN. |
Layout
The layout options, limu::layout::Options layout.Options, hold everything that affects where things go. Changing these options means laying the diagram out again, while changing the style doesn’t. In Rust, Options::default() gives the defaults. In Go, nil options are the same as the zero value, and every zero field means the default.
| Field | Default | What it does |
|---|---|---|
measurer | &Arial | Measures text. See Measuring text. |
font_size | 16 | Sets the size of text that has no size of its own. |
icons | None | Reports whether you can draw an icon such as fa:fa-car. Labels leave room only for icons you can draw. |
max_width | infinity | Sets the width you have. Diagrams that can get narrower will. |
keep_direction | false | Stops a diagram that runs across from switching to run down to fit max_width. |
direction_breakpoint | 640 | Sets the max_width below which a diagram may switch direction. |
links, images | true | Keep the links and images a diagram asks for. Set them to false to drop them. |
link_schemes, image_schemes | see SVG | Set the URL schemes that links and images may use besides relative URLs. |
padding | None, which is 8 | Sets the space around the diagram. |
snap | None | Rounds positions to a Grid, for backends that draw on whole pixels or on a terminal’s cells. |
routing | Routing::Auto | Sets how edges run in ranked layouts. Auto follows the text, and Routing::Orthogonal and Routing::Straight override it. |
monospace | Monospace::NONE | Sets which parts are set in the monospace face. Monospace::MEMBERS covers the members of class diagrams, ATTRIBUTES the types, names and keys of the attributes of entity relationship diagrams, FILES the entries of tree views, and MESSAGES the messages of sequence diagrams. A part whose author gives it a font keeps it. |
now | None, the time of the layout | Sets the current time for gantt charts, which marks today and starts tasks that have no start date. |
time_zone | &Utc | Sets the time zone gantt charts read and write dates in. Rust’s standard library knows no time zone but UTC. FixedOffset is a fixed number of seconds east of UTC, and a program that needs a real time zone implements TimeZone, for example with jiff. |
| Field | Default | What it does |
|---|---|---|
Measurer | text.Arial | Measures text. See Measuring text. |
FontSize | 16 | Sets the size of text that has no size of its own. |
Icons | none | Reports whether you can draw an icon such as fa:fa-car. Labels leave room only for icons you can draw. |
MaxWidth | no limit | Sets the width you have. Diagrams that can get narrower will. |
KeepDirection | false | Stops a diagram that runs across from switching to run down to fit MaxWidth. |
DirectionBreakpoint | 640 | Sets the MaxWidth below which a diagram may switch direction. |
NoLinks, NoImages | false | Drop the links and images a diagram asks for. |
LinkSchemes, ImageSchemes | see SVG | Set the URL schemes that links and images may use besides relative URLs. |
Padding | 8 | Sets the space around the diagram. It’s a pointer so you can set 0 with new(0.0). |
Snap | none | Rounds positions to multiples of this value, for backends that draw on whole pixels. |
Routing | layout.Auto | Sets how edges run in ranked layouts. Auto follows the text, and layout.Orthogonal and layout.Straight override it. |
Monospace | none | Sets which parts are set in the monospace face. layout.Members covers the members of class diagrams, layout.Attributes the types, names and keys of the attributes of entity relationship diagrams, layout.Files the entries of tree views, and layout.Messages the messages of sequence diagrams. A part whose author gives it a font keeps it. |
Now | time.Now() | Sets the current time for gantt charts, which marks today and starts tasks that have no start date. |
Location | time.Local | Sets the time zone gantt charts read and write dates in. |
The routing applies to flowcharts and to swimlane, agent flow, state, class, entity relationship, requirement and use case diagrams. Other diagrams route their edges as Pele does.
To render the same diagram on every build, set the current time and the time zone. This site does that for its gantt charts.
The scene
A scene, limu::scene::Scene scene.Scene, is a laid-out diagram. It has a size and a list of items in drawing order. Each item records what it is and where it goes, but not how it looks. Its colors are theme tokens that are resolved only when it’s drawn.
| Field | What it holds |
|---|---|
kind | Kind::Node, Group, Edge, Text for a standalone label, or Mark for a shape without a label. An edge’s kind holds its route, the corners of its line, and its ends, the markers at its ends. |
role | Which part of which diagram the item is, such as flowchart.node. Styles are assigned by role. |
shape | The name of the item’s outline, such as rect or diam. |
id | The id the diagram gave the item. |
class, tags | The classes the author assigned, and extra facts the diagram records, such as a gantt task being done. |
bounds | Where the item is. label_bounds() returns where its label is drawn. |
parts | The item’s outline as paths and boxes, each with how it’s painted. |
label | The measured label, with where and how to draw it. |
picture | An image or icon the item shows. |
style, author | The diagram’s own style for the item, in theme colors, and what the author set with classDef and style. |
link, tooltip | Where the item links to, and its tooltip. |
| Field | What it holds |
|---|---|
Kind | scene.Node, Group, Edge, Text for a standalone label, or Mark for a shape without a label. |
Role | Which part of which diagram the item is, such as flowchart.node. Styles are assigned by role. |
Shape | The name of the item’s outline, such as rect or diam. |
ID | The id the diagram gave the item. |
Class, Tags | The classes the author assigned, and extra facts the diagram records, such as a gantt task being done. |
Box | Where the item is. LabelBox() returns where its label is drawn. |
Parts | The item’s outline as paths and boxes, each with how it’s painted. |
Route, Ends | For an edge, the corners of its line and the markers at its ends. |
Label, At, Align, Rotate | The measured label, and where and how to draw it. |
Picture | An image or icon the item shows. |
Style, Author | The diagram’s own style for the item, in theme colors, and what the author set with classDef and style. |
Link, Tooltip | Where the item links to, and its tooltip. |
Because a scene is plain data, a program can read it directly. This loop prints where each node is.
1use limu::scene::Kind;23for it in &scene.items {4 if matches!(it.kind, Kind::Node) {5 println!("{} {:?} at {:?}", it.role.as_str(), it.id, it.bounds);6 }7}1for _, it := range sc.Items {2 if it.Kind == scene.Node {3 fmt.Printf("%s %q at %v\n", it.Role, it.ID, it.Box)4 }5}A backend draws each item’s parts, the markers at an edge’s ends (Marker::outline Marker.Outline) and the label. A backend with its own look can instead draw items from their role, shape, box and route. Paths use only four kinds of step, which are moves, lines, and quadratic and cubic curves. Arcs are converted to cubic curves. For backends that can’t draw curves or dashes, Path::flatten Path.Flatten turns a path into polylines and limu::scene::dash scene.Dash cuts polylines into dashes.
The drawing the Rust backends share is in limu::scene too. A backend implements Canvas, which fills and strokes paths and sets text and pictures, and draw walks the scene and settles each item’s style for it. Scene::item_at finds the item at a point, for a program that answers the pointer.
Measuring text
Layout measures every label, so a diagram must be drawn in the fonts it was measured with. Otherwise the text won’t fit the space layout gave it. A measurer, limu::scene::text::Measurer text.Measurer, returns the width of text in a given face and size.
1pub trait Measurer {2 fn width(&self, s: &str, size: f64, f: Face) -> f64;3}1type Measurer interface {2 Width(s string, size float64, f text.Face) float643}The default, limu::layout::Arial text.Arial, estimates widths from a table of Arial’s character widths without loading any font. It matches Pele’s widths exactly, and SVG drawn with it should use Arial or a font of the same width. If you draw text in other fonts, pass a measurer for those fonts. In Rust, each native backend has one for the fonts it draws in. In Go, limumygo.Fonts is one for MyGo.
A label’s span can also be subscript, superscript or underlined. Layout asks the measurer only about bold, italic and the monospace face. It measures subscript and superscript at the font size divided by 1.2, as Pele does, so a backend should draw them that much smaller and lowered or raised. An underline takes no room.
Chinese, Japanese and Korean
The default measurer treats every Chinese, Japanese and Korean character as one em wide, which is only an estimate. Real fonts may be narrower or wider. When a label is too wide, it wraps between words. Like Pele, it also wraps between any two Chinese or Japanese characters, but never before a closing punctuation mark or after an opening one. Korean wraps only between words. If you draw this kind of text, measure it with the fonts you draw it in.