API

Parse and lay out diagrams, set limits, handle errors, and read the scene.

View Markdown

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 moduleWhat it does
limuReads a diagram and lays it out. It holds the parsing options, the diagram types and the error type.
limu::layoutHolds the options that change where things go.
limu::rolesNames the role of every part of every diagram. See Theming.
limu::sceneThe limu-scene crate. It describes a laid-out diagram as a list of items, and holds the drawing every backend shares.
limu::scene::textMeasures text and lays out labels.
limu::scene::styleHolds themes and overrides. See Theming.
limu::scene::svgRenders a scene as SVG. See SVG.
limu-tiny-skiaDraws a scene into a bitmap. See tiny-skia.
limu-coregraphicsDraws a scene with Core Graphics, on Apple’s platforms. See Core Graphics.
limu-gpuiDraws a scene in a GPUI window. See GPUI.
limu-asciiDraws 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.

PackageWhat it does
limuReads a diagram and lays it out.
diagramHolds the parsing options, the diagram types and the error type.
layoutHolds the options that change where things go.
sceneDescribes a laid-out diagram as a list of items.
textMeasures text and lays out labels.
styleHolds themes and overrides. See Theming.
svgRenders a scene as SVG. See SVG.
limumygoDraws 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

NameWhat 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.
NameWhat 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.

use limu::{Map, Value};let flowchart = Map::from_iter([("curve", Value::from("linear"))]);let d = limu::parse(    src,    &limu::ParseOptions {        config: Map::from_iter([("flowchart", Value::from(flowchart))]),        ..Default::default()    },)?;
d, err := limu.Parse(src, diagram.Options{	Config: diagram.Config{"flowchart": diagram.Config{"curve": "linear"}},})

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

LimitDefaultOption
Length of the text50,000 UTF-16 code units, Mermaid’s maxTextSizelimit Limit
Edges in a flowchart or agent flow5,000max_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.

FieldWhat it holds
code CodeThe kind of error.
message MessageA description of the problem, which may quote the diagram.
diagram TypeThe diagram’s type, if known.
mermaid_type MermaidTypeThe type as Mermaid names it, if known.
line, column Line, ColumnThe 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 SnippetThe line with the error and a caret under the position, when there is one.
CodeMeaning
ErrorCode::UnsupportedDiagram diagram.UnsupportedDiagramThe text isn’t a type limu supports.
ErrorCode::Syntax diagram.SyntaxThe text doesn’t parse.
ErrorCode::Semantic diagram.SemanticThe text parses but asks for something impossible, such as a shape that doesn’t exist.
ErrorCode::Limit diagram.LimitThe 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.

FieldDefaultWhat it does
measurer&ArialMeasures text. See Measuring text.
font_size16Sets the size of text that has no size of its own.
iconsNoneReports whether you can draw an icon such as fa:fa-car. Labels leave room only for icons you can draw.
max_widthinfinitySets the width you have. Diagrams that can get narrower will.
keep_directionfalseStops a diagram that runs across from switching to run down to fit max_width.
direction_breakpoint640Sets the max_width below which a diagram may switch direction.
links, imagestrueKeep the links and images a diagram asks for. Set them to false to drop them.
link_schemes, image_schemessee SVGSet the URL schemes that links and images may use besides relative URLs.
paddingNone, which is 8Sets the space around the diagram.
snapNoneRounds positions to a Grid, for backends that draw on whole pixels or on a terminal’s cells.
routingRouting::AutoSets how edges run in ranked layouts. Auto follows the text, and Routing::Orthogonal and Routing::Straight override it.
monospaceMonospace::NONESets 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.
nowNone, the time of the layoutSets the current time for gantt charts, which marks today and starts tasks that have no start date.
time_zone&UtcSets 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.
FieldDefaultWhat it does
Measurertext.ArialMeasures text. See Measuring text.
FontSize16Sets the size of text that has no size of its own.
IconsnoneReports whether you can draw an icon such as fa:fa-car. Labels leave room only for icons you can draw.
MaxWidthno limitSets the width you have. Diagrams that can get narrower will.
KeepDirectionfalseStops a diagram that runs across from switching to run down to fit MaxWidth.
DirectionBreakpoint640Sets the MaxWidth below which a diagram may switch direction.
NoLinks, NoImagesfalseDrop the links and images a diagram asks for.
LinkSchemes, ImageSchemessee SVGSet the URL schemes that links and images may use besides relative URLs.
Padding8Sets the space around the diagram. It’s a pointer so you can set 0 with new(0.0).
SnapnoneRounds positions to multiples of this value, for backends that draw on whole pixels.
Routinglayout.AutoSets how edges run in ranked layouts. Auto follows the text, and layout.Orthogonal and layout.Straight override it.
MonospacenoneSets 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.
Nowtime.Now()Sets the current time for gantt charts, which marks today and starts tasks that have no start date.
Locationtime.LocalSets 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.

FieldWhat it holds
kindKind::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.
roleWhich part of which diagram the item is, such as flowchart.node. Styles are assigned by role.
shapeThe name of the item’s outline, such as rect or diam.
idThe id the diagram gave the item.
class, tagsThe classes the author assigned, and extra facts the diagram records, such as a gantt task being done.
boundsWhere the item is. label_bounds() returns where its label is drawn.
partsThe item’s outline as paths and boxes, each with how it’s painted.
labelThe measured label, with where and how to draw it.
pictureAn image or icon the item shows.
style, authorThe diagram’s own style for the item, in theme colors, and what the author set with classDef and style.
link, tooltipWhere the item links to, and its tooltip.
FieldWhat it holds
Kindscene.Node, Group, Edge, Text for a standalone label, or Mark for a shape without a label.
RoleWhich part of which diagram the item is, such as flowchart.node. Styles are assigned by role.
ShapeThe name of the item’s outline, such as rect or diam.
IDThe id the diagram gave the item.
Class, TagsThe classes the author assigned, and extra facts the diagram records, such as a gantt task being done.
BoxWhere the item is. LabelBox() returns where its label is drawn.
PartsThe item’s outline as paths and boxes, each with how it’s painted.
Route, EndsFor an edge, the corners of its line and the markers at its ends.
Label, At, Align, RotateThe measured label, and where and how to draw it.
PictureAn image or icon the item shows.
Style, AuthorThe diagram’s own style for the item, in theme colors, and what the author set with classDef and style.
Link, TooltipWhere 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.

use limu::scene::Kind;for it in &scene.items {    if matches!(it.kind, Kind::Node) {        println!("{} {:?} at {:?}", it.role.as_str(), it.id, it.bounds);    }}
for _, it := range sc.Items {	if it.Kind == scene.Node {		fmt.Printf("%s %q at %v\n", it.Role, it.ID, it.Box)	}}

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.

pub trait Measurer {    fn width(&self, s: &str, size: f64, f: Face) -> f64;}
type Measurer interface {	Width(s string, size float64, f text.Face) float64}

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.