# tml

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

> The TML language as a Go library. Parse, print and validate documents for terminal surfaces, evaluate their bindings, run local actions and apply JSON Patch to their state.

`tuios.dev/tml` is the TML language. A TML document is a tree of components from a fixed catalog, with a JSON state store. A program, a plugin or an agent sends one to a host, and the host draws it in a pane, a popup or a dock cell. This library is the language. It draws nothing. [loom](https://tuios.dev/docs/libraries/loom) draws it.

![A test run drawn from one TML document: tabs, stat tiles with sparklines, a pass-rate gauge, a bar chart by package, a line chart of past runs, a failures table with a cursor row and a row of buttons, in the frame tuios draws around a surface](https://tuios.dev/libs/tml/hero.webp)

*One TML document, drawn by loom in the frame tuios puts around a surface. Every picture on this page is drawn from real code by the docs build scripts.*

The library uses only the standard library. The API reference is on [pkg.go.dev](https://pkg.go.dev/tuios.dev/tml).

## Quickstart

```bash
go get tuios.dev/tml tuios.dev/loom
```

This program checks a document, draws it, changes its state with a JSON Patch and draws it again:

```go title="main.go"
package main

import (
	"fmt"
	"log"

	"tuios.dev/loom"
	"tuios.dev/tml"
)

const src = `<tml version="1" title="Build">
  <state>{"pct": 40, "step": "Compiling"}</state>
  <card title="Build">
    <text>Step: <b>{state.step}</b></text>
    <progress value="{state.pct / 100}"/>
  </card>
</tml>`

func main() {
	// Check parses and validates the document.
	doc, problems, err := tml.Check([]byte(src), nil)
	if err != nil {
		log.Fatal(problems)
	}

	// tml draws nothing. loom draws the document into cells.
	s, err := loom.New(doc, nil)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(s.Render(40, 3).Render())

	// The owner changes the state with a JSON Patch.
	ops, err := tml.DecodePatch([]byte(`[
	  {"op": "replace", "path": "/pct", "value": 80},
	  {"op": "replace", "path": "/step", "value": "Linking"}]`), nil)
	if err != nil {
		log.Fatal(err)
	}
	if err := s.Patch(ops); err != nil {
		log.Fatal(err)
	}
	fmt.Println(s.Render(40, 3).Render())
}

```

![The output of the program: the Build card at 40 percent with the step Compiling, then the same card at 80 percent with the step Linking](https://tuios.dev/libs/tml/quickstart.webp)

## How it works

A document has two parts: a tree of components and a JSON state. Attributes read the state through bindings, such as `{state.pct / 100}`. The owner of a surface changes the state with JSON Patch, and the host draws again only what reads the changed paths.

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

- **Two encodings.** TML text is a strict XML subset for files and people. TML JSON is for the wire and for agents. Both parsers give the same canonical tree, and a canonical tree prints and reads back unchanged in either encoding.
- **Roles, never colours.** A colour is a theme role, such as `success` or `mute`. A hex colour is an error, so every surface follows the theme of the host.
- **No code runs.** Expressions compute values. They cannot loop, assign or call out, and each frame has a step budget.
- **Local actions.** Tabs, sorting, the cursor, `set` and `toggle` run in the host at once. `emit` and `close` go back to the owner as events.

The same document in TML text and in TML JSON:

```xml
<tml version="1" title="Build">
  <state>{"pct": 40, "step": "Compiling"}</state>
  <card title="Build">
    <text>Step: <b>{state.step}</b></text>
    <progress value="{state.pct / 100}"/>
  </card>
</tml>
```

```json
{"type": "tml", "version": 1, "title": "Build", "state": {"pct": 40, "step": "Compiling"},
 "children": [{"type": "card", "title": "Build", "children": [
   {"type": "text", "children": ["Step: ", {"type": "b", "children": ["{state.step}"]}]},
   {"type": "progress", "value": "{state.pct / 100}"}]}]}
```

The root is `tml`, or one block component for a small surface, such as a dock cell. The examples below use both forms.

## Components

Each picture is the TML above it, drawn by loom in the site's theme.

### Layout

`row` lays its children out left to right, and `col` top to bottom. `gap` puts empty cells between children. `justify` and `align` place them. A `spacer` takes the free space.

```xml
<col gap="1">
  <row gap="2"><badge>one</badge><badge>two</badge><badge>three</badge></row>
  <row><text>left</text><spacer/><text role="mute">a spacer pushes this to the right</text></row>
  <row justify="center" gap="2"><badge role="info">justify="center"</badge></row>
  <row justify="between"><badge>a</badge><badge>b</badge><badge>c</badge></row>
</col>

```

![Badges in a row with a gap, text pushed to the right by a spacer, a centred badge, and three badges spread across the row](https://tuios.dev/libs/tml/layout-row.webp)

```xml
<row gap="4">
  <col gap="1" w="fill">
    <text role="mute">col gap="1"</text>
    <badge w="fill">first</badge>
    <badge w="fill">second</badge>
    <badge w="fill">third</badge>
  </col>
  <col align="end" w="fill">
    <text role="mute">col align="end"</text>
    <badge role="info">short</badge>
    <badge role="info">a longer one</badge>
    <badge role="info">mid</badge>
  </col>
</row>

```

![Two columns: badges stacked with one empty row between them, and badges aligned to the right edge](https://tuios.dev/libs/tml/layout-col.webp)

`w` and `h` take cells, a percentage, `fill` or `fill:N`. A `fill` box shares the free space with the other `fill` boxes, by its weight N. `min-w`, `max-w`, `min-h` and `max-h` bound a size. `pad` takes one, two or four cell counts.

```xml
<col gap="1">
  <row gap="1">
    <stat label="w=14" value="fixed" w="14" h="3"/>
    <stat label="w=fill" value="one share" w="fill" h="3" role="info"/>
    <stat label="w=fill:2" value="two shares" w="fill:2" h="3" role="success"/>
  </row>
  <row gap="1">
    <stat label="w=25%" value="a quarter" w="25%" h="3"/>
    <stat label="max-w=18" value="capped" w="fill" max-w="18" h="3" role="info"/>
    <stat label="w=fill" value="the rest" w="fill" h="3" role="success"/>
  </row>
</col>

```

![Two rows of stat tiles. In the first, a fixed tile of 14 cells, a tile with one share and a tile with two shares. In the second, a quarter, a tile capped at 18 cells and a tile that takes the rest](https://tuios.dev/libs/tml/layout-fill.webp)

`grid` wraps its children into equal columns:

```xml
<grid cols="3" gap="1">
  <stat label="session" value="6.2s" role="info"/>
  <stat label="app" value="4.8s" role="info"/>
  <stat label="vt" value="3.1s" role="info"/>
  <stat label="tape" value="1.4s"/>
  <stat label="config" value="0.9s"/>
  <stat label="terminal" value="0.8s"/>
</grid>

```

![Six stats in a grid of three columns](https://tuios.dev/libs/tml/layout-grid.webp)

`stack` layers its children, `scroll` scrolls them, and `split` holds two children with a divider that a person can drag.

### Text

`text` holds inline components: `b`, `i`, `u`, `s`, `code`, `c` (a colour role), `kbd` and `a` (a link). `heading` has three levels.

```xml
<col gap="1">
  <heading level="1">Release v0.11</heading>
  <heading level="2">What changed</heading>
  <text wrap="word">Text holds <b>bold</b>, <i>italic</i>, <u>underline</u>, <s>strike</s>,
    <code>inline code</code>, <c role="success">a role colour</c>, a key such as
    <kbd>ctrl+b</kbd> and <a href="https://tuios.dev">a link</a>.</text>
  <text role="mute" align="right">role="mute" align="right"</text>
</col>

```

![A first-level heading, a second-level heading with a rule, a paragraph with bold, italic, underline, strike, inline code, a green phrase, a key and a link, and a right-aligned muted line](https://tuios.dev/libs/tml/text.webp)

### Stat, gauge and progress

A `stat` is a labelled number. With a height of 3 it is a tile. A `gauge` shows a value against a maximum. A `progress` bar takes a value from 0 to 1.

```xml
<col gap="1">
  <row gap="3">
    <stat label="passed" value="412" delta="+12" role="success"/>
    <stat label="failed" value="3" delta="-2" role="error"/>
    <stat label="wall time" value="18.4s"/>
  </row>
  <row gap="2">
    <stat label="passed" value="412" delta="+12" role="success" w="18" h="3"/>
    <stat label="failed" value="3" delta="-2" role="error" w="18" h="3"/>
    <stat label="wall time" value="18.4s" w="18" h="3"/>
  </row>
</col>

```

![Three stats on one line with their deltas, and the same three stats as tiles with a coloured edge](https://tuios.dev/libs/tml/stat.webp)

```xml
<col>
  <gauge value="43" max="100" label="CPU"/>
  <gauge value="98.8" max="100" role="success"/>
  <progress value="0.4"/>
  <progress value="0.75" label="3 of 4" role="success"/>
</col>

```

![A CPU gauge at 43 percent, a green gauge at 98.8 percent, a progress bar at 40 percent and a green progress bar labelled 3 of 4](https://tuios.dev/libs/tml/gauge.webp)

### Badge and status

A `badge` is a short coloured tag. `status` shows the tuios agent state glyph and word. `spinner` is a busy mark.

```xml
<col gap="1">
  <row gap="1">
    <badge>v0.11</badge><badge role="success">passing</badge><badge role="warning">3 risky</badge>
    <badge role="error">2 failed</badge><badge role="info">draft</badge>
  </row>
  <row gap="3">
    <status state="working"/><status state="needs_input"/><status state="done"/>
    <status state="errored"/><status state="idle"/>
  </row>
  <row gap="1"><spinner label="Compiling"/></row>
</col>

```

![Five badges in different roles, the five agent states working, needs input, done, errored and idle, and a spinner labelled Compiling](https://tuios.dev/libs/tml/badge.webp)

### Table

A `table` shows the rows of a state array. Each `column` names a field. `format` is an expression for the cell, with `value` and `row`. `sort` gives the first order, and `select="single"` gives a cursor.

```xml
<tml version="1">
  <state>{"rows": [
    {"pkg": "internal/session", "test": "TestAttachRace", "ms": 2210},
    {"pkg": "internal/session", "test": "TestAttachReplay", "ms": 1950},
    {"pkg": "internal/app", "test": "TestDockClick", "ms": 840},
    {"pkg": "internal/app", "test": "TestDockCustomWidth", "ms": 610},
    {"pkg": "vt", "test": "TestKittyPlaceholder", "ms": 120}]}</state>
  <table rows="state.rows" key="test" sort="ms:desc" select="single">
    <column field="pkg" title="Package" w="fill"/>
    <column field="test" title="Test" w="fill:2"/>
    <column field="ms" title="Time" align="right" format="dur(value, 'ms')" sort="true"/>
  </table>
</tml>

```

![A table of five failed tests with package, test and time columns, sorted by time from the longest, with the cursor on the first row](https://tuios.dev/libs/tml/table.webp)

### List, tree and kv

A `list` repeats its children once per element of a state array. A `tree` shows nested state objects. A `kv` shows key and value pairs in two aligned columns. A long value wraps onto more rows under its value column.

```xml
<tml version="1">
  <state>{"agents": [
    {"name": "claude", "task": "Add tests for the store", "state": "working"},
    {"name": "codex", "task": "Add a delete endpoint", "state": "needs_input"},
    {"name": "gemini", "task": "Use the system font", "state": "done"}]}</state>
  <list items="state.agents" as="a" select="single">
    <row gap="2"><text w="8">{a.name}</text><text w="fill" role="dim">{a.task}</text><status state="{a.state}"/></row>
  </list>
</tml>

```

![A list of three agents with their tasks and states, with the cursor on the first](https://tuios.dev/libs/tml/list.webp)

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

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

### Card and tabs

A `card` is a titled block that a person can fold. `tabs` shows one `tab` at a time. A tab title can hold a binding.

```xml
<col gap="1">
  <card title="Failures" meta="3" role="error">
    <text>Three tests failed.</text>
    <text role="dim">Press r to run them again.</text>
  </card>
  <card title="Passed" meta="412" role="success" fold="true">
    <text>Hidden while the card is folded.</text>
  </card>
</col>

```

![An open card titled Failures 3 with two lines of text, and a folded card titled Passed 412](https://tuios.dev/libs/tml/card.webp)

```xml
<tml version="1">
  <state>{"failed": 3}</state>
  <tabs>
    <tab id="sum" title="Summary"><text>412 passed, 3 failed, 9 skipped.</text></tab>
    <tab id="fail" title="Failures {state.failed}"><text>Three failed.</text></tab>
    <tab id="log" title="Log"><code>ok  tuios.dev/vt  12.1s</code></tab>
  </tabs>
</tml>

```

![Three tabs, Summary, Failures 3 and Log, with the Summary tab open](https://tuios.dev/libs/tml/tabs.webp)

`modal` is a box that holds the focus while it is open. `toast` is a short notice that goes away.

### Charts

`bar`, `line`, `area`, `sparkline`, `histogram`, `heatmap` and `pie` read a state array. `x`, `y` and `v` name the fields. [plot](https://tuios.dev/docs/libraries/plot) draws them.

```xml
<tml version="1">
  <state>{"pkgs": [{"pkg": "session", "s": 6.2}, {"pkg": "app", "s": 4.8}, {"pkg": "vt", "s": 3.1}, {"pkg": "tape", "s": 1.4}],
    "runs": [{"run": 1, "s": 21}, {"run": 2, "s": 23}, {"run": 3, "s": 20}, {"run": 4, "s": 26}, {"run": 5, "s": 24},
      {"run": 6, "s": 19}, {"run": 7, "s": 22}, {"run": 8, "s": 27}, {"run": 9, "s": 25}, {"run": 10, "s": 21}],
    "wall": [41, 39, 44, 40, 52, 47, 38, 45, 49, 43, 41, 50],
    "lang": [{"lang": "Go", "lines": 900}, {"lang": "Shell", "lines": 240}, {"lang": "TOML", "lines": 120}]}</state>
  <grid cols="2" gap="2">
    <bar data="state.pkgs" x="pkg" y="s" dir="h" title="Seconds by package" h="5"/>
    <line data="state.runs" x="run" y="s" title="Suite time" h="5"/>
    <sparkline values="state.wall" title="Wall time"/>
    <pie data="state.lang" label="lang" v="lines" style="donut" h="5"/>
  </grid>
</tml>

```

![Four charts in a grid: horizontal bars of seconds by package, a line of suite time, columns of wall time, and a donut of lines by language with its legend](https://tuios.dev/libs/tml/charts.webp)

### Mermaid

`mermaid` holds a Mermaid diagram. loom draws it as text with [sketch](https://tuios.dev/docs/libraries/sketch), fitted to the width of the element, in the theme's colours. A diagram taller than its box scrolls with the wheel. A diagram that sketch cannot draw shows its source under a note that says why.

tuios draws eight diagram types itself. In tuios, a panel draws the other types through the [sketch plugin](https://tuios.dev/docs/plugins#plugins-of-the-tuios-release) (Unreleased). Run `tuios plugins install sketch` to get it. Without the plugin, the panel shows the source, and a notice says what to run.

```xml
<tml version="1">
  <mermaid>
flowchart LR
  P[Prompt] --> A[Agent works]
  A --> R[Review]
  R --> S[Ship]
  </mermaid>
</tml>
```

`tuios tml render` draws it like this:

```
┌─────────┐      ┌─────────────┐      ┌─────────┐     ┌──────┐
│ Prompt  │─────►│ Agent works │─────►│ Review  │────►│ Ship │
└─────────┘      └─────────────┘      └─────────┘     └──────┘
```

The text of a `mermaid` element is kept as written. Bindings do not apply in it.

### Forms

`form`, `input`, `textarea`, `select`, `checkbox`, `toggle` and `slider` collect values, and `button` with `submit` sends them. loom shows each field with its label and value. Editing comes in a later release.

## Motion (Unreleased)

A node can play an effect when it shows and when it goes away. A container can start the effects of its children one after the other.

```xml
<tml version="1" title="Jobs">
  <state>{"loading": true, "jobs": [{"name": "build"}, {"name": "test"}], "saved": "Saved", "cpu": "12%"}</state>
  <col pad="1" gap="1" stagger="60ms">
    <card each="state.jobs" key="{item.name}" title="{item.name}" enter="slide-up" exit="fade">
      <text>Running</text>
    </card>
    <card title="Host" skeleton="{state.loading}" h="4">
      <text>CPU {state.cpu}</text>
    </card>
    <toast role="success" ttl="4s">{state.saved}</toast>
  </col>
</tml>
```

| Attribute  | What it does                                                                                                                                                                                 |
| ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `enter`    | Plays when the node shows: `fade`, `slide-up`, `slide-down`, `slide-left`, `slide-right`, `iris` or `decode`. A surface that opens plays the `enter` of each node in it                      |
| `exit`     | Plays when the node goes away: its `if` turns false, its item leaves an `each`, or a modal closes. A node that goes away with its parent, such as the content of a closed tab, plays no exit |
| `stagger`  | On a container. Starts the `enter` of each child this much time after the child before it                                                                                                    |
| `skeleton` | Draws placeholder bars in the space of the node while it is true. The content fades in when it turns false. Give the node an `h`, so that its space stays the same                           |
| `ttl`      | On a `toast`. The toast goes away at the end of this time. A new text shows it again                                                                                                         |

Every component takes `enter`, `exit`, `skeleton` and `stagger`. With `appearance.motion = "none"` or [calm mode](https://tuios.dev/docs/configuration#calm-mode), nodes show at once, and a toast still goes away at the end of its `ttl`. `tuios tml render` draws the last frame.

## State and bindings

A value in braces is a binding: one expression that reads the state. The language is small and total. Every expression gives a value, and a mismatch gives `null`.

```xml
<tml version="1">
  <state>{"ok": 412, "failed": 3, "wall_ms": 18412, "rss": 36700160, "branch": "fix/token-refresh"}</state>
  <kv>
    <item k="Branch" v="{upper(state.branch)}"/>
    <item k="Pass rate" v="{round(pct(state.ok, state.ok + state.failed), 1)}%"/>
    <item k="Wall time" v="{dur(state.wall_ms)}"/>
    <item k="Memory" v="{bytes(state.rss)}"/>
    <item k="Result" v="{state.failed > 0 ? state.failed + ' failed' : 'all passed'}"/>
    <item k="Missing" v="{state.nothing ?? 'no value'}"/>
  </kv>
</tml>

```

![Six bound values: the branch in capitals, a pass rate of 99.3 percent, a wall time of 18.41 seconds, a memory size of 35M, the result 3 failed, and the fallback text no value](https://tuios.dev/libs/tml/bindings.webp)

- Paths: `state.a.b`, `state.items[0]`, `item.x` inside `each`, `form.tag` inside a form, `event.value` inside an action, and `view.width`.
- Operators: `+ - * / %`, comparisons, `&& || !`, `a ? b : c`, and `??` for a null value.
- Functions: `len`, `sum`, `avg`, `min`, `max`, `round`, `abs`, `pct`, `fmt`, `dur`, `bytes`, `ago`, `upper`, `lower`, `trim`, `join`, `contains`, `starts`, `pick` and `count`.
- `each="state.items" as="item"` repeats a node. `if` drops a node when false. `show` hides it and keeps its space.

Each surface has a budget of 10,000 steps per frame. Past the budget, a binding shows `!`. Each expression records the state paths it reads, so a renderer draws again only what a patch touches.

## Update with JSON Patch

The owner changes the state with an RFC 6902 JSON Patch. A patch is atomic: it applies in full, or not at all. The size limit is checked after every operation.

```json title="patch.json"
[
  { "op": "replace", "path": "/pct", "value": 80 },
  { "op": "replace", "path": "/step", "value": "Linking" },
  { "op": "add", "path": "/log/-", "value": "go test ./..." }
]

```

```xml
<tml version="1" title="Build">
  <state>{"pct": 40, "step": "Compiling", "log": ["go vet ./...", "go build ./cmd/tuios"]}</state>
  <col gap="1">
    <row gap="2"><text>Step: <b>{state.step}</b></text><spacer/><badge role="info">{len(state.log)} steps</badge></row>
    <progress value="{state.pct / 100}"/>
    <col><text each="state.log" as="line" role="dim">$ {line}</text></col>
  </col>
</tml>

```

![Before the patch: step Compiling, 2 steps, progress at 40 percent and two commands](https://tuios.dev/libs/tml/patch-before.webp)

*Before the patch*

![After the patch: step Linking, 3 steps, progress at 80 percent and three commands](https://tuios.dev/libs/tml/patch-after.webp)

*After the patch*

In Go:

```go
store, err := tml.StoreFor(doc, nil) // nil means the default limits
if err != nil {
	return err
}
ops, err := tml.DecodePatch(patch, nil)
if err != nil {
	return err
}
changed, err := store.Apply(ops) // the JSON Pointers that changed, such as [/pct /step /log]
```

A patch with a `test` operation that no longer matches is refused. Read the state again, then send a new patch.

## Events and actions

An action attribute, such as `on-press`, holds one or more calls separated by `;`. A button's `key` works from anywhere on the surface.

```xml
<tml version="1" title="Deploy">
  <state>{"tag": "v0.11.0", "risky": 2}</state>
  <col gap="1">
    <text>Deploy <b>{state.tag}</b>? <c role="warning">{state.risky} risky changes</c></text>
    <row gap="2">
      <button key="y" kind="primary" on-press="close('yes')">Deploy</button>
      <button key="n" on-press="close('no')">Cancel</button>
      <button key="d" on-press="emit('diff', state.tag)">Show diff</button>
    </row>
  </col>
</tml>

```

![A question, Deploy v0.11.0 with 2 risky changes, and three buttons: Deploy with the key y, Cancel with n, and Show diff with d](https://tuios.dev/libs/tml/confirm.webp)

loom runs the local actions. The others come back to the program. Pressing d and then y on this surface returns:

```text
key d: emit "diff" v0.11.0
key y: close "" yes

```

| Action                                                                          | Runs    | Effect                                                             |
| ------------------------------------------------------------------------------- | ------- | ------------------------------------------------------------------ |
| `set('path', expr)`, `toggle('path')`                                           | Locally | Change the state.                                                  |
| `tab('id')`, `sort('field')`, `filter('id', expr)`, `fold('id')`, `focus('id')` | Locally | Change the view.                                                   |
| `emit('name', expr)`                                                            | Owner   | Send an event.                                                     |
| `close(expr)`                                                                   | Owner   | Close the surface with a value.                                    |
| `copy(expr)`                                                                    | Host    | Put text on the clipboard.                                         |
| `open('file:path')`                                                             | Host    | Open a file under the owner's files folder.                        |
| `pane('verb', ...)`                                                             | Host    | Run `focus`, `new-window` or `send-text` under the owner's grants. |

## Errors that name the fix

`tml.Check` reports up to 20 problems in one pass. Each problem has a line and a column, a JSON Pointer to the node, a code, and the closest legal value.

```xml title="broken.tml"
<tml version="1">
  <state>{"rows": []}</state>
  <col>
    <chart-bar data="state.rows"/>
    <text role="#ff0000">Build failed</text>
    <table rows="state.rows" sortBy="ms"><column field="ms"/></table>
  </col>
</tml>

```

```text
4:5: <chart-bar> is not a TML component. (unknown_component at /children/0/children/0) Did you mean "bar"?
5:11: role takes a theme role, never a colour value such as "#ff0000". tuios picks the colour from the theme. (hex_color at /children/0/children/1/role)
6:30: table has no attribute 'sortBy'. (unknown_attribute at /children/0/children/2/sortBy) Did you mean "sort"?

```

`*tml.Error` marshals to the error object a host sends back, so an agent can read each fix.

## Limits and safety

A document comes from a program, a plugin or an agent, so the library treats it as untrusted.

- No code from a document runs. Expressions cannot loop, assign or call out, and each frame has a step budget.
- The store removes control, bidi and invisible characters from every string and key it takes in: the document's state, patch values and `Set`. Evaluated bindings are cleaned too.
- A hex colour is an error. A link opens only after the person confirms it.
- `StoreFor` keeps the tree, and refuses a patch that grows `each`, `list`, the images or the rows past their limits.

| Limit                                      | Value                                             |
| ------------------------------------------ | ------------------------------------------------- |
| Document                                   | 256 KiB, 1 MiB from the person's own command line |
| Nodes                                      | 5,000                                             |
| Depth                                      | 32                                                |
| State                                      | 1 MiB                                             |
| Nodes that `each` and `list` expand to     | 2,000                                             |
| Rows and data points, after `each` expands | 50,000                                            |
| Patch                                      | 64 KiB, 100 a second per surface                  |
| Images                                     | 4 per document, 4 MiB each                        |

For a host: give `Env.Budget` one `tml.NewBudget()` for all the bindings of a frame. A nil budget gets a fresh one for each call, which bounds one binding but not a frame.

## Show a document without tuios

The `tml` command shows a document full screen in any terminal, or prints it once as text. It is part of loom:

```bash
go install tuios.dev/loom/cmd/tml@latest
tml report.tml
```

[The tml command](https://tuios.dev/docs/libraries/loom#tml-command) on the loom page has the release archives and the flags.

## Show a document in tuios

> `tuios tml` is in tuios v0.11.0 and later.

`tuios tml show FILE` shows a document as a popup or as a pane. tuios draws it with loom in your theme, and keys and the mouse work in it. The daemon keeps the surface, so it stays when you detach.

```bash
tuios tml validate test-run.tml        # check it first: each problem names the fix
tuios tml render test-run.tml          # see it drawn as text; opens nothing
tuios tml show test-run.tml --pane     # a tiled pane; it prints the surface id
```

![The test run dashboard in a tuios pane, zoomed to fill the screen. The title bar shows Test run, then from shell.](https://tuios.dev/shots/tml-show-pane.webp)

The title bar shows the document's title, then who opened the surface: "from" and the name of that pane, or its id when it has no name. The document cannot change the owner. A surface does not take the focus: click it to use it.

A text field takes typed text and a paste, in a popup, in a pane and in the agents view. Tab or a click goes into a field, and Esc leaves it. Enter submits the form. While a field has the focus, a button's key, such as y, types the letter. A paste with no field to take it tells you to select a field first.

### Read a surface as text (Added in v0.11.1)

An agent cannot see your screen. It reads a surface as text before and after it shows it.

```bash
tuios tml render dash.tml                          # drawn at the terminal's width, or 100
tuios tml render dash.tml --width 80 --height 24 --tab log
tuios tml render dash.tml --state '{"runs":12}'
tuios capture-pane -s "$TUIOS_SESSION" -w WINDOW   # an open surface, as drawn
```

- `tml render` draws the document as tuios draws it in a pane, and opens nothing. It needs no daemon.
- The width is the terminal's width, or 100 when standard output is not a terminal. Without `--height`, the document gets the rows it needs.
- `--state` replaces the state. `--tab` opens a tab by its id. `--ansi` keeps the colours as ANSI escape sequences.
- When the document is not valid, `tml render` prints the problems and exits with status 1.
- `capture-pane` on the window of a surface prints the surface as drawn, at the window's size. It uses the surface's state and the view that a client last reported: the open tab, the cursor rows and the scroll place. `--json` adds `surface` to the result.

### Ask a question and wait for the answer

With `--wait`, the command stays open until the surface closes, and prints the value the document closed with.

```bash
answer=$(tuios tml show deploy.tml --wait)   # "yes", "no", or null
```

![The deploy question in a dialog over the panes. Its frame reads from shell, then the title Deploy. The buttons are Deploy, Cancel and Show diff.](https://tuios.dev/shots/tml-show-popup.webp)

`--wait` exits with 0 for the person's answer, 1 when the person closed the popup with no value, and 2 when a program closed it with `tuios tml close`.

### Dock a popup as a pane

You choose where a document sits. Ctrl+B t f docks the focused popup as a tiled pane, and floats a TML pane as a popup again. The `dock` control on the popup's top border and the `float` control on the pane's title bar do the same. The palette's "Toggle floating" works too.

![The deploy question after Ctrl+B t f. It is a tiled pane under the api pane, named deploy, from api, with float on its title bar. The api pane still waits for the answer.](https://tuios.dev/shots/tml-dock.webp)

The surface keeps its state and what you typed. The command that waits with `--wait` keeps waiting. A patch or a new document from the owner does not move the surface back.

Each document that an agent's pane shows is also on the agent's Artifacts tab in the agents view. There you answer a form without leaving the view. See [Artifacts](https://tuios.dev/docs/agent-inbox#artifacts).

### Own a live surface

With `--events`, the command prints one JSON line for each `emit` and for the close. A script reads the lines and answers with a patch or a new document.

```bash
tuios tml show dash.tml --pane --events     # prints tml_opened, then one line per event
tuios tml patch SURFACE '[{"op":"replace","path":"/passed","value":413}]'
tuios tml replace SURFACE next.tml --keep-state
tuios tml get SURFACE
tuios tml list
tuios tml close SURFACE '"done"'
```

From a pane, these commands need the `write` grant. Only the pane that opened a surface can patch, replace or close it. A `pane()` action runs with the grants of the pane that opened the surface, and tuios asks the person before a surface first types into a pane. The [CLI reference](https://tuios.dev/docs/cli-reference) lists every flag.

## How do I

- **Check a document before I send it?** Call `tml.Check(src, nil)`, or run `tuios tml validate FILE`.
- **Convert between TML text and JSON?** Call `tml.Format(src, tml.JSONEncoding, nil)`, or `tml.TextEncoding` for text.
- **Give an agent the format?** `tml.Schema()` returns the JSON Schema of TML JSON. It is also in the module as `tml.schema.json`.
- **Change one value?** Send a patch with one `replace` operation. Use `add` with the path `/log/-` to append to an array.
- **Change the layout with the width?** Read `view.band` in an `if`: `narrow` below 72 cells, `medium` below 120 and `wide` from 120.
- **Draw a document in my own program?** Use [loom](https://tuios.dev/docs/libraries/loom).
- **Get an answer from a person in a script?** Run `tuios tml show FILE --wait`, and use `close('value')` on the buttons.

## API overview

| Name                                                                                                                                                                        | Does                                                     |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------- |
| [`Check`](https://pkg.go.dev/tuios.dev/tml#Check)                                                                                                                           | Parses and validates a document in either encoding.      |
| [`Parse`](https://pkg.go.dev/tuios.dev/tml#Parse), [`Validate`](https://pkg.go.dev/tuios.dev/tml#Validate)                                                                  | The two steps of `Check`, apart.                         |
| [`Format`](https://pkg.go.dev/tuios.dev/tml#Format)                                                                                                                         | Prints a document in canonical TML text or TML JSON.     |
| [`Schema`](https://pkg.go.dev/tuios.dev/tml#Schema)                                                                                                                         | Returns the JSON Schema of TML JSON.                     |
| [`Node`](https://pkg.go.dev/tuios.dev/tml#Node)                                                                                                                             | One node of the tree: its type, attributes and children. |
| [`StoreFor`](https://pkg.go.dev/tuios.dev/tml#StoreFor), [`Store`](https://pkg.go.dev/tuios.dev/tml#Store)                                                                  | The state of a document, with its limits.                |
| [`DecodePatch`](https://pkg.go.dev/tuios.dev/tml#DecodePatch), [`Op`](https://pkg.go.dev/tuios.dev/tml#Op)                                                                  | JSON Patch operations.                                   |
| [`ParseTemplate`](https://pkg.go.dev/tuios.dev/tml#ParseTemplate), [`ParseExpr`](https://pkg.go.dev/tuios.dev/tml#ParseExpr), [`Env`](https://pkg.go.dev/tuios.dev/tml#Env) | Bindings and expressions, and what they read.            |
| [`ParseActions`](https://pkg.go.dev/tuios.dev/tml#ParseActions)                                                                                                             | Parses and checks an action attribute.                   |
| [`Problem`](https://pkg.go.dev/tuios.dev/tml#Problem), [`Error`](https://pkg.go.dev/tuios.dev/tml#Error)                                                                    | A problem with its place, code and fix.                  |
| [`Sanitize`](https://pkg.go.dev/tuios.dev/tml#Sanitize)                                                                                                                     | Removes what must never reach a terminal.                |

The [README](https://github.com/Gaurav-Gosain/tuios/tree/main/tml#readme) lists every component, attribute, function, action and limit.

## Where it fits

- [loom](https://tuios.dev/docs/libraries/loom) draws TML documents into cells. It uses tml for the tree, the store, the bindings and the actions.
- [plot](https://tuios.dev/docs/libraries/plot) draws the chart components for loom.
- tuios uses tml and loom for `tuios tml show`, and checks each document with `tml.Check` before it opens a surface.
- tml imports no other library and no tuios package.

## Versions

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