Files
sakurac/docs/tui.md
T
2026-10-28 22:13:49 -05:00

44 KiB
Raw Blame History

Plan: terminal interfaces

Written 2026-10-13, and brought up to date 2026-10-20 for what std has gained since: poll's timeout, Windows, threads, strview::chars, std::swar, signal handlers held as functions, and result<void, E>. This is a proposal. std is yours, so the decisions at the end are yours to make. Nothing is built yet.

Comes after the ffi plan, now built: std::sys is system, and @foreign and @link are extern sections.

Built in the rebuild alone (roadmap.md, decision 1). Where this plan says both compilers, C's half is left out. What was measured in C stays as measured.

What it is: a library for writing to a terminal:

  • color and style: text in sixteen, 256 or 16 million colors, bold, italic, underlined and the rest, written only where the output shows them;
  • the cursor: moving it, saving and restoring it, hiding it, and changing its shape, and clearing the screen;
  • box drawing: boxes and lines in light, heavy, double or rounded strokes, which join where they meet;
  • full-screen programs: raw mode, the alternate screen, keys, the mouse, pasting and resizing, and a canvas the program draws a frame on, of which only what changed is written.

Its users:

  • the logging plan (logging.md), whose levels are colored on a terminal. Its sys::is_terminal is this plan's;
  • std::args (the README's "Arguments"), whose help is written in columns padded by bytes. It could be wrapped to the terminal's width and padded by width_of. A program's own --no-color would give its painters abilities of its choosing;
  • std::testing, which could color what passed and failed and keep one line of progress;
  • the compilers' notes, which could color their places and underlines;
  • the build tool's progress;
  • full-screen programs, such as a profile viewer, a debugger's front end, or a program that picks from a list.

Probed: in the scratchpad on 2026-10-13 (tuiprobe/), and again on 2026-10-20 against today's std (plans/tui/). A small driver ran the probe under a pseudo-terminal of 24×80, resized it, and typed into it. The probe was built by both compilers and run as an executable and in each VM, and all four gave the same results both times:

  • TCGETS, made through sys::syscall, worked on the terminal and gave -25 (ENOTTY) on a pipe;
  • TIOCGWINSZ gave 24×80, and 40×120 once the driver resized it;
  • raw mode was set through TCSETS, as cfmakeraw sets it. The mode put back afterward matched the saved one byte for byte;
  • sys::poll with a timeout, std's own now, was ended by the resize with -4. The handler given to sys::handle(signal::resized, ...), a closure counting into a local, had run by then;
  • an up arrow arrived as one read of ESC [ A. A lone Escape was told apart from the start of a sequence by 30 ms of quiet;
  • sys::raise(signal::suspend) stopped the program, which went on from there once it was continued (2026-10-20);
  • bold red, 256-color and 24-bit color, hiding and moving the cursor, and a rounded box with ┬, ┼ and ┴ were all written from literals, with \x1b and UTF-8 text, and reached the terminal as written (2026-10-13). No terminal showed them, so how they look wasn't probed;
  • the sketches under "Using it", over stubs of the API, checked and ran in both compilers (2026-10-20), once union fields were pub and attribute was renamed effect (see "Found along the way").

Nothing was probed on Windows.

Measured on 2026-10-20: every program is checked with all of std, whatever it imports, and std is 40,200 lines now. The processor was held at 2.1 GHz, on battery, so the times are slower than 2026-10-13's, whose clock wasn't noted, and the two don't compare. Each is the best of 15 runs or more, interleaved, on one core.

  • A one-line program takes about 93 ms to check in the rebuild and 165 ms in C.
  • std/yaml's 4,498 lines cost 12 ms of that in the rebuild and 24 ms in C, and std/time's and std/thread's 1,965 lines 5 and 13 ms. That's about 2.6 ms per 1,000 lines in the rebuild, and 5 to 7 in C.
  • So the 2,500 or so lines this plan adds to std would add about 6.5 ms to checking every program in the rebuild, and 13 to 17 ms in C, at that clock: 7% of a one-line program's check in the rebuild, and 8 to 10% in C.

What's there now

  • Writers: io::output() writes at line breaks, io::error_output() writes at once, and io::writer_of buffers anything writable. A write gives result<void, io_error>. print and println hold the standard output for each call, so two threads' lines never mix, and io::output_locked() holds it across several.
  • Text: literals take \x1b and UTF-8, and strview and string are bytes.
    • strview::chars() decodes UTF-8 lazily into code points, giving U+FFFD for each byte that begins none. serial::is_utf8 checks text, and serial::utf8_length measures a sequence.
    • index_of, find_any and is_ascii go eight bytes at a time, and std::swar gives the words themselves, for passing over runs of plain ASCII.
    • Nothing knows how wide a character is.
  • std::sys, on Linux and, since 2026-10-19, on Windows:
    • it reads and writes handles;
    • poll(handles, ready, wait) waits on several handles for at most wait milliseconds, or forever where it's -1, and gives 0 where the wait ran out. On Windows it peeks pipes, so a console always reads as ready;
    • it handles signals, resized (SIGWINCH) among them. handle takes any callable, which it keeps as a function<def(signal): void>, the type sys::handler. A handler runs at a safe point, in the thread the program began with, and ends the wait it interrupts. watch and watched note a signal with no handler, and the waits it interrupts go on. raise sends a signal to the program itself;
    • it reads the environment, through sys::environment() and process::variable.
  • Nothing knows the terminal on Linux: whether a handle is one, its size, or its mode. There's no ioctl, though sys::syscall reaches it, as the probe did.
  • On Windows, std::sys asks GetConsoleMode whether a handle is a console, but only for itself. It reads and writes a console as UTF-16, through ReadConsoleW and WriteConsoleW, so UTF-8 shows whatever the code page. Nothing sets a console's mode, so a sequence written reaches it as text unless its virtual terminal processing is on already. The console's Ctrl-C, Ctrl-Break and closing are noted as interrupt, quit and hangup, no resized ever comes, and raise(suspend) gives unsupported.
  • Nothing runs as the program stops, besides close where a scope ends. exit and a fault from any thread, abort and a failed contract end in exit_group, or ExitProcess on Windows, through the runtime in runtime/start.sakura or through the VM.
  • flags32<T> is a set of flags named by an enum, which fits a style's effects.
  • std::time's duration fits a wait for input.
  • function<S> holds any callable of a signature, and owns it. It's moved, never copied.

What it needs

  1. Colors and styles:
    • the sixteen named colors, the 256 indexed ones, and 24-bit colors;
    • bold, dim, italic, underline, blink, reverse, hidden and strikethrough;
    • colors brought down to what the terminal shows, and nothing written where the output isn't a terminal or the user asked for no color.
  2. The cursor: moved to a place or by an amount, saved and restored, hidden and shown, and given a shape.
  3. The screen:
    • clearing it, a line, or the rest of either;
    • the alternate screen;
    • a scrolling region;
    • the window's title.
  4. Box drawing:
    • light, heavy, double and rounded strokes;
    • lines that meet joined into ├, ┬ and ┼;
    • boxes in a full-screen frame, and in ordinary output, as a table printed at the end of a build.
  5. The terminal itself:
    • whether a handle is one, and its size;
    • raw mode, and putting back the mode it was in;
    • resizing, and suspending with Ctrl-Z and resuming.
  6. Input:
    • keys, with Shift, Alt and Ctrl;
    • text, the mouse, pasting and focus;
    • reading with a timeout.
  7. A canvas the program draws a whole frame on, of which only the cells that changed are written.
  8. The width of text in columns, so that 中 takes two and an accent joining a letter none.
  9. Tests without a terminal, with one where it matters.
  10. Portable above std::sys, which has Windows now. Its console takes the same sequences once its virtual terminal processing is on. Every operation std::sys gains must exist there too, since std is checked whole for an executable for Windows (decision 11).

How it fits the rules

  • A terminal is owning. Closing it, on any way out of its scope, puts back what it changed:

    • the mode, and the screen;
    • the cursor;
    • mouse and paste reporting;
    • what the program did with resized.

    Decision 5 is what happens when the program stops some other way.

  • A painter borrows or owns its stream, as io::writer_of's writer does, so painter_of(&mut text) writes to a string and closes nothing.

  • Colors, styles, keys, events and cells are plain data. They copy freely and are equatable. A maybe has no ==, so style::equals compares its colors itself. A pasted text views the terminal's buffer, and is good until the next event is read, as a dir_entry's name is good until the next entry.

  • Errors are values. Anything that can fail gives result<T, io_error>, or result<void, io_error> where only whether it failed comes back. io_error gains not_a_terminal, for ENOTTY, which error_of gives as other today.

  • Everything is written through writable, so tests read what a painter wrote from a string.

  • Signals stay the program's:

    • in raw mode, Ctrl-C and Ctrl-Z are keys, so the program decides what they do;
    • while a terminal is open, it handles resized, and the program reads event::resized. On close, what the program did with resized comes back: its handler, or ignoring it, watching for it, or the default. A handler is a function, moved and never copied, so std::sys gains a way to take it and give it back.
  • Interpolation formats a value by its fields, so $"{style}" can't write a sequence. paint gives a string to interpolate instead.

  • What's shared is made on first use, as io::output() is: term::output() and term::error_output(), the standard streams' painters.

    • Each paints term::standard, a stream writing through io::output() or io::error_output() at each write, so painted text keeps its order with println's. It can't hold a &mut writer<console>, since a module's variable needs a zero value and a reference has none (probed in both compilers).
    • As io::output() doesn't, it takes no lock. A thread painting several pieces holds io::output_locked() around them.

Layers

std::sys gains

Operation Does
is_terminal(handle: fd): bool Whether the handle is a terminal, through TCGETS, and on Windows GetConsoleMode, which std::sys asks already for itself. The logging plan's. Probed on Linux
terminal_size(handle: fd, columns: &mut u16, rows: &mut u16): i32 Its size, through TIOCGWINSZ, and on Windows GetConsoleScreenBufferInfo's window. Probed on Linux
terminal_mode The mode a terminal is in, as the system keeps it: 36 bytes on Linux, and the input's and output's modes on Windows, which nothing above reads
get_mode(handle: fd, into: &mut terminal_mode): i32 Reads it, through TCGETS, or GetConsoleMode. Probed on Linux
set_mode(handle: fd, mode: &terminal_mode): i32 Sets it, through TCSETS, or SetConsoleMode. Probed on Linux
terminal_mode::make_raw(&mut this): void Raw: no echo, no lines, no signals from keys, and every byte as it comes, with virtual terminal processing and input on Windows. Probed on Linux, as cfmakeraw sets it
take_handling(which: signal): handling, give_handling(which: signal, back: handling): i32 What the program does with a signal, taken so that a library can handle it for a while and give it back: the default, ignoring it, watching for it, or its handler, moved out
restore_at_stop(...), forget_at_stop() Decision 5's record, which the runtime and the VMs keep
  • poll's timeout is there already, in milliseconds, so next turns its duration into them. The plan had it gain one in nanoseconds.
  • On Linux: ioctl is 16 on x86-64. Its requests are TCGETS 0x5401, TCSETS 0x5402 and TIOCGWINSZ 0x5413. They differ on a few processors, so they go in linux_x86_64.sakura, beside the other calls' numbers.
  • io_error::not_a_terminal is what error_of gives for -25.
  • On Windows (decision 11): SetConsoleMode, with ENABLE_VIRTUAL_TERMINAL_PROCESSING on the output, and for raw mode ENABLE_VIRTUAL_TERMINAL_INPUT on the input, without line input, echo or processed input. Windows sends no resized, so the terminal reads the size again each time next returns, or reads ReadConsoleInput's window events. poll peeks pipes, so waiting for a console's input needs a wait on the console's own handle. None of it is probed.

std gains nothing now

  • decode_utf8 isn't needed: strview::chars() decodes, and the canvas writes each character's UTF-8 into its cell itself.
  • The input decoder keeps a sequence cut short at the end of a read for the next one. It tells one from a wrong sequence by its first byte, which neither chars nor serial::utf8_length does.

std::term (decision 1)

std/term/
  style.sakura      color, ansi, effect, style
  abilities.sakura  color_depth, abilities, abilities_of
  painter.sakura    painter, standard, output, error_output, paint, and the cursor and screen
  boxes.sakura      line_style, and the glyph each meeting of lines takes
  widths.sakura     width_of, over a table tools/widths.sakura writes
  canvas.sakura     size, rect, cell, canvas
  input.sakura      event, key, key_code, modifier, mouse, and the decoder
  terminal.sakura   terminal, settings, show, next, suspend

Styles:

#! One of the sixteen colors every color terminal has, which its theme decides.
pub enum ansi: u8 {
  black, red, green, yellow, blue, magenta, cyan, white,
  bright_black, bright_red, bright_green, bright_yellow,
  bright_blue, bright_magenta, bright_cyan, bright_white,
}

#! A color of text, or of what's behind it.
pub union color : equatable {
  pub var ansi:    ansi;   #! One of the sixteen.
  pub var indexed: u8;     #! One of 256: the sixteen, a 6×6×6 cube, and 24 grays.
  pub var rgb:     u8[3];  #! Any, as red, green and blue.
}

pub val color::red := color{ ansi = ansi::red };   # and the other fifteen
pub def color::hex(value: u32): color;         # color::hex(0xFF8800)

#! What text looks like besides its colors.
pub enum effect: u32 {
  bold = 1, dim = 2, italic = 4, underline = 8,
  blink = 16, reverse = 32, hidden = 64, strike = 128,
}

#! How text is drawn. A color that's `nothing` is the terminal's own.
pub struct style : equatable {
  pub var fg:      maybe<color>;
  pub var bg:      maybe<color>;
  pub var effects: flags32<effect>;
}

What a stream shows (decision 3):

#! How many colors a stream shows.
pub enum color_depth: u8 { none, basic, indexed, full }

#! What a stream shows of what a painter writes.
pub struct abilities : equatable {
  pub var colors:   color_depth; #! How many colors, if any.
  pub var controls: bool;        #! Whether cursor moves, clearing and modes are written.
}

#! What a handle shows, from whether it's a terminal and from the environment.
pub def abilities_of(handle: sys::fd, environment: span<strview> = sys::environment()): abilities;

Painting, in ordinary output (decision 4):

#! Writes text in styles to any stream, and moves the cursor, writing only what the
#! stream shows. Colors are brought down to its depth, and where it shows none, only
#! the text is written. A style's sequence is written only where the style changes.
pub struct painter<W> : owning, writable, flushable where W: writable { ... }

#! The standard output or error, written through the writer `std::io` shares for it.
pub struct standard : writable { ... }

pub def painter_of<W>(sink: W, shows: abilities): painter<W>;
pub def output(): &mut painter<standard>;        # the standard output's
pub def error_output(): &mut painter<standard>;  # the standard error's
pub val painter<W>::shows: abilities;

pub def painter<W>::write(&mut this, text: strview): result<void, io_error>;               # in the style set
pub def painter<W>::write(&mut this, text: strview, with: style): result<void, io_error>;  # in a style, then back
pub def painter<W>::set(&mut this, with: style): void;
pub def painter<W>::reset(&mut this): void;

#! Text in a style, as a string to interpolate, for a stream showing what `shows` says.
pub def paint(text: strview, with: style, shows: abilities = output().shows): string;

The cursor and the screen, each written only where controls holds:

Method Writes
move_to(column: i32, row: i32) CSI row;col H, from 0 here and from 1 there (decision 10)
move_by(columns: i32, rows: i32) CSI n A, B, C and D
to_column(column: i32) CSI n G
save_cursor(), restore_cursor() ESC 7 and ESC 8, which more terminals take than CSI s
show_cursor(shown: bool) CSI ?25h or l
cursor_shape(shape: cursor_shape) CSI n SP q: block, underline or bar, blinking or steady
clear(what: clearing) The screen, its rest, the line or its rest: CSI 2J, CSI J, CSI 2K or CSI K
scroll_region(top: i32, bottom: i32), scroll(rows: i32) CSI t;b r, and CSI n S or T
title(text: strview) OSC 2;text BEL

The terminal:

#! What a terminal is set to while it's open.
pub struct settings {
  pub var alternate := true;              #! Draw on the alternate screen, leaving the shell's as it was.
  pub var mouse     := mouse_mode::none;  #! none, buttons, drags, or every move.
  pub var paste     := true;              #! Report pasted text as one event, not as keys.
  pub var focus     := false;             #! Report the window gaining and losing focus.
  pub var escape    := milliseconds(50);  #! How long a lone Escape waits for a sequence.
}

#! The terminal the program runs in, in raw mode. Closing it puts back everything it
#! changed.
pub struct terminal : owning { ... }

pub def terminal::open(with: settings = settings{}): result<terminal, io_error>;  # not_a_terminal through a pipe
pub val terminal::size: size;
pub val terminal::out: &mut painter<...>;    # for drawing without a canvas
pub def terminal::show(&mut this, frame: &canvas): result<void, io_error>;
pub def terminal::next(&mut this, wait: maybe<duration> = nothing{}): result<maybe<event>, io_error>;
pub def terminal::suspend(&mut this): void;  # for Ctrl-Z: put back, stop, and on resuming, take again

Input (decision 6):

pub union event {
  pub var key:     key;      #! A key, with the modifiers held.
  pub var mouse:   mouse;    #! A button pressed or let go, the wheel, or a move.
  pub var paste:   strview;  #! Text pasted, good until the next event is read.
  pub var resized: size;     #! The terminal's new size.
  pub var focused: bool;     #! Whether the window gained focus or lost it.
}

pub enum modifier: u32 { shift = 1, alt = 2, control = 4 }

pub struct key : equatable {
  pub var code:      key_code;           #! Which key.
  pub var character: u32;                #! The character, where `code` is `character`.
  pub var modifiers: flags32<modifier>;
}

pub enum key_code: u8 {
  character, enter, tab, backspace, escape,
  up, down, left, right, home, end, page_up, page_down, insert, delete,
  f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12,
}

pub struct mouse : equatable {
  pub var action:    mouse_action;  #! press, release, drag, move, wheel_up or wheel_down.
  pub var button:    mouse_button;  #! left, middle, right, or none.
  pub var column:    i32;
  pub var row:       i32;
  pub var modifiers: flags32<modifier>;
}

The canvas (decisions 7 to 9):

pub struct size : equatable { pub var columns: i32; pub var rows: i32; }
pub struct position : equatable { pub var column: i32; pub var row: i32; }
pub struct rect : equatable { pub var left: i32; pub var top: i32; pub var width: i32; pub var height: i32; }

#! Light, heavy or double strokes, or light ones with rounded corners.
pub enum line_style: u8 { light, heavy, double, rounded }

#! A grid of cells to draw a frame on.
pub struct canvas : owning { ... }

pub def canvas::new(of: size): canvas;
pub val canvas::size: size;
pub def canvas::resize(&mut this, to: size): void;
pub def canvas::clear(&mut this, with: style = style{}): void;
pub def canvas::put(&mut this, column: i32, row: i32, text: strview, with: style = style{}): i32;  # columns used
pub def canvas::fill(&mut this, area: rect, character: u32, with: style = style{}): void;
pub def canvas::draw_box(&mut this, area: rect, lines: line_style = line_style::light, with: style = style{}): void;
pub def canvas::draw_across(&mut this, row: i32, from: i32, to: i32, lines: line_style = line_style::light, with: style = style{}): void;
pub def canvas::draw_down(&mut this, column: i32, from: i32, to: i32, lines: line_style = line_style::light, with: style = style{}): void;
pub var canvas::cursor: maybe<position>;  # where the cursor shows after the frame, or hidden
pub def canvas::write_to<W>(&this, into: &mut painter<W>): result<void, io_error>;  # as lines, in ordinary output

pub def width_of(character: u32): u8;   # 0, 1 or 2
pub def width_of(text: strview): u64;

Using it

Color in ordinary output, which is plain text through a pipe:

import std;
import std::io;
import std::term;

def main(args: span<strview>): void {
  val out  := term::output();
  val warn := style{ fg = color::yellow, effects = effect::bold };
  _ = out.write("note: ");
  _ = out.write("`x` is never read", warn);
  _ = out.write("\n");

  println($"{term::paint("ok", style{ fg = color::green })} 12 tests");
}

A line of progress, written over itself:

val out := term::output();
for i in 0u..total {
  out.to_column(0);
  out.clear(clearing::line);
  _ = out.write($"building {i + 1} of {total}");
  _ = out.flush();
  build(i);
}
_ = out.write("\n");

A box in ordinary output:

var table := canvas::new(size{ columns = 32, rows = 4 });
table.draw_box(rect{ left = 0, top = 0, width = 32, height = 4 });
table.draw_down(16, 0, 3);
table.put(2, 1, "files");
table.put(18, 1, "1,204");
table.put(2, 2, "notes");
table.put(18, 2, "0", style{ fg = color::green });
_ = table.write_to(term::output());
┌───────────────┬──────────────┐
│ files         │ 1,204        │
│ notes         │ 0            │
└───────────────┴──────────────┘

A full-screen program:

import std;
import std::io;
import std::term;
import std::time;

def main(args: span<strview>): void {
  val names: strview[3] = ["build", "test", "clean"];
  var tty := terminal::open() else (e) { println("not a terminal"); return; };
  var frame := canvas::new(tty.size);
  var chosen := 0u;

  while true {
    frame.clear();
    frame.draw_box(rect{ left = 0, top = 0, width = frame.size.columns, height = frame.size.rows }, line_style::rounded);
    frame.put(2, 0, " Pick one ", style{ effects = effect::bold });
    for i, name in names {
      frame.put(2, 1 + i as i32, name, i == chosen ? style{ effects = effect::reverse } : style{});
    }
    _ = tty.show(&frame);

    val came := tty.next(milliseconds(250)) else (e) { return; };
    val ev := came else { continue; };   # nothing came within the wait
    if ev is resized(to) {
      frame.resize(to);
    } else if ev is key(k) {
      val typed := k.code == key_code::character;
      if k.code == key_code::up && chosen > 0 { chosen--; }
      if k.code == key_code::down && chosen + 1 < names.length { chosen++; }
      if k.code == key_code::enter || (typed && k.character == 'q') { return; }
      if typed && k.character == 'z' && k.modifiers.get(modifier::control) { tty.suspend(); }
    }
  }
}   # tty closes: the shell's screen, its mode and its cursor come back

How each part works

  • What it knows of terminals (decision 2): the sequences of ECMA-48, and xterm's private modes, which the terminals in use today share. These include xterm, VTE's (GNOME Terminal), Konsole, kitty, Alacritty, WezTerm, foot, iTerm2, Windows Terminal, tmux and screen. Synchronized output (CSI ?2026h) is written around every frame, and terminals that don't know it ignore it.
  • Detecting what a stream shows (decision 3):
    • Controls are written where the handle is a terminal and TERM isn't dumb.
    • Colors, the first of these that holds:
      1. NO_COLOR set and not empty gives none. no-color.org allows keeping bold and the rest, but none drops them too, so it always means plain text;
      2. a handle that isn't a terminal, or TERM=dumb, gives none, unless FORCE_COLOR is set and not empty;
      3. COLORTERM of truecolor or 24bit gives full;
      4. a TERM ending in 256color gives indexed;
      5. on Windows, a console whose virtual terminal processing is on gives full;
      6. anything else gives basic.
    • It reads only the environment it's given, so tests pass their own.
  • Bringing colors down:
    • 24-bit becomes the nearest of the 6×6×6 cube and the 24 grays, as xterm's palette sets them;
    • either of those becomes the nearest of the sixteen, by xterm's default colors;
    • nothing is written at none.
  • Writing a style:
    • Where the style only gains something, only that is written.
    • Where anything turns off, CSI 0m is written, then the whole style. Bold and dim share their "off", so the shorter way isn't always right.
    • A painter remembers the style it last wrote, so a run of text in one style writes it once.
  • Raw mode is cfmakeraw's, but for output:
    • a \n still begins a line, so the program's own println still works;
    • the canvas moves the cursor itself and never writes one.
  • Reading input:
    • The terminal polls its input with the wait given, reads what has come into a buffer, and decodes one event at a time.
    • Keys come as xterm writes them:
      • CSI A to D and SS3 A to D for the arrows;
      • CSI H and CSI F for Home and End, and CSI n ~ for them too, and for Insert, Delete, PageUp, PageDown and F5 to F12;
      • SS3 P to S for F1 to F4;
      • CSI 1;m X with the modifiers, as m - 1 holds Shift 1, Alt 2 and Ctrl 4;
      • CSI Z for Shift-Tab;
      • ESC before a key for Alt;
      • bytes 1 to 26 for Ctrl with a letter, but 9 is Tab and 13 is Enter;
      • 127 and 8 for Backspace, as terminals differ, so Ctrl-H reads as Backspace;
      • UTF-8 for any other character.
    • A lone Escape is told from the start of a sequence by waiting escape for more: 50 ms by default, as Neovim waits. The probe used 30.
    • The mouse: mouse_mode's buttons, drags and moves turn on xterm's modes 1000, 1002 and 1003, always with 1006. That's SGR's encoding (CSI < b;x;y M or m), whose places have no limit, unlike the original encoding's 223 columns.
    • Pasting comes between CSI 200~ and CSI 201~, as one event.
    • Focus comes as CSI I and CSI O.
    • A sequence it doesn't know is passed over whole, and bytes that aren't UTF-8 become U+FFFD.
  • Resizing:
    • While open, the terminal handles resized with a function that notes it in a variable of std::term. A closure won't do: the terminal moves once it's opened, and a closure would refer to where it was.
    • A wait the signal interrupts ends with -4, and next then reads the size again and gives event::resized. Watching for the signal instead wouldn't end the wait.
    • Handlers run only in the thread the program began with, so next called in another thread sees a resize only once its wait ends.
    • The program resizes its canvas, and the next show writes every cell.
    • On Windows, where no signal comes, next reads the size each time it returns (decision 11).
  • Suspending:
    • suspend puts the terminal back, as closing it would, then raises suspend, so the program stops as Ctrl-Z would stop it. Probed.
    • When the shell resumes it, the terminal is taken again, and next gives event::resized with the size, which may have changed meanwhile. That makes the next frame whole.
    • Windows has no such stopping, and raise(suspend) gives unsupported there, so suspend does nothing.
  • Showing a frame:
    • The terminal keeps the last frame it wrote, and compares the new one with it cell by cell.
    • For each run of changed cells, it moves the cursor only where the cursor isn't already, writes the style only where it changes, then writes the text.
    • All of it goes into one string, kept between frames, which is written in one write inside synchronized output, so a frame never shows half drawn.
    • The first frame, and the first after a resize, are written whole.
  • Cells:
    • A cell holds the UTF-8 of one character and of the marks joining it, up to 16 bytes, with its style and its lines.
    • A character two columns wide takes the next cell too, which is marked as its second half. Drawing over either half clears the other.
    • A cluster longer than 16 bytes, as some emoji sequences are, keeps its first character.
    • A tab moves to the next column that's a multiple of eight. Other control characters are drawn as �.
  • Width (decision 7):
    • width_of follows Unicode 16. A character is two columns where its East Asian width is W or F. It's none where it's a mark (Mn, Me), a format character (Cf) other than the soft hyphen, a Hangul vowel or final (U+1160 to U+11FF), or U+200B. Any other character is one column.
    • The table is 369 ranges of none and 123 of two, about 4 KB.
    • tools/widths.sakura writes it into std/term/widths.sakura, from Unicode's EastAsianWidth.txt and DerivedGeneralCategory.txt, when Unicode changes.
    • width_of(text) passes over printable ASCII, a column a byte, eight bytes at a time with std::swar, and looks up only the rest.
  • Lines that meet (decision 9):
    • A cell holds, for each of its four sides, whether a line leaves by it, and how heavy: light, heavy or double. That's two bits a side, and a ninth bit for a rounded corner.
    • Drawing a line adds to what the cell holds, and the glyph is looked up from all four sides. So a line drawn down through a box's top edge gives ┬, and two boxes sharing an edge give ├, ┤ and ┼ where they meet.
    • A line's end leaves its last cell by one side only, so a line drawn down from a box's top edge meets it as ┬, not ┼. A cell with a line leaving by one side only is still drawn as a whole ─ or │, so a line standing alone looks whole.
    • Every one of the 80 meetings of light and heavy strokes has a glyph in U+2500–U+257F.
    • Double strokes have glyphs only where the two sides along a line agree. Elsewhere, and where double meets heavy, the double sides are drawn light.
    • A rounded corner becomes square once a third line joins it.
    • Text put on a cell clears its lines.
  • Ordinary output: canvas::write_to writes each row's cells with their styles, then a line break, with no cursor moves. So it works through a pipe, where it writes only the text.
  • When the program stops some other way (decision 5):
    • Opening the terminal gives the runtime one record: the handle, the mode to put back, the text that undoes the screen, and the process that made it.
    • exit and a fault from any thread, abort and a failed contract put them back before anything else, with two system calls. A fault's report then shows on the shell's screen, not on the alternate one about to vanish.
    • Closing the terminal forgets the record. A copy made by fork leaves it alone, since the process isn't the one that made it.
    • The terminal also handles terminate and hangup while open, where the program doesn't, putting things back and then stopping as the signal would have.

Testing

  • test/std/term.sakura, written with std::testing, covers:
    • detection, from environments the tests give: a pipe, TERM=dumb, NO_COLOR, FORCE_COLOR, COLORTERM and 256color;
    • painting: every sequence, written to a string and compared exactly, at each depth. Also styles that only gain, styles that lose something, and nothing at all where the stream shows nothing;
    • bringing colors down, against a table, with the cube's and the grays' edges;
    • decoding input, from bytes the tests give, not from a terminal:
      • every key, with and without modifiers;
      • UTF-8 split across reads;
      • mouse reports, and pasting;
      • sequences it doesn't know, and bytes that aren't UTF-8;
    • width, of ASCII, é both composed and decomposed, 中, 😀, U+200B and U+0301;
    • boxes: each meeting of strokes, boxes sharing edges, a line through a box, double meeting light and heavy, and rounded corners joined;
    • the canvas: text clipped at its edges, wide characters at the last column, and drawing over half of one;
    • showing frames: a small terminal emulator in the test reads what show wrote, handling cursor moves, styles and text. The tests check its screen against the canvas, after a first frame, a changed one, a resize, and wide characters;
    • a real terminal, on Linux: the tests open a pseudo-terminal through /dev/ptmx, as the probe's driver did through Python, and run the terminal on it:
      • raw mode taken and put back;
      • the size, and a resize, from a resized the test raises;
      • keys written to it and read back as events;
      • a forked copy that opens the terminal and then faults, after which the mode is the one it found (decision 5).
  • A program of the corpus writes a box and a colored table to its output, a pipe, where it's plain text, under both compilers.
  • Where they run: in the VM, under run --checks, and as executables at -O0 and -O2. The rebuild's analyzer must check them with 0 notes, and std must still check for --target windows-x86_64. The time to check a one-line program is measured before and after.

Phases

About 130 lines of std::sys for Linux and 80 for Windows (decision 11), 2,300 of std::term (150 of them written by the tool), 150 for the tool, and 1,000 of tests. Decision 5's record adds two intrinsics to each compiler, and a few lines to each runtime's ways of stopping.

  1. std::sys: is_terminal, terminal_size, the modes, take_handling and give_handling, and io_error::not_a_terminal, on Linux and Windows. The logging plan can then color its levels.
  2. Styles and painting: style, abilities_of, painter, paint, and the cursor and screen.
  3. Width: the tool and the table.
  4. The canvas and boxes, with write_to.
  5. The terminal: raw mode, input, resizing, suspending, and show.
  6. Putting it back on every way out (decision 5), in both compilers and both runtimes.
  7. A "Terminals" section in the README.

Found along the way

  • sys::poll couldn't time out: settled. It has taken a wait in milliseconds since 2026-10-19.
  • io_error has nothing for ENOTTY, which becomes other.
  • Nothing runs when a program stops but close. A module's variable is never closed, so a terminal kept in one would be left raw even when main returns.
  • A signal's handler can't be read back, so a library that handles a signal for a while can't give the program's own back. A handler is a function now, moved and never copied, so it can't be read and left in place either. This plan adds sys::take_handling and sys::give_handling, where it had sys::handler_of.
  • Interpolation can't call a type's method to format it. A trait for that, as describable, would let $"{warn}" write a style's sequence. It would be a change to the language, in both compilers, so this plan works around it with paint.
  • attribute is taken (2026-10-20). It's std's trait for the structs written after @, so a program importing std::term had to write term::attribute::bold, in both compilers. The enum is effect now, and a style's field effects.
  • A module's variable can't hold a reference, since it needs a zero value. So the shared painters paint term::standard, not &mut writer<console>.
  • Union fields need pub for a program to test them, as ev is key(k). The sketches had left it out.
  • Windows' poll sees a console as always ready, since it peeks pipes, and a console isn't one.
  • A signal watched for doesn't end a wait, so the terminal handles resized rather than watching for it.

Later, where wanted

  • Inline frames: a canvas shown below the shell's prompt, not on the alternate screen, as a picker or a progress display does. It needs the cursor's position, read through CSI 6n, whose answer looks like F3 with modifiers, and is told apart only by waiting for it.
  • Widgets:
    • lists, tables and text fields;
    • scrolling views;
    • layout that splits a rect by constraints;
    • a line editor with history, as readline is.
  • The kitty keyboard protocol, for keys xterm's encoding can't tell apart, as Ctrl-I from Tab, and for keys let go.
  • Hyperlinks through OSC 8.
  • The terminal's colors, read through OSC 10 and 11, to tell a light theme from a dark one.
  • Grapheme clusters, by Unicode's segmentation rules, once terminals agree on how wide they are.
  • ASCII boxes, for terminals without UTF-8. Also the Linux console's font, which lacks heavy and rounded strokes.
  • Images, through sixel or kitty's graphics.
  • terminfo, for a TERM the built-in sequences don't suit.
  • The terminal's input on Windows, where decision 11 leaves it for later.
  • Events from a thread: a thread reading the terminal and sending its events through a thread::channel, so a program waits on its own work and on input at once. Resizes would still be noted in the thread the program began with.

Decisions for you

  1. Where it lives:
    • (a) std::term, in std/term/ (recommended). One import gives a program all of it. Every program is checked with all of std anyway, so splitting it saves nothing.
    • (b) std::term for styles, painting and the terminal, and std::tui for the canvas and boxes. The names say more, at the cost of two imports for a full-screen program.
    • (c) Styles, painting and the terminal in std, and the canvas, boxes and widths left to a library outside it. Every program's check would pay for about 850 fewer lines: about 2 ms less in the rebuild and 4 to 6 in C, at the clock measured above.
  2. What it knows of terminals:
    • (a) xterm's sequences, built in (recommended). It's what the terminals in use share, and what crossterm and termenv do.
    • (b) The terminfo database, as curses reads it. Its entries lag what terminals do, as with 24-bit color, and its files are a compiled format to read.
    • (c) (a), with terminfo for a TERM it doesn't know.
  3. How color is decided:
    • (a) From the handle and the environment, as "How each part works" orders it, with colors brought down to what's found (recommended).
    • (b) The program says, and std never looks. Every program then repeats the same checks, or writes color into files.
    • (c) Ask the terminal, through its replies to queries. It's exact, but slow over a network, and impossible through a pipe.
  4. How styled text is written:
    • (a) Through a painter over any stream, with paint for interpolating (recommended). A painter knows what its stream shows, and writes a style only where it changes.
    • (b) Only as text to interpolate, as $"{term::red}x{term::reset}". It's the easiest to write, but colors reach files and pipes unless each program checks, and nothing brings them down.
    • (c) Only through a terminal. Ordinary output, such as the logging plan's, couldn't be colored.
  5. When the program stops without closing the terminal:
    • (a) The runtime and both VMs put it back, from a record std keeps (recommended). This covers exit, faults, abort, failed contracts, and a terminal kept in a module's variable. It adds two intrinsics to each compiler.
    • (b) Only close. A fault leaves the shell in raw mode, on the alternate screen, with the mouse reported, until the user types reset.
    • (c) (b), with terminate and hangup handled while the terminal is open. That covers being killed politely, but not faults.
  6. Input:
    • (a) Keys, text, the mouse, pasting, focus and resizing, read with a timeout (recommended).
    • (b) Keys and resizing only, with the mouse and pasting later.
    • (c) None: output only. Full-screen programs would read bytes themselves.
  7. How wide text is:
    • (a) A table of each character's width, from Unicode 16 (recommended). It's what wcwidth does and what terminals do, for about 4 KB.
    • (b) Every character is one column. No table is needed, but Chinese, Japanese, Korean and emoji break the layout.
    • (c) Grapheme clusters, with Unicode's segmentation rules too. It's more exact where terminals agree, which they don't yet for emoji sequences, and it needs a second, larger table.
  8. What draws the screen:
    • (a) A canvas the program draws whole each frame, of which std writes only the changes (recommended). It's as ratatui and tcell work. The program keeps its own state, and draws from it.
    • (b) Widgets std keeps, which the program changes, and which redraw what they cover, as curses' windows do. It's more API, and state in two places.
    • (c) No canvas: programs draw with the painter's cursor moves. There's less to build, but every program works out what changed itself, and boxes can't join.
  9. Boxes that meet:
    • (a) Joined, from the lines each cell holds (recommended).
    • (b) Each box writes its own glyphs, and the last drawn wins. It's simpler, but boxes sharing an edge show broken corners.
  10. Places on the screen:
    • (a) From 0, column first, as rect is (recommended). It's as drawing in most libraries is, and the sequences' rows and columns from 1 stay inside std.
    • (b) From 1, row first, as the sequences number them. It matches what a terminal's documentation says, but not rect, size or the mouse's columns.
  11. Windows, which std has supported since 2026-10-19. Whatever is chosen, each operation std::sys gains exists there too, since std is checked whole for an executable for Windows, and one missing there is an error in every such check (probed in both compilers):
    • (a) Output now, input later (recommended). is_terminal, the size, and virtual terminal processing, so painters and canvas::write_to color a console as they do a terminal, and the logging plan's levels with them. terminal::open gives io_error::unsupported there until raw input, a wait on the console, and resizing are built. About 80 lines.
    • (b) All of it now, with raw input through ENABLE_VIRTUAL_TERMINAL_INPUT, a wait on the console's handle, and resizes found by reading the size at each next. It's more code, and none of it can be probed here.
    • (c) Linux only. Each new operation gives unsupported on Windows, and is_terminal false, so nothing is colored there.