# sketch

URL: https://tuios.dev/docs/libraries/sketch

> Mermaid diagrams as SVG, PNG and box-drawing text, in pure Go. A port of pele by kepano.

`tuios.dev/sketch` draws Mermaid diagrams in pure Go. It needs no browser, no JavaScript runtime and no cgo. It has three outputs:

- **SVG** from `sketch.Render`, the same SVG that pele writes, byte for byte.
- **A picture** from `sketch/raster`, which draws that SVG into a Go `image.RGBA`.
- **Text** from `sketch/text`, which draws the diagram with box-drawing characters for a terminal.

*[An interactive figure goes here. Open the page to use it.](https://tuios.dev/docs/libraries/sketch)*

*[An interactive figure goes here. Open the page to use it.](https://tuios.dev/docs/libraries/sketch)*

The API reference is on [pkg.go.dev](https://pkg.go.dev/tuios.dev/sketch).

## Install

```bash
go get tuios.dev/sketch
```

The module holds four packages: `tuios.dev/sketch`, `tuios.dev/sketch/raster`, `tuios.dev/sketch/text` and `tuios.dev/sketch/core`. `sketch/core` is the same API with the eight common diagram types (flowchart, sequence, state, class, er, gantt, pie and mindmap), about 2.7 MB smaller in a binary. Its `Detect` still knows every type, so a caller can tell a type it does not draw from text that is no diagram.

### The sketch command

`sketch` draws Mermaid diagrams without the rest of tuios. It needs Go 1.25 or newer:

```bash
go install tuios.dev/sketch/cmd/sketch@latest
```

Each tuios release from v0.11.0 also carries a `sketch` archive for Linux, macOS, Windows and FreeBSD, on x86\_64 and arm64. Download it from the [releases page](https://github.com/Gaurav-Gosain/tuios/releases), or install it with a package manager:

```bash
brew install --cask gaurav-gosain/tap/tuios-sketch   # macOS and Linux
yay -S tuios-sketch-bin                              # Arch Linux, from the AUR
```

```bash
sketch flow.mmd                    # box-drawing text in a terminal
sketch README.md                   # every mermaid block of a Markdown file
sketch flow.mmd -o flow.png        # a picture; .svg writes SVG
echo 'flowchart LR; A-->B' | sketch - -f svg > flow.svg
sketch flow.mmd -f kitty --theme nord
```

FILE takes the same input as [tuios mermaid](https://tuios.dev/docs/libraries/sketch#tuios-mermaid). `sketch -h` lists every flag, and `sketch --themes` lists the themes.

## Quick start

The three programs below draw the same flowchart. Each one is a complete program. The output under each program is what it printed when the docs were built.

### SVG

```go
package main

import (
	"fmt"
	"log"
	"os"

	"tuios.dev/sketch"
)

const src = `flowchart LR
  src[Mermaid source] --> sketch{{sketch}}
  sketch --> svg[(SVG)]
  sketch --> png[(PNG)]
  sketch --> txt[(Text)]
`

func main() {
	svg, err := sketch.Render(src, sketch.RenderOptions{})
	if err != nil {
		log.Fatal(err) // a *sketch.Error, with a code such as "syntax"
	}
	if err := os.WriteFile("flow.svg", []byte(svg.Data), 0o644); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%s (Mermaid calls it %s)\n", svg.Type, svg.MermaidType)
	fmt.Printf("%.0f by %.0f, %d bytes of SVG\n", svg.Width, svg.Height, len(svg.Data))
}

```

```text title="Output"
flowchart (Mermaid calls it flowchart-v2)
440 by 276, 3213 bytes of SVG

```

This is `flow.svg` as the program wrote it. It has no theme, so it shows pele's own colours:

*[An interactive figure goes here. Open the page to use it.](https://tuios.dev/docs/libraries/sketch)*

The SVG takes its colours from `--pele-*` CSS custom properties, with pele's colours as the fallback. A page can set those properties to theme the diagram. Set `RenderOptions.Theme` to write a theme into the SVG.

### PNG

```go
package main

import (
	"fmt"
	"image/png"
	"log"
	"os"

	"tuios.dev/sketch"
	"tuios.dev/sketch/raster"
)

const src = `flowchart LR
  src[Mermaid source] --> sketch{{sketch}}
  sketch --> svg[(SVG)]
  sketch --> png[(PNG)]
  sketch --> txt[(Text)]
`

func main() {
	svg, err := sketch.Render(src, sketch.RenderOptions{})
	if err != nil {
		log.Fatal(err)
	}
	theme, _ := sketch.ThemeNamed("catppuccin-mocha")
	img, err := raster.Draw(svg.Data, raster.Options{
		Scale:      2,     // two pixels for each SVG unit
		Theme:      theme, // nil keeps the colours of the SVG
		Background: true,  // paint the theme's background first
	})
	if err != nil {
		log.Fatal(err) // raster.ErrTooLarge past 40 million pixels
	}
	f, err := os.Create("flow.png")
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()
	if err := png.Encode(f, img); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("flow.png: %d by %d pixels\n", img.Bounds().Dx(), img.Bounds().Dy())
}

```

```text title="Output"
flow.png: 880 by 552 pixels

```

![The same flowchart drawn by sketch/raster in the Catppuccin Mocha theme: light text and coloured boxes on a dark background](https://tuios.dev/libs/sketch/examples/flow.webp)

`raster.Draw` draws only SVG that sketch wrote. It is not a general SVG renderer.

### Text

```go
package main

import (
	"fmt"
	"log"

	"tuios.dev/sketch"
	"tuios.dev/sketch/text"
)

const src = `flowchart LR
  src[Mermaid source] --> sketch{{sketch}}
  sketch --> svg[(SVG)]
  sketch --> png[(PNG)]
  sketch --> txt[(Text)]
`

func main() {
	d, err := sketch.Parse(src, sketch.ParseOptions{})
	if err != nil {
		log.Fatal(err)
	}
	lines, err := text.Draw(d, text.Options{Cols: 80, Color: true})
	if err != nil {
		log.Fatal(err) // text.ErrTooWide, text.ErrTooLarge or text.ErrUnsupported
	}
	for _, line := range lines {
		fmt.Println(line)
	}
}

```

The program prints this, with ANSI colours:

*[An interactive figure goes here. Open the page to use it.](https://tuios.dev/docs/libraries/sketch)*

## Text drawings

`sketch/text` draws every type that sketch draws. The drawers of the types outside `sketch/core` are left out of a program unless it asks for them: call `text.Rare()` once, before the first drawing, as the `sketch` command does. It takes the layout that sketch works out for the SVG, and maps it to cells at a scale where every label fits. The labels stay real text. Charts keep their shape in cells: a pie chart is a disc of half blocks, a radar chart and a Venn diagram are braille dots, and the charts are drawn with [plot](https://tuios.dev/docs/libraries/plot). [Diagram types](https://tuios.dev/docs/libraries/sketch/diagram-types) shows the text drawing of each type.

### Width

`text.Options.Cols` is the most columns the drawing can use. `0` means no limit. When the drawing does not fit, `text.Draw` asks sketch for a narrower layout:

1. A graph loses the columns that hold only gaps and horizontal lines.
2. A flowchart that runs across turns to run down.
3. A timeline, a user journey and some other types change their form. The [Diagram types](https://tuios.dev/docs/libraries/sketch/diagram-types) page tells you which.

If no layout fits, `text.Draw` returns `text.ErrTooWide`. This program draws one flowchart at the width you give it:

```go
package main

import (
	"errors"
	"fmt"
	"log"
	"os"
	"strconv"

	"tuios.dev/sketch"
	"tuios.dev/sketch/text"
)

const src = `flowchart LR
  push[git push] --> ci{CI passes?}
  ci -->|yes| tag[Tag a release]
  ci -->|no| fix[Fix the build]
  tag --> ship[Ship it]
`

func main() {
	cols, _ := strconv.Atoi(os.Args[1]) // go run . 100
	d, err := sketch.Parse(src, sketch.ParseOptions{})
	if err != nil {
		log.Fatal(err)
	}
	lines, err := text.Draw(d, text.Options{Cols: cols})
	if errors.Is(err, text.ErrTooWide) {
		// No layout fits: show the source, as tuios mermaid does
		// for a type with no text drawing.
		fmt.Printf("no drawing fits in %d columns\n%s", cols, src)
		return
	}
	if err != nil {
		log.Fatal(err)
	}
	for _, line := range lines {
		fmt.Println(line)
	}
}

```

> > The layout of the SVG, with nothing changed.
> >
> > *[An interactive figure goes here. Open the page to use it.](https://tuios.dev/docs/libraries/sketch)*
>
> > The empty columns close up.
> >
> > *[An interactive figure goes here. Open the page to use it.](https://tuios.dev/docs/libraries/sketch)*
>
> > The flowchart turns to run down.
> >
> > *[An interactive figure goes here. Open the page to use it.](https://tuios.dev/docs/libraries/sketch)*
>
> > No layout fits, so the program prints the source.
> >
> > *[An interactive figure goes here. Open the page to use it.](https://tuios.dev/docs/libraries/sketch)*

### Errors

| Error                 | Meaning                                                                      | What `tuios mermaid` does                                        |
| --------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------- |
| `text.ErrTooWide`     | No layout fits in `Cols`.                                                    | It draws at full width (`Cols: 0`), and writes a note on stderr. |
| `text.ErrTooLarge`    | The drawing needs more than `text.MaxCells` (4,000,000) cells, at any width. | It prints the source, and writes a note on stderr.               |
| `text.ErrUnsupported` | The type has no text drawing. All 33 types have one now.                     | It prints the source, and writes a note on stderr.               |

### Colours

With `Color: true`, the drawing has 16-colour ANSI escape codes (SGR 30 to 37 and 90 to 97, and bold). Without it, the lines are plain text. The terminal shows the colours in its own palette, so the drawing follows the terminal theme. The named sketch themes apply to the SVG and the picture, not to text.

| Part                                          | Colour                                         |
| --------------------------------------------- | ---------------------------------------------- |
| Lines and arrows, frames                      | Bright black (grey)                            |
| Boxes                                         | Cyan                                           |
| Notes                                         | Yellow                                         |
| Titles                                        | Bold                                           |
| Critical items, such as a critical gantt task | Red                                            |
| Data series of a chart, in order              | Bright blue, yellow, green, red, cyan, magenta |

### Safety

A label can hold any character, and labels are entity-decoded: `#27;` in a source is an ESC. `sketch/text` writes each character that a terminal acts on as U+FFFD. These are the C0 and C1 controls, DEL, the bidirectional overrides and isolates, the bidirectional marks, and the line and paragraph separators. A label cannot set the window title or write the clipboard of the terminal that shows the drawing.

### tuios mermaid

![tuios mermaid in two tuios panes: a deploy pipeline drawn as a kitty picture on the left, and the same pipeline drawn with box-drawing characters on the right. The two decisions, Image scan and Error rate OK?, are drawn with slanted sides.](https://tuios.dev/shots/sketch-kitty-text.webp)

`tuios mermaid` draws the Mermaid diagrams of a file with sketch. FILE is a `.mmd` file, a Markdown file (each `mermaid` code block), or `-` for standard input.

```bash
tuios mermaid flow.mmd                    # draw it here
tuios mermaid README.md                   # every mermaid block of a Markdown file
tuios mermaid flow.mmd --format text      # box-drawing text, also in a kitty terminal
tuios mermaid flow.mmd -f text --cols 60  # text at most 60 columns wide
tuios mermaid flow.mmd -o flow.png        # save a picture (or .svg)
tuios mermaid flow.mmd --theme nord
tuios mermaid flow.mmd --watch --split    # draw again on every save, source beside it
tuios mermaid --demo --theme flexoki      # type a diagram, for a recording
```

| Flag               | Does                                                                                                                                                                                |
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `-f`, `--format`   | `svg`, `png`, `kitty` or `text`. With no flag, tuios picks one: `kitty` in a terminal with kitty graphics, `text` in another terminal, and `svg` when the output is not a terminal. |
| `--cols`, `--rows` | The size in cells. `0`, the default, is the size of the terminal.                                                                                                                   |
| `-o`, `--out`      | Write to a file. The extension picks SVG or PNG.                                                                                                                                    |
| `--scale`          | Pixels for each SVG unit of a PNG. The default is 2.                                                                                                                                |
| `--diagram N`      | Draw only diagram N of the file, from 1.                                                                                                                                            |
| `--theme NAME`     | The colour theme of a picture: `tuios` (your tuios theme, the default) or a named sketch theme.                                                                                     |
| `-w`, `--watch`    | Draw again each time the file changes. With kitty graphics, the diagram moves to its new layout.                                                                                    |
| `--split`          | With `--watch`, show the source beside the diagram.                                                                                                                                 |
| `--demo`           | Type the diagram one character at a time, for a recording. `--loop` starts again at the end.                                                                                        |

The text output uses colour only when the output is a terminal that shows colour. Piped text is plain. `theme` in the `[mermaid]` table of the tuios config sets the default theme. The [CLI reference](https://tuios.dev/docs/cli-reference#mermaid) lists every flag.

## Themes

pele takes its colours from the page, through `--pele-*` CSS custom properties. A `sketch.Theme` sets those properties. `sketch.Themes()` lists the named themes, and `sketch.ThemeNamed` finds one. Case, spaces and `_` do not matter in the name.

```go
package main

import (
	"fmt"

	"tuios.dev/sketch"
)

func main() {
	for _, t := range sketch.Themes() {
		ground := "light"
		if t.Dark {
			ground = "dark"
		}
		fmt.Printf("%-17s %-17s %s\n", t.Name, t.Title, ground)
	}
}

```

```text title="Output"
pele              pele              light
flexoki           Flexoki           light
flexoki-dark      Flexoki dark      dark
nord              Nord              dark
everforest        Everforest        dark
gruvbox           Gruvbox dark      dark
rose-pine         Rosé Pine         dark
catppuccin-mocha  Catppuccin Mocha  dark
catppuccin-latte  Catppuccin Latte  light
tokyo-night       Tokyo Night       dark
dracula           Dracula           dark
solarized-light   Solarized light   light
kanagawa          Kanagawa          dark

```

| Theme                                                                                           | From                              |
| ----------------------------------------------------------------------------------------------- | --------------------------------- |
| `pele`                                                                                          | pele's own colours                |
| `flexoki`, `flexoki-dark`                                                                       | The pele.run site, light and dark |
| `nord`, `everforest`, `gruvbox`, `rose-pine`                                                    | pele's launch video               |
| `catppuccin-mocha`, `catppuccin-latte`, `tokyo-night`, `dracula`, `solarized-light`, `kanagawa` | Those terminal themes             |

One flowchart in eight of the themes:

*[An interactive figure goes here. Open the page to use it.](https://tuios.dev/docs/libraries/sketch)*

Use a theme in one of two places:

- `raster.Options.Theme` colours the picture. The SVG stays as it is.
- `RenderOptions.Theme` writes the theme into the SVG. With `nil`, the SVG is pele's, byte for byte.

For your own colours, fill a `sketch.Theme`. It has `Bg`, `Fg`, `Muted`, `Line`, `Surface`, `SurfaceAlt`, `Border`, `Accent`, `Critical`, eight `Series` colours, `Font`, `FontMono` and `Radius`. A `nil` colour keeps pele's fallback.

A diagram can set its series colours with Mermaid's palette theme variables, as pele 1.13 does: `pie1` to `pie8`, `git0` to `git7`, `cScale0` to `cScale7` (timeline, radar, treemap and mindmap), `venn1` to `venn8`, and `xyChart.plotColorPalette`. They win over the theme in the SVG and in `sketch/raster`. A value must be a colour: a hex or named colour, or a colour function, and `var()` may read only `--pele-*`. A label on a palette colour takes the theme's light or dark text, whichever reads.

*[An interactive figure goes here. Open the page to use it.](https://tuios.dev/docs/libraries/sketch)*

A diagram can set its own fill with `style` or `classDef`. Text in a theme colour on such a fill can be hard to read. Set `raster.Options.Readable` to fix this. When such text has a contrast under 4.5:1 (`raster.TextFloor`), it changes to the theme's text or background colour. If neither reads, it changes to near-black or white. pele does not do this.

## Options

### RenderOptions

`sketch.RenderOptions` holds pele's render options, plus a few that are not part of pele. A `nil` pointer or a zero value keeps the default.

| Field                                      | Does                                                                                                         |
| ------------------------------------------ | ------------------------------------------------------------------------------------------------------------ |
| `Theme`                                    | Writes a `sketch.Theme` into the SVG. Not part of pele.                                                      |
| `MaxWidth`                                 | The width in pixels that the host has. A type that can draw narrower does so, and its text keeps its size.   |
| `AutoDirection`, `DirectionBreakpoint`     | Let a diagram that runs across run down when it does not fit `MaxWidth`. On by default, under 640 pixels.    |
| `Responsive`                               | Lets the SVG scale to its container.                                                                         |
| `FontFamily`, `FontFamilyMono`, `FontSize` | The fonts that labels are measured and drawn in.                                                             |
| `Measurer`                                 | Measures text. The default is a table of Arial advances, which gives the same output as pele.                |
| `Padding`, `IDPrefix`                      | The space around the diagram, and a prefix for the ids in the SVG.                                           |
| `Limit`, `OutputLimit`, `MaxEdges`         | Lower limits for this host. See [Limits](https://tuios.dev/docs/libraries/sketch#limits).                    |
| `Links`, `LinkSchemes`, `LinkRel`          | Turn links off, set the schemes a link can use, and set its `rel` (`noopener` by default).                   |
| `Images`, `ImageSchemes`                   | Turn images off, and set the schemes an image can use.                                                       |
| `Icons`                                    | Gives the markup of an icon by its name, for diagrams that show icons.                                       |
| `Config`                                   | Mermaid configuration. The configuration in the source takes priority.                                       |
| `Now`, `Location`                          | The time that gantt charts use as now, and the time zone they read dates in. `Location` is not part of pele. |
| `Geometry`                                 | Receives the layout. sketch/text uses it. Not part of pele, and it does not change the SVG.                  |

`sketch.Parse` reads a source once. `Diagram.RenderSVG` draws it, and `text.Draw` draws it as text. Use them to draw one source more than one way.

### Labels

Labels follow pele v1.9.0:

- A label can style text with `<sub>`, `<sup>`, `<code>`, `<kbd>`, `<samp>`, `<tt>`, `<u>`, `<ins>`, `<var>`, `<cite>` and `<dfn>`. sketch drops other HTML tags and keeps their text.
- Text that looks like a tag but is not HTML, such as `List<T>`, stays as it is.
- A label can break at a zero-width space or a soft hyphen (`&shy;`).
- Bold and italic carry across a line break.

### Math labels

A label can hold TeX between `$$` marks. sketch has no typesetter. You give one in `RenderOptions.Math`, a `sketch.MathResolver`:

```go
type MathResolver func(tex string, size float64) (MathMarkup, bool)
```

The resolver gets the TeX without the `$$` marks, and the font size in pixels. It returns a `sketch.MathMarkup`:

| Field             | Holds                                                                                                     |
| ----------------- | --------------------------------------------------------------------------------------------------------- |
| `Markup`          | The inside of an `<svg>` element, or HTML when `HTML` is true.                                            |
| `HTML`            | Marks `Markup` as HTML, which goes in a `<foreignObject>`. The page then needs the CSS of the typesetter. |
| `Width`, `Height` | The size of the markup in pixels.                                                                         |

When there is no resolver, when it returns false, or when the size is not a positive number, the label shows its `$$` source as text. `tuios mermaid` gives no resolver, so its pictures and text drawings show the TeX source.

This program draws one source twice: with a resolver that writes the TeX as italic text, and with no resolver. A real host calls a typesetter in place of `resolve`.

```go
package main

import (
	"fmt"
	"html"
	"log"
	"os"
	"strconv"
	"unicode/utf8"

	"tuios.dev/sketch"
)

const src = `flowchart LR
  a["$$E = mc^2$$"] --> b["$$x < y$$"]
`

// resolve writes the TeX as italic text. A real host calls a typesetter here.
func resolve(tex string, size float64) (sketch.MathMarkup, bool) {
	y := strconv.FormatFloat(size, 'f', -1, 64)
	return sketch.MathMarkup{
		// Escape the TeX: it comes from the author of the diagram.
		Markup: `<text y="` + y + `" font-style="italic">` + html.EscapeString(tex) + `</text>`,
		Width:  float64(utf8.RuneCountInString(tex)) * size * 0.6,
		Height: size * 1.2,
	}, true
}

func main() {
	for _, out := range []struct {
		file string
		opts sketch.RenderOptions
	}{
		{"math.svg", sketch.RenderOptions{Math: resolve}},
		{"math-source.svg", sketch.RenderOptions{}}, // no resolver
	} {
		svg, err := sketch.Render(src, out.opts)
		if err != nil {
			log.Fatal(err)
		}
		if err := os.WriteFile(out.file, []byte(svg.Data), 0o644); err != nil {
			log.Fatal(err)
		}
		fmt.Printf("%s: %.0f by %.0f\n", out.file, svg.Width, svg.Height)
	}
}

```

```text title="Output"
math.svg: 261 by 64
math-source.svg: 309 by 64

```

These are the two files as the program wrote them. With the resolver, each label holds the markup of the resolver:

*[An interactive figure goes here. Open the page to use it.](https://tuios.dev/docs/libraries/sketch)*

With no resolver, each label shows its TeX source between the `$$` marks:

*[An interactive figure goes here. Open the page to use it.](https://tuios.dev/docs/libraries/sketch)*

> **The resolver gets untrusted TeX**
>
> The TeX comes from the author of the diagram, with entities decoded. sketch writes the markup of the resolver into the SVG with no change, as pele does.
>
> - Do not copy the TeX into the markup. Escape it in all markup that you make from it.
> - Do not trust it. Turn off each command that makes a link or runs a script, such as the `trust` option of KaTeX.

## Limits

sketch keeps the limits of pele. A host can set lower limits in `RenderOptions` (and in `ParseOptions` for `sketch.Parse`).

| Limit                                            |                          Default | Error                |
| ------------------------------------------------ | -------------------------------: | -------------------- |
| Source length (`Limit`)                          |                50,000 characters | `limit`              |
| Edges of a flowchart (`MaxEdges`)                |                            5,000 | `limit`              |
| SVG length (`OutputLimit`)                       |             4,000,000 characters | `limit`              |
| Cells of a text drawing (`text.MaxCells`)        |                        4,000,000 | `text.ErrTooLarge`   |
| Pixels of a picture (`raster.Options.MaxPixels`) | 40,000,000, and 32,768 on a side | `raster.ErrTooLarge` |

`sketch/raster` also has a work budget. Each fill costs the pixels of its mask, so a style such as a huge stroke width cannot run for long.

The limits bound the size of the input. Tests also bound the work for each size:

- Parsers that build a string one token at a time stay linear. A test renders statements of 200,000 characters and fails when one allocates more than 512 MB.
- `sketch/text` cuts and wraps labels in linear time. A test draws labels of 50,000 characters and holds the time to a fixed ratio of a short label's time.

### Errors

A source that sketch cannot draw gives a `*sketch.Error`. Its `Code` is one of four values. A syntax error also has `Line` and `Column`.

```go
package main

import (
	"errors"
	"fmt"

	"tuios.dev/sketch"
)

func main() {
	for _, src := range []string{
		"flowchart LR\n  A --> B --> \n",
		"zenuml\n  A.call()\n",
	} {
		_, err := sketch.Render(src, sketch.RenderOptions{})
		var e *sketch.Error
		if errors.As(err, &e) {
			fmt.Printf("code %s, line %d, column %d: %s\n", e.Code, e.Line, e.Column, e.Message)
		}
	}
}

```

```text title="Output"
code syntax, line 2, column 14: Parse error on line 2:
  A --> B --> 
-------------^
Expecting 'NODE_STRING', got 'EOF'
code unsupported-diagram, line 0, column 0: No diagram type detected for the given text.

```

| Code                  | Meaning                                                       |
| --------------------- | ------------------------------------------------------------- |
| `syntax`              | The source does not parse.                                    |
| `semantic`            | The source parses, but the diagram it describes is not valid. |
| `limit`               | The source or the SVG is past a limit.                        |
| `unsupported-diagram` | sketch finds no diagram type, or pele does not draw the type. |

A panic in sketch also comes back as an error with the code `semantic`. A diagram never stops the host.

## Security

sketch follows the safety rules of pele, and adds some of its own.

- **Escaping:** text from the source is escaped in the SVG. Tests port pele's inert-output tests: hostile text goes through every template of each type, and the SVG must have no live markup.
- **Links:** a link is relative, or uses `http`, `https`, `mailto` or `tel`. An image uses `http` or `https`. Other schemes are left out. `LinkSchemes` and `ImageSchemes` change these lists, and `Links` and `Images` turn them off.
- **Fonts:** `Theme.Font` and `Theme.FontMono` must pass pele's check for a font list. A list with `;` is refused, so a font cannot add CSS.
- **Text drawings:** terminal controls in a label become U+FFFD. See [Safety](https://tuios.dev/docs/libraries/sketch#text-safety).
- **Math:** the math resolver gets TeX from the author. See [Math labels](https://tuios.dev/docs/libraries/sketch#math).

sketch reads URLs with Go's `net/url`, and a browser uses the WHATWG URL parser. So some links differ from pele:

- sketch writes no link for `http:host` or `https:/host`, where a browser reads `http://host/`.
- It writes an international host as `%CF%89`, where pele writes `xn--bya`.
- It reads U+2028 and U+2029 as part of a line.
- It folds `ſ` and `K` to `s` and `k`, so it blocks `javaſcript:`, which pele keeps as a relative link.
- It writes `(`, `)`, a soft hyphen or `;` in the user part in another form, and `#` in a fragment as `%23`.

The last gate is the same scheme list as pele's. In a review of 30,000 hostile link targets, no link that sketch wrote led to a scheme other than `http`, `https`, `mailto` or `tel`.

## Fidelity and tests

### Goldens

`TestGolden` draws the 522 sources of the pele documentation corpus. It compares each SVG with the SVG that pele drew from the same source, byte for byte. All 522 match. `testdata/extra` holds more cases that pele drew and its corpus does not cover. Examples are Chinese and Japanese labels that wrap, and the label tags, break hints, class rows, sankey gradients and state curves of pele v1.9.0. They match too. [Diagram types](https://tuios.dev/docs/libraries/sketch/diagram-types#summary) gives the count for each type.

The goldens catch small changes. When the port was new, a change to one layout constant failed 14 of the 114 flowchart goldens.

### Differential tests

Differential tests draw the same source with sketch in Go and with pele in Node, and compare the SVG. They run behind the `differential` build tag.

- Each new type ran against thousands of mutated and random sources. For example: 40,896 block diagrams, 36,240 architecture diagrams and 25,440 requirement diagrams. The only difference was an emoji that the mutator split into half a surrogate pair, which a Go string cannot hold.
- The JavaScript math functions are ported from V8, because Go's `math` package can differ in the last bit. `js.Acos` matches Node on 2,308,009 inputs, where Go's `math.Acos` differs on 737,401 of them. `js.Log` and `js.Log10` match on 1,086,347 inputs.
- `sketch/raster` against `rsvg-convert`, on the 114 flowcharts: a mean difference of 0.59 in 255, and no pixel off by more than 24 in 255.

### Fused multiply-add on arm64

Go may fuse `x*y+z` into one FMA instruction. FMA rounds once, and JavaScript rounds twice, so the last bit can differ and move a line. arm64 fuses, and so does amd64 at `GOAMD64=v3`.

- The ported code wraps each float product in `float64()`. The Go spec says that this rounds the product, so the compiler cannot fuse it.
- CI runs the sketch tests on linux/arm64 and at `GOAMD64=v3`, so a fused product fails a check.
- Before this fix, 3 of 12,000 random block diagrams differed at `GOAMD64=v3`. Two of them are now the goldens `fma-002` and `fma-003`.

### Fuzzing

Fuzz targets cover rendering, detection, the layout, `sketch/raster` (still pictures and motion) and `sketch/text`. They run each night in CI. Each new type ran `FuzzRender` and the text `FuzzDraw` for one to four minutes, with up to 5.8 million runs. No run found a problem.

## Performance and size

From the perf pass of October 2026, on an Intel Core i7-10700 with Linux, pinned to one core. The [perf record](https://github.com/Gaurav-Gosain/tuios/blob/main/docs/perf.md) of tuios has the method.

| Measure                                                               |    Time |
| --------------------------------------------------------------------- | ------: |
| Render one diagram of the pele corpus, mean (`BenchmarkRenderCorpus`) | 38.9 µs |
| Median render, 421 diagrams of other docs                             | 32.7 µs |
| p95 render, the same diagrams                                         | 70.9 µs |
| A new process draws one flowchart (`tuios mermaid`)                   | 1.12 ms |
| Start sketch's packages                                               | 0.08 ms |

A test holds a golden render to 260 allocations, and the start of the internal packages to 400 allocations. An allocation count does not depend on the machine, so the tests read no clock.

Against pele in Node 24 on one machine, on the 152 flowchart and sequence sources of the corpus, sketch was faster on every source. The median render took 21.8 µs in sketch and 43.6 µs in pele. A new process that draws one diagram took about 2 ms with sketch and about 60 ms with pele.

sketch adds no third-party dependency. The diagram types make the tuios binary larger: for example, eight types from tree views to railroad diagrams added 892,928 bytes on linux/amd64. The size ceiling of tuios went from 40 MB to 50 MB for sketch. The diagram types will move to plugins when tuios has them.

## API overview

| Name                                                                                                                                                                         | Does                                                                               |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| [`Render`](https://pkg.go.dev/tuios.dev/sketch#Render), [`SVG`](https://pkg.go.dev/tuios.dev/sketch#SVG)                                                                     | Draws a source as SVG.                                                             |
| [`Parse`](https://pkg.go.dev/tuios.dev/sketch#Parse), [`Diagram`](https://pkg.go.dev/tuios.dev/sketch#Diagram)                                                               | Parses a source once, to draw it as SVG or as text.                                |
| [`Detect`](https://pkg.go.dev/tuios.dev/sketch#Detect), [`Supports`](https://pkg.go.dev/tuios.dev/sketch#Supports)                                                           | Gives the diagram type of a source, and tells if sketch draws it.                  |
| [`Themes`](https://pkg.go.dev/tuios.dev/sketch#Themes), [`ThemeNamed`](https://pkg.go.dev/tuios.dev/sketch#ThemeNamed), [`Theme`](https://pkg.go.dev/tuios.dev/sketch#Theme) | The named themes, and the colours of a theme.                                      |
| [`Error`](https://pkg.go.dev/tuios.dev/sketch#Error)                                                                                                                         | An error with a code, a line and a column.                                         |
| [`raster.Draw`](https://pkg.go.dev/tuios.dev/sketch/raster#Draw)                                                                                                             | Draws SVG from sketch as an image.                                                 |
| [`raster.ParseScene`](https://pkg.go.dev/tuios.dev/sketch/raster#ParseScene), [`raster.NewMotion`](https://pkg.go.dev/tuios.dev/sketch/raster#NewMotion)                     | The motion between two versions of a diagram, as `tuios mermaid --watch` shows it. |
| [`text.Draw`](https://pkg.go.dev/tuios.dev/sketch/text#Draw)                                                                                                                 | Draws a diagram with box-drawing characters.                                       |

## Where it fits

- tuios draws `tuios mermaid` with sketch: a picture through kitty graphics, or text.
- The [playground](https://tuios.dev/docs/libraries/sketch/playground) is sketch compiled to WebAssembly.
- `sketch/text` draws XY charts with [plot](https://tuios.dev/docs/libraries/plot). sketch imports no other tuios library and no tuios package.

## Credit

sketch is a port of [pele](https://github.com/obsidianmd/pele), the Mermaid renderer by [kepano](https://github.com/kepano) of [Obsidian](https://obsidian.md/). pele is under the MIT licence, and so is the port. The port follows pele v1.9.0 (commit `e7f092a`). Each Go file is the port of one pele file and keeps its names and comments, so a change upstream maps to a change in sketch. The layout, the shapes, the safety rules, the test corpus and the themes from pele's site and launch video are pele's work.

The pictures use subsets of [Arimo](https://github.com/googlefonts/Arimo) (SIL Open Font License 1.1) and Go Mono. The licence notices are in `sketch/LICENSE` and `sketch/raster/fonts/NOTICE`.

## Versions

The module is at v0. The API can change between minor versions. Its tags have the folder name as a prefix, such as `sketch/v0.1.1`. The source is in the [sketch folder](https://github.com/Gaurav-Gosain/tuios/tree/main/sketch) of the tuios repository, under the MIT licence.
