Terminal

Stable

Direct ANSI terminal control for Go, and the same cells in a browser, a desktop window or on Android

Used by ViF, Stapes and LogWisp · Built on Color

Terminal I/O for Go with no terminfo: double-buffered cell diffing, true colour with automatic fallback to 256 or 16 colours, raw key and mouse input, and the same API on a browser page, a desktop window or an Android view, which draw the cells themselves.

  • Cell-level diffing: only changed cells emit escape sequences
  • True colour, or 256 or 16 colours as the terminal supports, mapped perceptually
  • Raw input: keys, modifiers, UTF-8, SGR mouse, resize, bracketed paste
  • One interface over Unix and Windows terminals, a browser page, an X11 window and an Android view
  • An immediate-mode TUI toolkit, inline CLI output and a bitmap font for the window and the Android view, as sub-packages

Quick start

A program fills a slice of cells, hands it to Flush and reads events. This one runs as it is on a terminal and in a browser, and in a desktop window with terminal.New() replaced:

package main

import (
    "github.com/lixenwraith/color"
    "github.com/lixenwraith/terminal"
)

func main() {
    term := terminal.New() // color mode auto-detected
    if err := term.Init(); err != nil {
        panic(err)
    }
    defer term.Fini()

    w, h := term.Size()
    cells := make([]terminal.Cell, w*h)
    for {
        for i := range cells {
            cells[i] = terminal.Cell{Rune: ' ', Bg: color.Gunmetal}
        }
        msg := "hello" // ASCII: len is its width in cells
        for i, ch := range msg {
            cells[(h/2)*w+(w-len(msg))/2+i] = terminal.Cell{
                Rune: ch, Fg: color.Amber, Bg: color.Gunmetal,
                Attrs: terminal.AttrBold,
            }
        }
        term.Flush(cells, w, h)

        switch ev := term.PollEvent(); ev.Type {
        case terminal.EventKey:
            if ev.Key == terminal.KeyEscape || ev.Rune == 'q' {
                return
            }
        case terminal.EventResize:
            w, h = ev.Width, ev.Height
            cells = make([]terminal.Cell, w*h)
        case terminal.EventClosed: // a window's close button
            return
        }
    }
}

In a browser

Built for js/wasm, the program runs in a Web Worker, and the Init of terminal.New()’s Terminal opens the page, which draws the cells on a canvas, with WebGL or else 2D. The page is four files from the module’s web/ directory and Go’s loader, wasm_exec.js, served over HTTP by any static server:

GOOS=js GOARCH=wasm go build -o site/app.wasm .
web=$(go list -m -f '{{.Dir}}' github.com/lixenwraith/terminal)/web
install -m 0644 "$web"/index.html "$web"/page.css "$web"/page.js \
    "$web"/worker.js "$(go env GOROOT)/lib/wasm/wasm_exec.js" site/
python3 -m http.server -d site

index.html runs app.wasm at once. A page opened from a file: URL starts no Worker, and wasm_exec.js must come from the Go that built the binary, so it is copied again at each build.

In a desktop window

The window is a module of its own, github.com/lixenwraith/terminal/window, tagged at the root’s version with every release since v0.7.1. It requires the root at that version, so one go get takes both. The program opens the window in place of terminal.New():

//go:build linux || freebsd

// imports github.com/lixenwraith/terminal/atlas and .../terminal/window
win, err := window.Open(window.Config{
    Title: "hello", Font: atlas.Hack(), Cols: 80, Rows: 24,
})
if err != nil {
    panic(err)
}
term := terminal.NewWithHost(win) // in place of terminal.New()
go get github.com/lixenwraith/terminal/window@latest
CGO_ENABLED=0 go build
# on FreeBSD:
CGO_ENABLED=0 go build -gcflags=github.com/ebitengine/purego/internal/fakecgo=-std

Xlib, EGL and GLES 2 are loaded at run time, as libX11.so.6, libEGL.so.1 and libGLESv2.so.2, the last two from libglvnd or Mesa, so the build needs no cgo. The package builds for Linux and FreeBSD alone, so a program built for other targets too opens the window in a file under that build constraint. The window is open once Open returns: Init opens nothing, Fini closes it, and its close button is an EventClosed, which the loop above returns on.

On Android

android.NewView is the Go half of an Android view: the app binds a Go package of its own that calls it, with gomobile for one, and paints its frames in Java or Kotlin from a texture of the font’s glyphs. ViF’s app is a whole one.

Drawing a frame

There is no terminfo and no retained screen model. The application owns a flat buffer of cells, row by row, draws its whole frame into it, and hands it to Flush, which compares it with the last frame and writes only what changed. It is built for full-screen redraws at 60 frames a second, as games and dashboards make them.

Frame

[]Cellrune, foreground, background, attributes; row by row, the application’s own

