# gizlang/terminal

the one owner of a terminal's bytes. Every program that writes to a terminal goes through it: - What the terminal can do (capsOf): its colours, whether its text is UTF-8, how it shows pictures (kitty's graphics, Sixel, or half blocks of text that every terminal draws), read from the environment once. - Lines that stay (a log, a progress line, a test report): `paint` gives text an SGR style when colours are on, `clipped` cuts text to a number of cells (gizlang/unicode width), ERASE_LINE clears a line drawn in place. - A line a person types (LineEditor): edited in place, with its history, on standard error. - A whole screen (Screen): raw input decoded into keys, pastes, mouse and focus (Keys), and a surface of cells (gizlang/graphics Cells) sent as the bytes of the cells that changed since the last frame, in one synchronized update; nothing at all when nothing changed. Pictures go as kitty images or Sixel, else as half blocks.

```gizlang
import * as Terminal from "gizlang/terminal";
```

## Types

### `Caps`

```gizlang
type Caps = { colors: i64; unicode: bool; images: string; cellW: i64; cellH: i64; }
```

A terminal's abilities: COLORS 0 (none), 16, 256 or 24 (true colour); UNICODE: its text is UTF-8; IMAGES "kitty",
"sixel" or "blocks"; the pixels of one cell (CELL_W x CELL_H), which a Screen learns from the terminal.

- `colors`: `i64`
- `unicode`: `bool`
- `images`: `string`
- `cellW`: `i64`
- `cellH`: `i64`

### `Key`

```gizlang
type Key = { kind: string; name: string; text: string; ctrl: bool; alt: bool; shift: bool; x: i64; y: i64; button: i64; press: bool; move: bool; }
```

One input of a terminal. KIND "key": NAME is the key as the DOM names it ("Enter", "ArrowUp", "a"), TEXT what it
types ("" for none); "text": TEXT typed at once (a run of characters, or what an input method composed); "paste":
TEXT pasted (bracketed); "mouse": BUTTON (0 main, 1 middle, 2 other, 64 wheel up, 65 wheel down) at cell (X, Y),
PRESS false on its release and MOVE for a motion; "focus": PRESS whether the terminal has it; "cell": a cell is X x Y
pixels; "resize": the terminal's size changed; "background": TEXT "dark" or "light", the terminal's background.

- `kind`: `string`
- `name`: `string`
- `text`: `string`
- `ctrl`: `bool`
- `alt`: `bool`
- `shift`: `bool`
- `x`: `i64`
- `y`: `i64`
- `button`: `i64`
- `press`: `bool`
- `move`: `bool`

### `Keys`

```gizlang
class Keys { pending: bytes = b""; pasting: bool = false; pasted: bytes = b""; constructor() {} feed(data: bytes): Vec<Key> { let b = this.pending + data; this.pending = b""; let out: Vec<Key> = []; let i = 0; let run = b""; const flush = (): void => { if (run.length> 0) { out.push(inputOf("text", run.lossy())); run = b""; } }; while (i <b.length) { if (this.pasting) { const end = b.indexOf(b"\x1b[201~", i); if (end <0) { this.pasted = this.pasted + b.slice(i, b.length); i = b.length; break; } this.pasted = this.pasted + b.slice(i, end); i = end + 6; this.pasting = false; out.push(inputOf("paste", this.pasted.lossy())); this.pasted = b""; continue; } const c = i64(b[i]); if (c === 27) { flush(); if (i + 1> = b.length) { out.push(key("Escape", "", false, false, false)); i + = 1; continue; } const n = i64(b[i + 1]); if (n === 91 || n === 79) { let j = i + 2; while (j <b.length && (i64(b[j]) <0x40 || i64(b[j])> 0x7e)) { j + = 1; } if (j> = b.length) { this.pending = b.slice(i, b.length); return out; } const params = b.slice(i + 2, j).lossy(); const final = i64(b[j]); i = j + 1; if (n === 79) { const k = ss3(final); if (k !== undefined) { out.push(k!); } continue; } if (params === "200" && final === 126) { this.pasting = true; continue; } const k = this.csi(params, final); if (k !== undefined) { out.push(k!); } continue; } if (n === 93) { let j = i + 2; while (j <b.length && b[j] !== 7u && !(b[j] === 27u && j + 1 <b.length && b[j + 1] === 92u)) { j + = 1; } if (j> = b.length || (b[j] === 27u && j + 1> = b.length)) { this.pending = b.slice(i, b.length); return out; } const k = osc(b.slice(i + 2, j).lossy()); if (k !== undefined) { out.push(k!); } i = b[j] === 7u ? j + 1: j + 2; continue; } const rest = this.feed(b.slice(i + 1, i + 2 + (n> = 0xc0 ? (n> = 0xf0 ? 3: n> = 0xe0 ? 2: 1): 0))); for (const r of rest) { let k = r; k.alt = true; if (k.kind === "text") { k = key(k.text, "", false, true, false); } out.push(k); } i + = 2 + (n> = 0xc0 ? (n> = 0xf0 ? 3: n> = 0xe0 ? 2: 1): 0); continue; } if (c === 13 || c === 10) { flush(); out.push(key("Enter", "", false, false, false)); i + = 1; continue; } if (c === 9) { flush(); out.push(key("Tab", "", false, false, false)); i + = 1; continue; } if (c === 127 || c === 8) { flush(); out.push(key("Backspace", "", false, false, false)); i + = 1; continue; } if (c === 0) { flush(); out.push(key(" ", "", true, false, false)); i + = 1; continue; } if (c <32) { flush(); out.push(key(fromCodePoints([c + 96]), "", true, false, false)); i + = 1; continue; } const size = c> = 0xf0 ? 4: c> = 0xe0 ? 3: c> = 0xc0 ? 2: 1; if (i + size> b.length) { flush(); this.pending = b.slice(i, b.length); return out; } run = run + b.slice(i, i + size); i + = size; } flush(); return out; } csi(params: string, final: i64): Option<Key> { if (params.startsWith("<") && (final === 77 || final === 109)) { const p = params.slice(1).split(";").map(s => parseInt(s) ?? 0); if (p.length <3) { return undefined; } const code = p[0]; let k = inputOf("mouse", ""); k.button = code> = 64 ? 64 + (code & 1): code & 3; k.x = p[1] - 1; k.y = p[2] - 1; k.press = final === 77; k.move = (code & 32) !== 0; k.shift = (code & 4) !== 0; k.alt = (code & 8) !== 0; k.ctrl = (code & 16) !== 0; return k; } if (final === 73 || final === 79) { let k = inputOf("focus", ""); k.press = final === 73; return k; } const p = params.split(";"); const number = parseInt(p[0].split(":")[0]) ?? 1; const bits = p.length> 1 ? (parseInt(p[1].split(":")[0]) ?? 1) - 1: 0; const shift = (bits & 1) !== 0; const alt = (bits & 2) !== 0; const ctrl = (bits & 4) !== 0; if (final === 116 && p.length === 3 && p[0] === "6") { let k = inputOf("cell", ""); k.y = parseInt(p[1]) ?? 20; k.x = parseInt(p[2]) ?? 10; return k; } if (final === 126) { for (const [n, name] of TILDE) { if (n === number) { return key(name, "", ctrl, alt, shift); } } return undefined; } if (final === 117) { const named = number === 13 ? "Enter": number === 9 ? "Tab": number === 27 ? "Escape": number === 127 ? "Backspace": ""; if (named !== "") { return key(named, "", ctrl, alt, shift); } if (number <32 || number> 0x10ffff) { return undefined; } const text = fromCodePoints([number]); return key(text, ctrl || alt ? "": text, ctrl, alt, shift); } if (final === 90) { return key("Tab", "", ctrl, alt, true); } const k = ss3(final); if (k === undefined) { return undefined; } let out = k!; out.ctrl = ctrl; out.alt = alt; out.shift = shift; return out; } }
```

The decoder of a terminal's input: bytes in (feed), inputs out. A sequence cut between two reads waits for the
rest; an escape alone at the end of a read is the Escape key, as a person types it alone.

- `pending`: `bytes`
- `pasting`: `bool`
- `pasted`: `bytes`

### `Screen`

