terminal

package module
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 15, 2026 License: BSD-3-Clause Imports: 17 Imported by: 3 modules, 19 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

terminal

Direct ANSI terminal control for Go with zero-allocation rendering. Built for sustained 60fps full-screen redraws in cell-based applications (games, dashboards, TUIs). Depends on github.com/lixenwraith/color (RGB, palettes, blending), golang.org/x/sys and golang.org/x/term.

The package bypasses terminfo/termcap entirely and emits ANSI sequences directly. Target environments: xterm-compatible terminals on Linux and BSDs, Windows consoles with VT processing, and browsers via xterm.js (WASM builds).

Features

  • True color (24-bit), 256-color, ANSI 16-color and colorless output with automatic capability detection, and the terminal's own default colors
  • Double-buffered output with cell-level diffing — only changed cells emit sequences
  • Raw stdin parsing: keys, modifiers, UTF-8 runes, SGR mouse, resize, bracketed paste
  • Draws on the controlling terminal when stdin or stdout is redirected (Unix)
  • Perceptual (Redmean) RGB → 256-palette mapping via O(1) LUT, from color
  • Panic-safe terminal restoration (Fini, EmergencyReset)
  • Unix, Windows and WASM backends behind a common interface

Architecture

Terminal (interface)
  └── termImpl
        ├── outputBuffer   diffing, ANSI generation
        ├── writeLoop      the one goroutine that writes output
        ├── inputReader    escape sequence parser, event channel
        └── Backend (interface)
              ├── unixBackend     //go:build unix — termios, unix.Poll, SIGWINCH, /dev/tty
              ├── windowsBackend  //go:build windows — console modes, VT processing
              └── wasmBackend     //go:build wasm — syscall/js, xterm.js bridge

Shared code carries no build tags: cell diffing, ANSI generation, escape parsing. Platform specifics are isolated in the Backend implementations.

Rendering pipeline

The application owns a flat []Cell buffer (row-major, cells[y*width+x]) and passes it to Flush. The output buffer diffs against the previously flushed frame:

  • Rows are scanned with early termination (trailing unchanged cells skipped).
  • Cursor moves are emitted only when the write position is non-contiguous.
  • SGR state (fg, bg, attributes) is coalesced across cells; redundant sequences are suppressed.
  • If the backend size changed between buffer preparation and Flush, the frame is dropped to prevent resize-race corruption. The next frame (built at the new size) renders normally.
  • A cell is one glyph in one column, on a terminal that draws ambiguous-width runes (box drawing, U+FFFD) narrow: a control or format character in Rune (a pasted escape, a bidi override, a line separator) is drawn as a space, and a rune a terminal draws in no column, in two or in its neighbour's cluster (a combining or spacing mark, a wide or emoji rune) as U+FFFD.

Sync() clears the screen and invalidates the front buffer, forcing a full redraw — required after any external process writes to the terminal.

Output is written on a goroutine of its own, so no call waits on the terminal. A terminal that stops reading (a hidden tab, a multiplexer client that went away, flow control) holds that goroutine in its write; meanwhile Flush keeps only the newest frame, drawn once the write returns, and control sequences (cursor, mouse, paste, Clear, Sync) queue behind it in call order. Blocked() reports how long the write in flight has waited, so a caller can stop composing frames nobody will see. Fini waits up to two seconds for the restoring sequences, then restores the termios without them.

Auto-wrap and, where the terminal follows ECMA-48 mode 8 (VTE), its own bidi reordering are off during the session: the bottom-right cell is writable without scroll side effects, and right-to-left text stays in its cells.

Quick start

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 {
        // Build frame
        for i := range cells {
            cells[i] = terminal.Cell{Rune: ' ', Bg: color.Gunmetal}
        }
        msg := "hello"
        for i, ch := range msg {
            // len(msg) to utf8.RuneCountIdString(msg) for non-ASCII
            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)

        // Handle input
        ev := term.PollEvent()
        switch 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)
        }
    }
}

Cells and attributes

type Cell struct {
    Rune  rune
    Fg    color.RGB
    Bg    color.RGB
    Attrs Attr
}

Attr is a bitmask: AttrBold, AttrDim, AttrItalic, AttrUnderline, AttrBlink, AttrReverse.

Attr is 16 bits wide; the bits above the styles say how to read a cell's colors:

  • With AttrFg256 / AttrBg256 set, Fg.R / Bg.R holds an xterm-256 palette index directly and G/B are ignored. This allows exact palette output on true color terminals and skips RGB → palette conversion. Indices 0-15 are the ANSI 16, which every terminal shows in its own theme's shades.
  • With AttrFgDefault / AttrBgDefault set, the color is the terminal's own (SGR 39/49), whatever Fg / Bg hold: an application keeps a light or dark terminal's background without knowing which it is.