Flush

  1. ChangedCellsSIMD a bitmap of a row’s changes; 64 cells compared as one block, then 16, or vectors with SIMD
  2. Runs from the first change to the last, moving over more than three unchanged
  3. Sequences a cursor move only where the write jumps, a color only where it changes
  4. One update wrapped in synchronized output, which a terminal that has it draws whole

Writer

  1. One goroutine no call but Fini, two seconds at most, waits on the terminal; one that stops reading keeps only the newest frame

Backend

  • Unix termios, poll, SIGWINCH, /dev/tty
  • Windows console modes and VT, CONIN$ and CONOUT$
SIMD
Built with GOEXPERIMENT=simd on Go 1.27, the comparison runs on vectors: AVX2 on amd64 where the CPU has it, NEON on arm64, SIMD128 in WebAssembly. Without it, plain Go writes the same bits and the same bytes. ChangedCells is exported for a renderer that draws cells itself, as the hosts below do.
Whole frames
A frame goes out as one synchronized update, which terminals that have the mode, Alacritty from 0.13, kitty, WezTerm, foot and Ghostty among them, draw whole; others ignore it. A frame prepared before a resize is dropped rather than drawn at the wrong size, and Sync clears the screen after another program wrote to it, so the next frame is drawn whole.
One glyph a column
A control or format character in a cell, a pasted escape, a bidi override or a zero-width space, is drawn as a space, and a rune a terminal would draw in no column or two, or join to its neighbour, as U+FFFD, so a frame's columns stay where the application put them on a terminal that draws ambiguous-width runes, U+FFFD and box drawing among them, narrow. The session also turns off auto-wrap and, on terminals that allow it (VTE), the terminal's own bidi reordering.
A stalled terminal
Output goes through one writer goroutine. When a terminal stops reading, a hidden tab or a gone multiplexer client, Flush keeps only the newest frame for when it reads again, and Blocked says how long it has waited, so the application can stop drawing what nobody sees.

Color

DetectColorMode reads COLORTERM, TERM and the variables kitty, Konsole, iTerm2, Alacritty, WezTerm and Windows Terminal set: 24-bit, 256 or 16 colors, and 16 on a text console whatever it claims; New picks none under NO_COLOR. An application draws in RGB throughout. On a 256-color terminal each cell maps through a precomputed Redmean table, one array load per cell, and on 16 colors to the nearest ANSI index. Two bits per color change what a cell’s color means: an xterm-256 index, written exactly on 256 colors or more, or the terminal’s own default, so a program keeps a light or dark terminal’s background without knowing which. Native Windows consoles from 1703 on get true color; one without VT processing is refused at Init, with the reason.

Input

Sources

  • The terminal stdin, or the terminal itself when stdin is a pipe
  • The console keyboardreleases a Linux or FreeBSD virtual console’s raw key codes
  • A host a page’s, a window’s or a view’s keys, pointer and size, decoded and paired by the host itself
  • PostEvent the application’s own events

Reader

  1. Reassemble UTF-8 and escape sequences split across reads
  2. Decode keys, SGR mouse, bracketed paste, focus, CSI u
  3. Time a lone ESC after 10 ms; a paste that stalls, after a second
  4. Pair each release with its press, by physical key

PollEvent

  • EventKey a named key or a rune, modifiers, press, repeat or release
  • EventMouse three buttons, wheel, back and forward; press, release, move, drag
  • EventPaste a whole paste as sent; on a page or a view, a soft keyboard’s or an input method’s text too
  • Resize, focus, key report focus only while releases come through the terminal’s protocol, and the outcome of each ask for releases
  • EventClosed input ended at Fini, or a window’s close button

On Unix an idle reader takes no wakeups: it polls the terminal beside a pipe Wake writes to; on Windows the read still wakes every 10 ms. When stdin or stdout is redirected, the terminal itself is read and drawn on, so app > out.toml and cmd | app keep both as data while the application still has its screen and keys.

Key releases

A terminal reports presses, and a held key as more presses; a game that needs to know when a key comes up asks with SetKeyReport, and an EventKeyReport answers with what it got. Releases pair with their press by physical key, so letting go of Shift first still releases the A, and every hold ends: focus leaving or the console switching away releases what was held, marked lost. Releases come from the first of these sources that the game allows and the screen has:

Console
On a Linux virtual console or FreeBSD's vt(4) the keyboard switches to raw key codes, which needs no root, and each key types what the console's own keymap says. Before the switch the package starts the game's binary again as a guard that puts the keyboard back if the game is killed outright.
Protocol
Elsewhere on Unix, the terminal's key event protocol (CSI u), asked for and confirmed by the terminal's own answers, never guessed from TERM. Alacritty from 0.13 is the reference; it works over ssh, and not through tmux, screen or mosh, where the answer is presses.
Host
A page, a window or an Android view reads its platform's own key events, each key's down and up, and HostKeys pairs them by the host's code for the key; the game allows it as KeySourceHost. A key with no release to come, such as a soft keyboard's delete, lets go as it presses; the text a soft keyboard commits comes as an EventPaste. A window on an X server that sends a held key's repeats as releases and presses, which cannot be told from the player's own, reports presses.