```gizlang
class Screen { output: Stream; saved: bytes; caps: Caps; columns: i64 = 80; rows: i64 = 24; shown: Option<Cells> = undefined; shownPictures: Vec<string> = []; pen: string = ""; cursorShown: bool = false; errors: string = ""; open: bool = true; constructor() throws IoError { const output = sys.stdout(); this.output = output; const saved = sys.terminalState(0); this.saved = saved; this.caps = capsOf(1); sys.terminalRaw(0); output.write(utf8(ENTER)); try { const folder = sys.temporaryDir().temporaryPath(); sys.errorsTo(`${folder }/errors`); this.errors = folder; } catch (why: IoError) { this.errors = ""; } this.measure(); } measure(): void { const s = sys.terminalSize(1).valueOr({ columns: this.columns, rows: this.rows }); this.columns = s.columns; this.rows = s.rows; this.shown = undefined; this.shownPictures = []; this.pen = ""; } took(k: Key): void { if (k.kind === "cell" && k.x> 0 && k.y> 0) { this.caps.cellW = k.x; this.caps.cellH = k.y; this.shownPictures = []; } if (k.kind === "resize") { this.measure(); } } present(cells: Cells): void { if (!this.open) { return; } if (this.caps.images === "blocks") { for (const p of cells.pictures) { blocks(cells, p); } } let out = b""; if (this.shown === undefined || this.shown!.columns !== cells.columns || this.shown!.rows !== cells.rows) { out + = utf8("\x1b[0m\x1b[H\x1b[2J"); this.shown = new Cells(cells.columns, cells.rows); this.pen = ""; } let shown = this.shown!; const pictures = this.caps.images === "blocks" ? []: cells.pictures.map(p => pictureKey(p)); const repicture = pictures.join("|") !== this.shownPictures.join("|"); if (repicture && this.caps.images === "kitty" && this.shownPictures.length> 0) { out + = utf8("\x1b_Ga=d,d=a,q=2\x1b\\"); } let row = -1; let col = -1; for (let r = 0; r <cells.rows; r + = 1) { for (let c = 0; c <cells.columns; c + = 1) { const i = r * cells.columns + c; const t = cells.text[i]; if (t === shown.text[i] && cells.fg[i] === shown.fg[i] && cells.bg[i] === shown.bg[i] && cells.style[i] === shown.style[i]) { continue; } shown.text[i] = t; shown.fg[i] = cells.fg[i]; shown.bg[i] = cells.bg[i]; shown.style[i] = cells.style[i]; if (t === "") { continue; } if (r !== row || c !== col) { out + = utf8(`\x1b[${r + 1 }; ${ c + 1 }H`); } const pen = sgr(cells.fg[i], cells.bg[i], cells.style[i], cells.base, this.caps.colors); if (pen !== this.pen) { out + = utf8(pen); this.pen = pen; } out + = utf8(t); row = r; col = c + graphemeWidth(t); } } if (repicture) { for (let k = 0; k <cells.pictures.length && this.caps.images !== "blocks"; k + = 1) { const p = cells.pictures[k]; out + = utf8(`\x1b[${p.row + 1 }; ${ p.column + 1 }H`); out + = this.caps.images === "kitty" ? kitty(p, k + 1): sixel(p, this.caps.cellW, this.caps.cellH); } this.shownPictures = pictures; this.pen = ""; } const wanted = cells.cursor.length === 2; if (wanted) { out + = utf8(`\x1b[${cells.cursor[1] + 1 }; ${ cells.cursor[0] + 1 }H`); } if (wanted !== this.cursorShown) { out + = utf8(wanted ? "\x1b[?25h": "\x1b[?25l"); this.cursorShown = wanted; } if (out.length === 0) { return; } this.output.write(utf8("\x1b[?2026h") + out + utf8("\x1b[?2026l")).valueOr(0); } close(): void { if (!this.open) { return; } this.open = false; this.output.write(utf8(LEAVE)).valueOr(0); sys.terminalRestore(0, this.saved).valueOr(false); if (this.errors === "") { return; } sys.errorsTo("").valueOr(false); const held = sys.readFile(`${this.errors }/errors`).valueOr(b""); if (held.length> 0) { sys.stderr().valueOr(this.output).write(held).valueOr(0); } sys.removeTree(this.errors).valueOr(false); } }
```

The terminal as one screen of cells, its input read by `listen`: each frame (present) is sent as the cells that
changed since the last, in one synchronized update. `close` gives the terminal back as it was.

- `output`: `gizlang_system.Stream`
- `saved`: `bytes`
- `caps`: `gizlang_terminal.Caps`
- `columns`: `i64`
- `rows`: `i64`
- `shown`: `_gizlang_sdk_core.Option<Ref<gizlang_graphics.Cells>>` — The cells the terminal shows: what the next frame is compared with (none before the first, or after a resize).
- `shownPictures`: `Vec<string>`
- `pen`: `string` — The style the terminal writes in now ("" unknown), and whether its cursor shows.
- `cursorShown`: `bool`
- `errors`: `string` — The folder whose file `errors` holds what the program writes to stderr while the screen is up ("" when it goes to
the terminal).
- `open`: `bool`

### `LineEditor`

```gizlang
class LineEditor { history: Vec<string> = []; keys: Keys = new Keys(); fd: i64; pending: bytes = b""; constructor(fd: i64 = 2) { this.fd = fd; } read(label: string): Option<string> { const input = sys.stdin(); const err = this.fd === 1 ? sys.stdout(): sys.stderr(); const write = (text: string): void => { err.write(utf8(text)).valueOr(0); }; if (!sys.isTerminal(0) || !sys.isTerminal(this.fd)) { write(label); while (true) { const end = this.pending.indexOf(b"\n", 0); let line = b""; let last = false; if (end> = 0) { line = this.pending.slice(0, end); this.pending = this.pending.slice(end + 1, this.pending.length); } else { let chunk = b""; try { chunk = input.read(4096); } catch { chunk = b""; } if (chunk.length> 0) { this.pending = this.pending + chunk; continue; } if (this.pending.length === 0) { return undefined; } line = this.pending; this.pending = b""; last = true; } let text = ""; for (const k of new Keys().feed(line)) { if (k.kind === "text" || k.kind === "paste") { text + = k.text; } else if (k.name === "Tab") { text + = "\t"; } } if (!last || text !== "") { return text; } return undefined; } } let saved = b""; try { saved = sys.terminalState(0); sys.terminalRaw(0); } catch { return undefined; } write("\x1b[?2004h\x1b[>1u"); let line: Vec<string> = []; let at = 0; let back = this.history.length; let draft: Vec<string> = []; let shown = 0; const color = colored(this.fd); const draw = (): void => { const room = columns(this.fd)> 0 ? columns(this.fd): 80; let out = shown> 0 ? `\x1b[${shown }A`: ""; out + = `\r\x1b[J${paint(label, BOLD, color) }`; let row = 0; let col = width(label); let cursorRow = 0; let cursorCol = col; for (let k = 0; k <= line.length; k + = 1) { if (k === at) { cursorRow = row; cursorCol = col; } if (k === line.length) { break; } const g = line[k]; if (g === "\n") { out + = "\r\n  "; row + = 1; col = 2; continue; } const w = graphemeWidth(g); if (col + w> room) { out + = "\r\n"; row + = 1; col = 0; } out + = g; col + = w; } if (cursorCol> = room) { cursorRow + = 1; cursorCol = 0; } out + = "\r"; if (row> cursorRow) { out + = `\x1b[${row - cursorRow }A`; } if (cursorCol> 0) { out + = `\x1b[${cursorCol }C`; } write(out); shown = cursorRow; }; const insert = (text: string): void => { const parts = graphemes(text.replaceAll("\r\n", "\n").replaceAll("\r", "\n")); line = line.slice(0, at).concat(parts).concat(line.slice(at, line.length)); at + = parts.length; }; const word = (from: i64, step: i64): i64 => { let k = from; while (k + (step <0 ? -1: 0)> = 0 && k + (step <0 ? -1: 0) <line.length && line[k + (step <0 ? -1: 0)] === " ") { k + = step; } while (k + (step <0 ? -1: 0)> = 0 && k + (step <0 ? -1: 0) <line.length && line[k + (step <0 ? -1: 0)] !== " ") { k + = step; } return k; }; draw(); let given: Option<string> = undefined; let ended = false; while (!ended) { let got = b""; try { got = input.read(4096); } catch { got = b""; } if (got.length === 0) { ended = true; break; } for (const k of this.keys.feed(got)) { if (k.kind === "text") { insert(k.text); continue; } if (k.kind === "paste") { insert(k.text); continue; } if (k.kind !== "key") { continue; } const n = k.name; if (n === "Enter" && (k.alt || k.shift)) { insert("\n"); } else if (n === "Enter") { given = line.join(""); ended = true; break; } else if (k.ctrl && n === "d") { if (line.length === 0) { ended = true; break; } line.splice(at, 1); } else if (k.ctrl && n === "c") { line = []; at = 0; write("^C"); shown = 0; write("\r\n"); } else if (n === "Backspace" && (k.ctrl || k.alt)) { const w0 = word(at, -1); line.splice(w0, at - w0); at = w0; } else if (n === "Backspace") { if (at> 0) { line.splice(at - 1, 1); at - = 1; } } else if (n === "Delete") { if (at <line.length) { line.splice(at, 1); } } else if (k.ctrl && n === "w") { const w0 = word(at, -1); line.splice(w0, at - w0); at = w0; } else if (k.ctrl && n === "u") { line.splice(0, at); at = 0; } else if (k.ctrl && n === "k") { line.splice(at, line.length - at); } else if ((k.ctrl && n === "a") || n === "Home") { at = 0; } else if ((k.ctrl && n === "e") || n === "End") { at = line.length; } else if (n === "ArrowLeft" && (k.ctrl || k.alt)) { at = word(at, -1); } else if (n === "ArrowRight" && (k.ctrl || k.alt)) { at = word(at, 1); } else if ((n === "ArrowLeft" || (k.ctrl && n === "b")) && at> 0) { at - = 1; } else if ((n === "ArrowRight" || (k.ctrl && n === "f")) && at <line.length) { at + = 1; } else if (n === "ArrowUp" && back> 0) { if (back === this.history.length) { draft = line; } back - = 1; line = graphemes(this.history[back]); at = line.length; } else if (n === "ArrowDown" && back <this.history.length) { back + = 1; line = back === this.history.length ? draft: graphemes(this.history[back]); at = line.length; } else if (k.ctrl && n === "l") { write("\x1b[H\x1b[2J"); shown = 0; } else if (n === "Escape") { line = []; at = 0; } else if (!k.ctrl && !k.alt && n.length> 0 && width(n)> 0 && n !== "Tab") { insert(n); } } if (!ended) { draw(); } } at = line.length; draw(); write("\r\n\x1b[<u\x1b[?2004l"); sys.terminalRestore(0, saved).valueOr(false); if (given !== undefined && given! !== "" && (this.history.length === 0 || this.history[this.history.length - 1] !== given!)) { this.history.push(given!); } return given; } }
```

The line a person types after a label, the one way a program reads one (a REPL, a debugger, a chat). On a
terminal it is edited in place on descriptor FD: characters by grapheme, the cursor's moves (arrows, Home, End,
Ctrl+A, Ctrl+E, a word with Ctrl or Alt), deletions (Backspace, Delete, Ctrl+W, Ctrl+U, Ctrl+K), the history (Up,
Down), pastes whole (bracketed), Alt+Enter or Shift+Enter for a new line, Enter to give it; Ctrl+C drops the line,
Ctrl+D on an empty line or the end of input ends. From a pipe or a file the label is written as it is and each line
of input is given, the escapes of a terminal's keys left out.

- `history`: `Vec<string>`
- `keys`: `Ref<gizlang_terminal.Keys>`
- `fd`: `i64`
- `pending`: `bytes`

## Functions

### `capsOf`

```gizlang
function capsOf(fd: i64): Caps
```

The abilities of the terminal on descriptor FD, from the environment (TERM, COLORTERM, TERM_PROGRAM, NO_COLOR,
the locale; GIZLANG_IMAGES names the picture protocol): none when FD is no terminal or TERM is dumb.

Effects: fail, io, alloc.

### `colored`

```gizlang
function colored(fd: i64): bool
```

Whether text written to descriptor FD takes colours: it is a terminal, TERM is not dumb and NO_COLOR is not set.

Effects: fail, io, alloc.

### `paint`

```gizlang
function paint(text: string, code: string, on: bool): string
```

TEXT in the SGR style CODE (BOLD, "1;31", ...) when ON, else as it is.

Effects: fail, alloc.

### `columns`

```gizlang
function columns(fd: i64): i64
```

The columns of the terminal on FD, or 0 when FD is no terminal.

Effects: fail, io, alloc.

### `clipped`

```gizlang
function clipped(text: string, cells: i64, utf: bool): string
```

TEXT in at most CELLS cells: its start and its end around an ellipsis ("…", or "..." without UTF-8) when it is
wider.

Effects: fail, alloc.

### `inputOf`

```gizlang
function inputOf(kind: string, text: string): Key
```

An input of KIND (Key) with TEXT and no key.

### `constructor`

```gizlang
constructor()
```

A decoder with nothing read yet.

Effects: fail, write, alloc.

### `constructor`

```gizlang
constructor() throws IoError
```

Takes the terminal: raw input, the other screen, the cursor hidden; throws when stdin is not a terminal.

Effects: fail, read, write, io, alloc.

### `listen`

```gizlang
function listen(into: Task.Channel<Key>, woken: Task.Cell<i64>): void
```

Reads the terminal's input until it ends, on a thread of its own: each input goes to INTO and bumps WOKEN, which
the host waits on; the end of input is a "close". The terminal's resizes (SIGWINCH) come the same way, as "resize".

Effects: fail, read, write, io, alloc.

### `picture`

```gizlang
function picture(bitmap: Bitmap, fd: i64, most: i64 = 64): bytes
```

BITMAP as lines that stay on the terminal on FD (a picture a command made, under its line): at most MOST cells
wide and as wide as the terminal, as the terminal draws pictures (kitty's graphics, Sixel, else half blocks in
colour); nothing when FD takes no colours.

Effects: fail, read, write, io, alloc.

### `constructor`

```gizlang
constructor(fd: i64 = 2)
```

An editor that reads lines from the terminal at descriptor FD (stderr by default).

Effects: fail, read, write, alloc.

## Methods

### `Keys.feed`

```gizlang
feed(data: bytes): Vec<Key>
```

The inputs of DATA, after what an earlier read left.

Effects: fail, read, write, alloc.

### `Keys.csi`

```gizlang
csi(params: string, final: i64): Option<Key>
```

The input of `CSI PARAMS FINAL`.

Effects: fail, alloc.

### `Screen.measure`

```gizlang
measure(): void
```

Reads the terminal's size again: the next frame draws every cell.

Effects: fail, read, write, io, alloc.

### `Screen.took`

```gizlang
took(k: Key): void
```

Takes what input K tells the screen itself: a cell's pixels, which the pictures are drawn at.

Effects: fail, read, write, io, alloc.

### `Screen.present`

```gizlang
present(cells: Cells): void
```

Sends what CELLS show and the last frame did not; nothing when nothing changed.

Effects: fail, read, write, io, alloc.

### `Screen.close`

```gizlang
close(): void
```

Gives the terminal back as it was: modes off, the main screen, its own line discipline.

Effects: fail, read, write, io, alloc.

### `LineEditor.read`

```gizlang
read(label: string): Option<string>
```

The next line given after LABEL, or none at the end.

Effects: fail, read, write, io, alloc.

## Constants

### `BOLD`

```gizlang
const BOLD = "1"
```

The SGR code of the paint bold.

### `DIM`

```gizlang
const DIM = "2"
```

The SGR code of the paint dim.

### `RED`

```gizlang
const RED = "31"
```

The SGR code of the paint red.

### `GREEN`

```gizlang
const GREEN = "32"
```

The SGR code of the paint green.

### `YELLOW`

```gizlang
const YELLOW = "33"
```

The SGR code of the paint yellow.

### `CYAN`

```gizlang
const CYAN = "36"
```

The SGR code of the paint cyan.

### `ERASE_LINE`

```gizlang
const ERASE_LINE = "\r\x1b[2K"
```

Clears the line the cursor is on and goes to its start: a line drawn in place goes before another is written.

### `NO_WRAP`

```gizlang
const NO_WRAP = "\x1b[?7l"
```

Turns the terminal's wrap off and on again: a line drawn in place with it off never takes two rows.

### `WRAP`

```gizlang
const WRAP = "\x1b[?7h"
```

Turns the wrap on again (NO_WRAP).

