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
- Key releases on request, from the Linux or FreeBSD console's keyboard or the terminal's key event protocol (Alacritty's), and presses where there are neither
- Drawing on the terminal itself when stdin or stdout is redirected (/dev/tty on Unix, CONIN$ and CONOUT$ on Windows)
- Resize detection (SIGWINCH on Unix, size records on Windows, 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
- windows: Console modes with VT input and output, size records
- 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 ├── windowsBackend (//go:build windows) - console modes, VT I/O └── 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, and a frame is one synchronized update (DEC mode 2026). 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 ¶
- func ChangedCells(dst []uint64, a, b []Cell) []uint64
- func EmergencyReset(w io.Writer)
- func KeyName(k Key) string
- func RGBTo256(c color.RGB) uint8
- func WarmPalette256()
- func WindowSize(f *os.File) (w, h int, ok bool)
- type Attr
- type Backend
- type Cell
- type ColorMode
- type Event
- type EventType
- type Key
- type KeyAction
- type KeyHolds
- type KeyReport
- type KeySource
- type Modifier
- type MouseAction
- type MouseButton
- type MouseMode
- type ResizeEvent
- type Terminal
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ChangedCells ¶ added in v0.6.5
ChangedCells returns, in dst's storage, a bit for each cell where a and b differ: bit i&63 of word i>>6 for cell i of the first min(len(a), len(b)), the bits past them clear. A frame's changed cells are the bits set against the frame before; built with GOEXPERIMENT=simd, cells compare as vectors.
func EmergencyReset ¶
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 ¶
KeyName returns the canonical string name for a Key constant Returns empty string for KeyNone and KeyRune
func RGBTo256 ¶
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.
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
const AttrStyle Attr = AttrBold | AttrDim | AttrItalic | AttrUnderline | AttrBlink | AttrReverse
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, wait passes or Wake is called, and
// returns no data for the last two; a negative wait never passes. The data
// is valid until the next Read.
Read(wait time.Duration) ([]byte, error)
// Wake makes the Read in progress return, or the next one if none is.
Wake()
// 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 ColorMode ¶
type ColorMode uint8
ColorMode indicates terminal color capability
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
Action KeyAction // For EventKey: KeyPress unless the terminal reports releases
Lost bool // For a KeyRelease the package made for a hold whose own release can't arrive
Width int // For EventResize
Height int // For EventResize
Err error // For EventError
Text string // For EventPaste: the pasted bytes as sent, controls included
Focused bool // For EventFocus: whether the terminal now has focus
Report KeyReport // For EventKeyReport: what the terminal now reports of each key
Source KeySource // For EventKeyReport: the source releases come from, zero for presses
// Mouse event fields
MouseX int
MouseY int
MouseBtn MouseButton
MouseAction MouseAction
Touch bool // A touch, from a host that reads one; terminals report none
}
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 EventFocus // The terminal gained or lost focus, while it reports releases through its protocol EventKeyReport // What a SetKeyReport ask came to: Report through Source )
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 ControlKey ¶ added in v0.4.1
ControlKey is the key a terminal reads for Ctrl with a printable character: the control byte that pair sends, parsed as input parsing reads it. Letters of either case, space and '@', '[' '\' ']' '^' '_', '-' and '/' as '_', and the digits 2 to 7 have one; ok is false for any other character.
type KeyAction ¶ added in v0.5.0
type KeyAction uint8
KeyAction is what happened to a key. Only a terminal reporting releases (see SetKeyReport) tells them apart; elsewhere every key event is a press, and a key held down arrives as more presses at the keyboard's repeat rate.
type KeyHolds ¶ added in v0.5.0
type KeyHolds struct {
// contains filtered or unexported fields
}
KeyHolds pairs key releases with their presses. A source names each physical key by a code of its own (a console keycode, a protocol key number, a host's keycode) and reports presses, repeats and releases of it; KeyHolds hands each on as an Event, a release carrying what its press carried, so letting go of Shift first still releases 'A', not 'a'. The zero value is ready to use. It is not safe for concurrent use.
func (*KeyHolds) ReleaseAll ¶ added in v0.5.0
ReleaseAll ends every hold, sending a Lost release for each, oldest first: focus left, the console switched away, or releases stopped
func (*KeyHolds) Report ¶ added in v0.5.0
Report hands on one report of the key code names through send: ev is the key as the source reads it, its Action set. A press starts a hold and a release ends it, carrying the press's Key, Rune and Modifiers; a repeat passes as it is. A report the holds contradict means the source lost one, as a terminal's own mode swallows keys: a press of a key held first ends that hold with a Lost release, a repeat of a key not held is a press, and a release of a key not held is dropped. A source that repeats a held key as more presses, as the consoles do, asks Held to tell its repeats apart.
type KeyReport ¶ added in v0.5.0
type KeyReport uint8
KeyReport is how much a terminal reports of each key
type KeySource ¶ added in v0.5.0
type KeySource uint8
KeySource is where key releases come from (bitmask). SetKeyReport tries the sources a game allows in the order below; a terminal with none of them reports presses, as every terminal does until a game asks.
const ( // KeySourceConsole is the kernel console's own keyboard, switched to raw // keycodes while releases are asked for: the Linux console on the VT the // game runs on, and FreeBSD's vt(4). Never over ssh, where the keyboard is // the far terminal's. KeySourceConsole KeySource = 1 << iota // KeySourceProtocol is the terminal's key event protocol (CSI u with event // types), found by asking the terminal whether it has one: Alacritty 0.13 // and later, and any terminal that answers the same. Over ssh too. KeySourceProtocol // KeySourceHost is a host that reads its platform's own key events, such as // a window or a browser, and builds Events itself; no Terminal reports it. KeySourceHost )
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 8, a mouse's back side button MouseBtnForward // Button 9, its forward side button MouseBtnWheelLeft // A wheel tilted left, or a touchpad swiped so MouseBtnWheelRight // A wheel tilted right, or a touchpad swiped so )
func (MouseButton) String ¶
func (b MouseButton) String() string
String returns human-readable button name
type ResizeEvent ¶
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
// SetKeyReport asks for keys to be reported at level report. Releases come
// through the first source in allow the terminal has, the console before
// the protocol; KeyReportPresses gives up the source in use. It returns at
// once, and an EventKeyReport follows with what the terminal reports now,
// so a game learns the outcome of every ask; asks the reader has not yet
// acted on are answered together, by the latest. A change of source ends
// the holds it leaves with Lost releases. Until an ask for releases, nothing
// is sent to the terminal or switched.
SetKeyReport(report KeyReport, allow KeySource) error
}
Terminal provides low-level terminal access
func New ¶
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
func NewWithBackend ¶ added in v0.4.0
NewWithBackend creates a Terminal over b in color mode c, for a pipe, an in-process emulator or a test standing in for the tty. b must not be nil; the Terminal calls its Init on Init and its Fini on Fini, and writes to it on its own goroutine as New's does
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
example-inline
command
|
|
|
example-keys
command
keys — shows each key event the terminal reports, for trying key releases where a game runs: a Linux or FreeBSD console, Alacritty, ssh, tmux.
|
keys — shows each key event the terminal reports, for trying key releases where a game runs: a Linux or FreeBSD console, Alacritty, ssh, tmux. |
|
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
|