Color system

Modes

ColorModeTrueColor emits 38;2;R;G;B sequences; ColorMode256 emits 38;5;N after mapping; ColorMode16 emits 30-37/90-97 and 40-47/100-107, an RGB or palette color mapped to the nearest ANSI index; ColorModeNone emits attributes only, so a highlight drawn as a background color alone (a list's CursorBg) does not show; the tui form controls mark every selection with a glyph.

DetectColorMode() reports what the terminal can show from the environment (COLORTERM, TERM): 16 colors on a text console (TERM of linux, cons25*, vt and a digit, ansi or *-16color), whatever COLORTERM says. In 16 colors every color change restates the style from a reset, since a console's bright colors (90-97) also set bold. New() also honours NO_COLOR, choosing ColorModeNone; a mode passed to New overrides both, as a --color=always or never would. Init refuses TERM=dumb, which cannot address the cursor.

Init and Sync clear the screen to the terminal's own background. EmergencyReset(os.Stdout) writes to the controlling terminal when stdout is redirected, so the reset never lands in the program's output.

RGB → 256 mapping

RGBTo256 maps any RGB to the nearest xterm-256 index using perceptually weighted Redmean distance. The full mapping is pre-computed at init into a 6-bit-quantized LUT (256KB, L2-resident), making per-cell conversion a single array load. Applications targeting 256-color terminals can render in RGB throughout; degradation is automatic.

Palette helpers: Cube256(r,g,b) / CubeRGB256(idx) for 6×6×6 cube math, Gray256(step) for the grayscale ramp, plus named constants (P256Amber, P256SteelBlue, ...) and named true color values (Amber, Gunmetal, Obsidian, ...), all in github.com/lixenwraith/color.

Blending

github.com/lixenwraith/color provides compositing primitives operating on RGB. All take destination first and are branch-free in the hot path or LUT-backed; suitable for per-cell use at frame rate.

  • Blend(dst, src, alpha): linear interpolation, standard transparency
  • Add(dst, src, alpha): saturating add, bright accumulation, clips
  • Screen(dst, src, alpha): 1-(1-d)(1-s), lightens, never clips
  • Overlay(dst, src, alpha): multiply/screen split at 0.5, contrast, keeps dst structure
  • SoftLight(dst, src, intensity): Perez soft light, gentle tint/glow
  • Max(dst, src, alpha): per-channel max, non-additive highlight
  • Scale(c, factor): channel multiply, dim/brighten
  • Grayscale(c): Rec. 601 luma, desaturation
  • c.Lerp(other, t): method on RGB, gradients, animation

alpha/intensity/t are [0,1]; out-of-range values clamp. alpha of 0 or 1 short-circuits without float math. All float→channel conversions round half-up, so gradients from Blend, Scale, Lerp, and SoftLight are bit-consistent.

bg := color.Gunmetal
glow := color.RGB{R: 255, G: 160, B: 40}

cell.Bg = color.Screen(bg, color.Scale(glow, pulse), 1.0) // pulsing glow
cell.Bg = color.Blend(cell.Bg, color.Black, 0.6)          // dim overlay backdrop
cell.Fg = color.SoftLight(cell.Fg, tint, 0.4)                // subtle recolor
bar := cold.Lerp(hot, load)                                     // value-mapped gradient

Integer paths (Add, Screen, Overlay) use a (x + (x>>8) + 1) >> 8 division approximation; SoftLight uses init-time LUTs replacing math.Sqrt.

Input

PollEvent() blocks on a unified channel. Event.Type values:

  • EventKey — Key for named keys (KeyEnter, KeyUp, KeyCtrlC, ...), Key == KeyRune with Rune set for printable input, Modifiers bitmask (ModShift, ModAlt, ModCtrl)
  • EventMouse — 0-indexed MouseX/Y, MouseBtn (buttons, wheel), MouseAction (press/release/move/drag), modifiers. Enable via SetMouseMode(MouseModeClick | MouseModeDrag); SGR protocol only.
  • EventResize — new Width/Height
  • EventPaste — Text holds a whole paste, as sent, control characters included. Enable via SetPasteMode(true) (bracketed paste); off, a paste arrives as keys, its newlines pressing Enter.
  • EventError, EventClosed

A standalone ESC press is disambiguated from escape sequences by a short input-idle timeout (one ~10ms poll cycle). ESC ESC is Alt+Escape alone, Escape before a paste, and Alt with the key that follows otherwise (rxvt's Alt+arrows). Partial UTF-8 and escape sequences at read boundaries are reassembled in a persistent buffer. With paste mode off, a paste marker is not a paste. A paste whose end marker never arrives ends once input pauses for a second, so what follows a paste that stalls that long arrives as keys.

On Unix, a redirected stdin or stdout is replaced by /dev/tty, so app > out.toml and cmd | app keep both as data while the application draws and reads keys on the terminal. PostEvent injects synthetic events (used for clean shutdown of blocked PollEvent).

WASM

WASM builds bridge to xterm.js via JS globals:

goTerminalWrite(Uint8Array)    // Go → JS terminal output
goTerminalInput(Uint8Array)    // JS → Go keyboard input
goTerminalResize(cols, rows)   // JS → Go resize
xterm.cols, xterm.rows         // initial size query

Sub-packages

  • tui — immediate-mode widget toolkit (regions, layout, widgets, scroll/editor state) built on the cell buffer model.

Documentation

Overview

Package terminal provides direct ANSI terminal control with zero-alloc rendering.

Features

  • True color (24-bit), 256-color, ANSI 16-color and colorless output, and the terminal's own default colors
  • Double-buffered output with cell-level diffing
  • Raw input parsing with escape sequence handling and bracketed paste
  • Drawing on /dev/tty when stdin or stdout is redirected (Unix)
  • Resize detection (SIGWINCH on Unix, callback on WASM)
  • Clean terminal restoration on exit/panic

Platform Support

The package uses build tags to separate platform-specific code:

  • unix: Native terminal via termios, unix.Poll, SIGWINCH
  • wasm: Browser terminal via xterm.js JavaScript bridge

Architecture

The Backend interface abstracts platform-specific operations:

Backend (interface)
├── unixBackend  (//go:build unix)  - termios, raw I/O, signals
└── wasmBackend  (//go:build wasm)  - syscall/js, callbacks

Shared code (no build tags): Terminal interface, cell diffing, ANSI generation, escape sequence parsing.

WASM Integration

WASM builds require JavaScript glue exposing these globals:

goTerminalWrite(Uint8Array)     // Go → JS: terminal output
goTerminalInput(Uint8Array)     // JS → Go: keyboard input
goTerminalResize(cols, rows)    // JS → Go: terminal resize
xterm.cols, xterm.rows          // Initial size query

Performance

Output uses cell-level diffing. Only changed cells generate ANSI sequences. Style attributes are coalesced to minimize SGR calls. One goroutine writes what is rendered, so a terminal that stops reading never holds the caller: Flush keeps the newest frame until the write in flight returns, and Blocked reports how long it has waited. Input parsing is zero-allocation for common cases.

This package bypasses terminfo/termcap entirely, emitting direct ANSI sequences. Target environments: Linux, macOS, BSDs with xterm-compatible terminals, and modern browsers with xterm.js.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func EmergencyReset

func EmergencyReset(w io.Writer)

EmergencyReset attempts to restore terminal to sane state Call this from panic recovery if Fini() cannot be called normally. Given a redirected stdout, it writes to the controlling terminal instead.

func KeyName

func KeyName(k Key) string

KeyName returns the canonical string name for a Key constant Returns empty string for KeyNone and KeyRune

func RGBTo256

func RGBTo256(c color.RGB) uint8

RGBTo256 delegates to the color package's perceptual quantizer. Exists to preserve terminal API backwards-compatibility.

func WarmPalette256

func WarmPalette256()

WarmPalette256 delegates to the color package's lazily evaluated 256-color LUT builder. Exists to preserve terminal API backwards-compatibility.

func WindowSize

func WindowSize(f *os.File) (w, h int, ok bool)

WindowSize queries terminal dimensions for f without raw mode or Terminal lifecycle. ok=false when f is not a terminal.

Types

type Attr

type Attr uint16

Attr represents text attributes and how to read a cell's colors (bitmask)

const (
	AttrNone      Attr = 0
	AttrBold      Attr = 1 << 0
	AttrDim       Attr = 1 << 1
	AttrItalic    Attr = 1 << 2
	AttrUnderline Attr = 1 << 3
	AttrBlink     Attr = 1 << 4
	AttrReverse   Attr = 1 << 5
	AttrFg256     Attr = 1 << 6 // Fg.R is 256-color palette index
	AttrBg256     Attr = 1 << 7 // Bg.R is 256-color palette index
	AttrFgDefault Attr = 1 << 8 // Fg is the terminal's own (SGR 39); Fg is ignored
	AttrBgDefault Attr = 1 << 9 // Bg is the terminal's own (SGR 49); Bg is ignored
)
const (
	AttrFgColor Attr = AttrFg256 | AttrFgDefault
	AttrBgColor Attr = AttrBg256 | AttrBgDefault
)

AttrFgColor and AttrBgColor mask the bits that say how to read Fg and Bg

AttrStyle masks only the style bits (excludes color mode flags)

type Backend

type Backend interface {
	// Lifecycle
	Init() error
	Fini()

	// Capabilities
	Size() (width, height int)

	// I/O
	// Write writes raw bytes to the terminal output.
	Write(p []byte) error

	// Read blocks until input is available, the stop channel is closed, or an error occurs.
	Read(stopCh <-chan struct{}) ([]byte, error)

	// Callbacks
	// SetResizeHandler registers a callback for terminal resize events.
	SetResizeHandler(handler func(width, height int))
}

Backend abstracts platform-specific terminal operations. This interface allows the terminal package to support both native Unix environments and WASM/Browser environments (via xterm.js).

type Cell

type Cell struct {
	Rune  rune
	Fg    color.RGB
	Bg    color.RGB
	Attrs Attr
}

Cell represents a single terminal cell

type ColorMode

type ColorMode uint8

ColorMode indicates terminal color capability

const (
	ColorMode256       ColorMode = iota // xterm-256 palette
	ColorModeTrueColor                  // 24-bit RGB
	ColorMode16                         // ANSI 16: SGR 30-37/90-97, 40-47/100-107
	ColorModeNone                       // no color; attributes only
)

func DetectColorMode

func DetectColorMode() ColorMode

DetectColorMode determines terminal color capability from environment: 16 colors on text consoles, true color where announced, else 256. It reports what the terminal can show; New also honours NO_COLOR.

type Event

type Event struct {
	Type      EventType
	Key       Key
	Rune      rune
	Modifiers Modifier
	Width     int    // For EventResize
	Height    int    // For EventResize
	Err       error  // For EventError
	Text      string // For EventPaste: the pasted bytes as sent, controls included

	// Mouse event fields
	MouseX      int
	MouseY      int
	MouseBtn    MouseButton
	MouseAction MouseAction
}

Event represents a terminal input event

type EventType

type EventType uint8

EventType distinguishes input event categories

const (
	EventKey EventType = iota
	EventResize
	EventPaste  // Bracketed paste, Text holds it
	EventMouse  // SGR mouse reporting
	EventError  // Read error
	EventClosed // Input closed
)

type Key

type Key uint16

Key represents a parsed input key

const (
	KeyNone Key = iota
	KeyRune     // Printable character (check Event.Rune)

	// Control keys
	KeyEscape
	KeyEnter
	KeyTab
	KeyBacktab  // Shift+Tab
	KeyShiftTab // Same as KeyBacktab,for clarity
	KeyBackspace
	KeyDelete
	KeySpace

	// Navigation
	KeyUp
	KeyDown
	KeyLeft
	KeyRight
	KeyHome
	KeyEnd
	KeyPageUp
	KeyPageDown
	KeyInsert

	// Function keys
	KeyF1
	KeyF2
	KeyF3
	KeyF4
	KeyF5
	KeyF6
	KeyF7
	KeyF8
	KeyF9
	KeyF10
	KeyF11
	KeyF12

	// Ctrl+letter (Ctrl+A = 0x01, Ctrl+Z = 0x1A)
	KeyCtrlA
	KeyCtrlB
	KeyCtrlC
	KeyCtrlD
	KeyCtrlE
	KeyCtrlF
	KeyCtrlG
	KeyCtrlH // Often same as Backspace
	KeyCtrlI // Often same as Tab
	KeyCtrlJ // Often same as Enter
	KeyCtrlK
	KeyCtrlL
	KeyCtrlM // Often same as Enter
	KeyCtrlN
	KeyCtrlO
	KeyCtrlP
	KeyCtrlQ
	KeyCtrlR
	KeyCtrlS
	KeyCtrlT
	KeyCtrlU
	KeyCtrlV
	KeyCtrlW
	KeyCtrlX
	KeyCtrlY
	KeyCtrlZ

	// Ctrl+special
	KeyCtrlSpace // Ctrl+@ / Ctrl+Space (Ctrl+@ produces NUL byte 0x00)
	KeyCtrlBackslash
	KeyCtrlBracketLeft
	KeyCtrlBracketRight
	KeyCtrlCaret
	KeyCtrlUnderscore
)

Key constants - designed for expansion

func KeyByName

func KeyByName(name string) (Key, bool)

KeyByName resolves a canonical name to a Key constant Returns KeyNone and false if name is unknown

type Modifier

type Modifier uint8

Modifier flags

const (
	ModNone  Modifier = 0
	ModShift Modifier = 1 << 0
	ModAlt   Modifier = 1 << 1
	ModCtrl  Modifier = 1 << 2
)

type MouseAction

type MouseAction uint8

MouseAction represents the type of mouse event

const (
	MouseActionNone MouseAction = iota
	MouseActionPress
	MouseActionRelease
	MouseActionMove
	MouseActionDrag
)

func (MouseAction) String

func (a MouseAction) String() string

String returns human-readable action name

type MouseButton

type MouseButton uint8

MouseButton represents mouse button identity

const (
	MouseBtnNone MouseButton = iota
	MouseBtnLeft
	MouseBtnMiddle
	MouseBtnRight
	MouseBtnWheelUp
	MouseBtnWheelDown
	MouseBtnBack    // Button 4 (if supported)
	MouseBtnForward // Button 5 (if supported)
)

func (MouseButton) String

func (b MouseButton) String() string

String returns human-readable button name

type MouseMode

type MouseMode uint8

MouseMode controls which mouse events are reported (bitmask)

const (
	MouseModeNone   MouseMode = 0
	MouseModeClick  MouseMode = 1 << 0 // Press/release events
	MouseModeDrag   MouseMode = 1 << 1 // Drag events (button held + motion)
	MouseModeMotion MouseMode = 1 << 2 // All motion events
)

type ResizeEvent

type ResizeEvent struct {
	Width  int
	Height int
}

ResizeEvent represents a terminal resize

type Terminal

type Terminal interface {
	// Init enters raw mode, alternate screen buffer, hides cursor
	Init() error

	// Fini restores terminal state. Safe to call multiple times
	Fini()

	// Size returns current terminal dimensions
	Size() (width, height int)

	// ResizeChan returns channel that receives resize events
	ResizeChan() <-chan ResizeEvent

	// ColorMode returns detected color capability
	ColorMode() ColorMode

	// Flush hands a frame to the terminal; cells are row-major: cells[y*width + x].
	// It never waits on the terminal: while the last write is still out, the frame
	// is held and drawn once that write returns, a newer one replacing it
	Flush(cells []Cell, width, height int)

	// Blocked reports how long the terminal has held the write in flight, zero
	// while output drains. A terminal that stops reading (a hidden tab, a client
	// that went away, flow control) shows here instead of as a caller that waits
	Blocked() time.Duration

	// Clear fills screen with specified background color
	Clear(bg color.RGB)

	// SetCursorVisible shows/hides cursor
	SetCursorVisible(visible bool)

	// MoveCursor positions cursor (0-indexed)
	MoveCursor(x, y int)

	// Sync forces full redraw
	Sync()

	// PollEvent blocks until next input event
	PollEvent() Event

	// PostEvent injects a synthetic event
	PostEvent(Event)

	// SetMouseMode enables/disables mouse event reporting
	// Modes can be combined: MouseModeClick | MouseModeDrag
	SetMouseMode(mode MouseMode) error

	// SetPasteMode turns bracketed paste on or off: on, a paste arrives as
	// one EventPaste rather than as keys, so its newlines don't press Enter
	SetPasteMode(on bool) error
}

Terminal provides low-level terminal access

func New

func New(colorMode ...ColorMode) Terminal

New creates a new Terminal instance. Without a mode it uses DetectColorMode's, or ColorModeNone when NO_COLOR is set; an explicit mode overrides both, as a --color=always or never would

Directories

Path Synopsis
cmd
example-inline command
example-tui command
fv — file voyager: an lf / midnight-commander / xxd hybrid.
fv — file voyager: an lf / midnight-commander / xxd hybrid.
Package inline renders styled text and in-place progress in the normal terminal scrollback: no raw mode, no alternate screen, no input handling, no cursor hiding.
Package inline renders styled text and in-place progress in the normal terminal scrollback: no raw mode, no alternate screen, no input handling, no cursor hiding.
internal
env
Package env reads what the environment says about a terminal's colors, for terminal and inline alike
Package env reads what the environment says about a terminal's colors, for terminal and inline alike
window module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL