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 ¶
- 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 Modifier
- type MouseAction
- type MouseButton
- type MouseMode
- type ResizeEvent
- type Terminal
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
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, 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 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
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 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 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 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
}
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-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
|