Hosts

A host is a screen that draws the cells itself and reports its player’s keys, pointer and size as the events a terminal would: a browser page, a desktop window or an Android view. Host is its interface, and NewWithHost makes one a Terminal, so a program written to the interface runs on it unchanged. The host is open already, so Init opens nothing, and Fini calls its Close where it has one, as a window does. A host draws in true color, and of a cell’s styles only reverse and dim show. It has no cursor, and a paste, which a window does not take, is one EventPaste whatever the paste mode.

Frame

[]Cellthe frame a terminal takes, through the same Flush

Host

  1. Newest frame kept as Flush returns; one the drawer has not taken yet gives way to it
  2. ChangedCellsSIMD only the cells changed since the frame on screen are encoded or painted
  3. CellColors two RGB colors a cell, a palette index or the terminal’s own resolved; reverse and dim applied, no other style

Drawer

  • Pagejs/wasm posted from the program’s Web Worker; the page draws each rune in its font on a canvas, WebGL or 2D
  • WindowX11 glyph.Raster paints the cells with a bitmap font; GLES 2 shows the pixels as one texture
  • Android view the app’s own drawer, on its thread, paints each frame from the font’s texture, or shows the raster’s pixels
Page
Built for js/wasm, terminal.New() opens the page at Init, and OpenPage opens one with more asked of it: a web font (atlas.HackWeb() is one), the cell size it opens at and the range a zoom keeps to, and rows at the grid's foot that a finger presses with the pointer off. The page fits the grid to the whole cells it holds. Ctrl and the wheel, a trackpad's pinch or two fingers zoom it, a cell 4 to 40 CSS pixels tall unless the program names a range. A finger is the left button. On a touch screen the page shows a strip of keys and raises the soft keyboard on request; the grid keeps its size under the keyboard, its last row's left half drawn again above it at twice its size, and Covered is the rows hidden. PagePost and Handle carry the program's own messages to the page's script and back.
Window
An X11 window on Linux and FreeBSD. The grid is the whole cells the window holds and follows each resize. Ctrl with = or -, or with the wheel, zooms within Config.Zoom once it names a range with a step, and Ctrl with 0 goes back to the font's own size; the window keeps these chords for itself, as many terminal emulators keep them for their own zoom. Config also opens the window maximized or fullscreen.
Android
android.View is the Go half of a view, with no binding of its own: the view's pixels are its grid, its keys, touches and typed text are events, Back is Escape, and a pinch zooms within Config.Zoom, once it names a range with a step, and refits the grid. The drawer is the app's, in Java or Kotlin, on its own thread: it takes the texture of the strike in use from the view, again after a zoom crosses to another strike, and paints each frame from it, or shows the raster's pixels.

Each host reports the zoom its player left as Cell, for a program to keep and open at next time.

A bitmap font

A window and an Android view draw from a bitmap font, which glyph reads: one face at several cell sizes, called strikes, one bit a pixel. A host takes the largest strike no taller than its cell, so a glyph is stretched up and never down where the strikes share one aspect, as Hack’s do. glyph.Raster paints a grid of cells with a strike into RGBA pixels, which the window shows; a glyph.Texture is a strike as one texture, with the frames encoded for it, for a drawer in another runtime, such as an Android app’s. atlas is Hack as such a font, at 6x12, 8x16 and 12x24 pixels, and as a web font for a page. The application imports it and hands the font to its host, and no host imports it, so a binary carries only the form it names. Hack comes under the MIT and Bitstream Vera licences, whose text, atlas/LICENSE, goes with any binary that embeds it.

Widgets and inline output

tui is an immediate-mode toolkit over the same cell buffer: no widget tree and no event loop of its own. A Region is a clipped view of the cells, nested with Sub and Inset, so a widget cannot draw outside its place. Boxes in seven line styles, wires whose tees and crossings join, lists, tables, trees, text fields and an editor, forms, tabs, dialogs, toasts, progress bars and sparklines draw into regions each frame, their state in plain structs the application keeps. It writes cells and nothing else, so its widgets draw the same cells on every host, though a window or an Android view leaves blank a glyph its bitmap font lacks, as Hack lacks the braille spinners and the toast icons.

inline is for command-line tools that stay in the scrollback: permanent lines above a live block rewritten in place, colors that degrade with the terminal, no raw mode and no alternate screen.