# terminal

A terminal emulator screen: what xterm.js is to a web app, written for Mote
from nothing (`runtime/page/terminal.mote`, part `TM`). It is a screen,
not a shell: the page gives it bytes to show and is handed the bytes the
user types. Gallery: `examples/kit/terminal.mote`. Test:
`tests/kit_terminal.real.mjs`.

    terminal output=out input=typed change=sized height=420

## How a page drives it

There is no object to call. The page keeps a string and appends to it; the
terminal is that string's view.

    state out = ""
    action typed(data: string)     what the user typed, as a terminal sends it
      out += data                  (here: echoed straight back)
    terminal output=out input=typed

- **`output` grows: only the new part is written.** When the new value starts
  with the old one, the terminal writes the suffix.
- **Any other value is a reset.** The screen, the scrollback and every mode
  are cleared, then the whole value is written. The empty string therefore
  clears. This is also how to keep the string from growing without end: cut
  it from the front (at a line break, so no escape sequence is cut in half)
  and the terminal starts again from what is left. The view jumps when you
  do, so do it rarely and in large steps.
- **`ESC c`** (RIS) inside the stream is the same full reset without touching
  the string.
- **A line feed only goes down**, as on a real terminal: write `\r\n`, or
  send `ESC [ 20 h` once to make every LF return to column one as well.
- Mote strings know `\r`, `\n` and `\t` but not `\x1b` or `\b`: write
  `String.fromCharCode(27)` (the gallery's `csi(s)` and `sgr(code, s)` helpers
  are three lines). Inside a backtick template `\r` is not an escape at all:
  join with `+ "\r\n"` instead.

## Attributes

| attribute | type | meaning |
|---|---|---|
| `output` | string | The bytes to show. Append to it (see above). |
| `cols`, `rows` | number | Written by the page: the grid is that size; the element takes the grid's size unless styled otherwise, scrolls sideways if it is narrower and leaves a margin if it is larger. Left out (or 0): the grid is fitted to the element and its font, and fitted again when either changes. If the value is assignable state, the fitted size is written back to it. |
| `scrollback` | number | Lines kept above the screen. Default 1000; 0 keeps none. |
| `cursor` | bool | Whether the cursor blinks. Default true. |

Size it with styles (`width`, `height`, `flex`, `resize=both`). With no height
the element is as tall as its rows (24 unless `rows` says otherwise). Its own
look has no weight, so anything the page writes wins: `font-size` (13px),
`font-family` (the system's monospace), `line-height` (1.2, the cell's
height), `padding`, `border`, `border-radius`, `background` (`--bg`), `color`
(`--fg`). The sixteen colours come in a dark and a light set, chosen by how
dark the background really is, so they follow the page's scheme and a
terminal given `background=#000000` on a light page is still right.

## Events

| event | `node.value` | when |
|---|---|---|
| `input` | the bytes | A key, pasted text, a mouse report, or the answer to a question the program asked (DA, DSR). `input=typed` with `action typed(data: string)`. |
| `change` | `"COLSxROWS"` | The fitted grid has a new size (also once at the start). Not raised when both `cols` and `rows` are fixed. |

`node.title` is set by OSC 0 / OSC 2 (no event; no tooltip over the screen).

### What keys send

| key | bytes |
|---|---|
| text, an input method's composition, the phone's keyboard | as typed (UTF-16, as JavaScript has it) |
| Enter, Tab, Escape, Backspace | `\r` (`\r\n` in newline mode), `\t`, `ESC`, `\x7f` (Ctrl+Backspace `\b`) |
| arrows, Home, End | `ESC [ A B C D H F`; `ESC O …` in application-cursor mode (DECCKM) |
| Insert Delete PageUp PageDown | `ESC [ 2~ 3~ 5~ 6~` |
| F1 to F4, F5 to F12 | `ESC O P Q R S`, `ESC [ 15~ 17~ 18~ 19~ 20~ 21~ 23~ 24~` |
| Shift / Alt / Ctrl with those | the xterm form: `ESC [ 1 ; m A`, `ESC [ 3 ; m ~` (m = 1 + Shift 1 + Alt 2 + Ctrl 4); Shift+Tab `ESC [ Z` |
| Ctrl+letter, Ctrl+`[ \ ] ^ _`, Ctrl+Space | the control code (`\x01`…`\x1f`, `\0`) |
| Alt+key | `ESC` then the key. On a Mac, Option with a letter or digit is Alt, unless the layout makes another ASCII character of it (`@` on a German keyboard), which is typed. |
| paste | the text with newlines as `\r`; between `ESC [ 200~` and `ESC [ 201~` when the program asked (2004) |
| focus in / out | `ESC [ I` / `ESC [ O` when asked (1004) |
| mouse, when asked | 1000 (press, release), 1002 (drag), 1003 (all motion), wheel as buttons 64 / 65; SGR form with 1006, else the X10 bytes. Shift takes the mouse back for selecting. |

Kept for the reader, not sent: Cmd+C (Ctrl+Shift+C, or Ctrl+C with a
selection, off the Mac) copies; Cmd+V (Ctrl+V / Ctrl+Shift+V off the Mac)
pastes; Cmd+A selects everything; Shift+PageUp / PageDown scroll. On the
alternate screen the wheel sends arrow keys (so `less` and `vim` scroll)
unless the program takes the mouse or turns that off (`ESC [ ? 1007 l`).

## What it draws

A canvas, in device pixels. Text is selected with the terminal's own
selection: drag, double click for a word, triple for a line, Shift+click to
extend, dragging past an edge scrolls. Copied text has rows joined by
newlines, trailing blanks trimmed and wrapped lines joined into one. Box
drawing (U+2500–257F), blocks (U+2580–259F), braille (U+2800–28FF) and the
powerline arrows (U+E0B0–E0B3) are drawn by the terminal itself, so they
meet without seams at any size. Wide characters take exactly two cells;
anything not Latin is placed cell by cell, so a glyph from a fallback font
moves nothing after it. Only rows that changed are redrawn; writes are queued
and parsed for at most about 8 ms a frame, so a megabyte arriving at once
does not stop the page. Scrollback is the browser's own scrolling (wheel,
touch, scrollbar); new output keeps the view at the end unless the reader
has scrolled up. The cursor is a block when focused and an outline when not;
a click focuses a hidden field that takes keys, composition and the phone's
keyboard, and the element shows a focus ring.

## Sequences

| group | supported |
|---|---|
| C0 | BEL (ignored), BS, HT, LF VT FF, CR, SO / SI (G1 / G0), ESC, CAN / SUB (abandon a sequence) |
| ESC | `7` `8` DECSC / DECRC · `D` IND · `E` NEL · `M` RI · `H` HTS · `c` RIS · `Z` DECID · `( 0` `( B` `) 0` `) B` DEC line drawing · `# 8` DECALN · `=` `>` accepted |
| cursor | CUU `A` · CUD `B` `e` · CUF `C` `a` · CUB `D` · CNL `E` · CPL `F` · CHA `G` `` ` `` · CUP `H` · HVP `f` · VPA `d` · CHT `I` · CBT `Z` · save / restore `s` `u` |
| erase | ED `J` 0 1 2 3 (3: the scrollback) · EL `K` 0 1 2 · ECH `X`; erased cells take the current background |
| edit | ICH `@` · DCH `P` · IL `L` · DL `M` · REP `b` · insert mode `4 h` |
| scroll | SU `S` · SD `T` · DECSTBM `r` (top;bottom region) |
| tabs | stops every 8 · HTS · TBC `g` 0 3 |
| SGR `m` | 0 · 1 bold · 2 dim · 3 italic · 4 underline (`4:0`–`4:5`: none, single, double, curly, dotted, dashed) · 21 double · 5 6 blink · 7 inverse · 8 hidden · 9 strike · 53 overline · 22 23 24 25 27 28 29 55 · 30–37 40–47 90–97 100–107 · 39 49 · `38;5;n` `48;5;n` · `38;2;r;g;b` `48;2;r;g;b` · the colon forms `38:5:n` `38:2:r:g:b` `38:2::r:g:b` · 58 / 59 read and ignored |
| modes `? … h / l` | 1 DECCKM · 5 reverse video · 6 DECOM · 7 DECAWM · 12 cursor blink · 25 DECTCEM · 47, 1047, 1049 alternate screen (1049 saves the cursor) · 1048 · 1000 1002 1003 1006 mouse · 1004 focus · 1007 wheel as arrows · 2004 bracketed paste |
| modes `… h / l` | 4 insert · 20 newline |
| other CSI | DECSCUSR `SP q` (block, underline, bar; blinking or steady) · DECSTR `! p` · DECRQM `$ p` |
| answers (as `input`) | DA `c` → `ESC [ ? 1 ; 2 c` · DA2 `> c` → `ESC [ > 0 ; 276 ; 0 c` · DSR `5 n` → `ESC [ 0 n` · `6 n` → `ESC [ row ; col R` · `18 t` → `ESC [ 8 ; rows ; cols t` |
| OSC | 0, 2 title → `node.title` · 8 hyperlinks: `http`, `https`, `mailto`, `ftp` only; shown dotted-underlined, the address appears on hover, a click opens it in a new tab |
| strings | DCS, SOS, PM, APC are read to their end and dropped |
| text | deferred wrap at the right margin; wide (CJK, emoji) cells; combining marks, variation selectors, ZWJ sequences and flags joined into one cell; lines re-wrapped when the width changes |

## Not supported

- Images: sixel, the iTerm2 and kitty protocols (their DCS / OSC / APC are
  skipped safely).
- OSC 52 (clipboard), OSC 4 / 10 / 11 (palette and colour queries), OSC 7.
  The palette is the terminal's; a program cannot change it.
- Underline colour (58), left / right margins (DECSLRM), rectangular area
  operations, DECCOLM, double-size lines, the kitty keyboard protocol,
  synchronized output (2026: accepted, not acted on), 8-bit C1 controls
  other than ST.
- Mouse encodings 1005 and 1015. Selecting text by touch (a tap focuses and
  a drag scrolls).
- Character widths for scripts that shape (Arabic joining, Indic
  conjuncts): each code point is one cell or a mark, as in most terminals.
- A screen reader hears the input field only: the canvas is not mirrored
  into text.
- A bell. Search. Plain URLs are not found in the text; only OSC 8 links.

## Reading the screen from script

For tests (and a page's own script), on the element:

    node.hkScreen()            the rows as strings, trailing blanks trimmed
    node.hkScrollback()        the lines above, oldest first
    node.hkCell(row, col)      {ch, fg, bg, bold, dim, italic, underline, blink, inverse,
                                hidden, strike, overline, wide, tail, wrapped, link}
                               fg / bg: "default", a palette index, or "#rrggbb"
    node.hkState()             {cols, rows, x, y, wrap, alt, visible, shape, blink, scrollback,
                                top, bottom, appCursor, paste, mouse, stuck, focused, cw, ch}
    node.hkWrite(s)            write now, past `output` (hkFeed(s): queued, as output is)
    node.hkSelect(l0, c0, l1, c1) / hkSelection()   select by line and column; the text
    node.hkReset() · node.hkIdle()

## Wiring a shell

Mote has `net` (fetch) but no sockets yet, so a page cannot hold a pty on a
server today. When it can, this is all the wiring there is to it (an
illustration: `socket` does not exist):

    state out = ""
    state size = "80x24"
    // on each message from the socket:   out += message
    action typed(data: string)
      socket.send(data)                  keys, pastes and the terminal's replies
    action sized(s: string)
      socket.send(resizeMessage(s))      "COLSxROWS", for the server's TIOCSWINSZ
    terminal output=out input=typed change=sized height=480

What works now is the same shape with the program in the page. A whole,
if small, shell:

    state out = "$ "
    state line = ""
    action typed(data: string)
      for ch in Array.from(data)
        if ch == "\r"
          out += "\r\n" + (line == "" ? "" : "you said: " + line + "\r\n") + "$ "
          line = ""
        else if ch.charCodeAt(0) == 127
          if line != ""
            line = line.slice(0, -1)
            out += String.fromCharCode(8) + " " + String.fromCharCode(8)
        else if ch.charCodeAt(0) >= 32
          line += ch
          out += ch
    terminal output=out input=typed height=300

`examples/kit/terminal.mote` grows that into line editing with the arrow
keys, history, completion, colours, a progress bar redrawn with `\r`, and a
full-screen editor on the alternate screen.
