terminal

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2026 License: MIT Imports: 27 Imported by: 0

README

terminal - a Virtual Terminal Emulator for Go

Go Version License CI Go Reference

A high-performance, cross-platform virtual terminal emulator for Go — headless, scriptable, and renderable.

This package started as a fork of git.sr.ht/~rockorager/tcell-term (v0.10.0, by Tim Culverhouse) and has since undergone substantial improvements: a richer API surface, headless Terminal with synchronous feed, image rendering with custom fonts and colour schemes, session recording and replay (asciinema v2), AI/automation helpers, a comprehensive mock terminal, delta tracking, SSH PTY bridging, WASM support, box-drawing / braille procedural rendering, 8 built-in colour schemes, and 37 runnable demos.


Table of Contents


Features

Area Capabilities
Parser Full ANSI/ECMA-48 parser built on Paul Flo Williams' state machine
Headless Terminal Synchronous Terminal — feed input, inspect screen instantly. No screen, no PTY, no goroutines needed
PTY Session Live Session backed by a PTY subprocess; event-driven with tcell events
Image Rendering Rasterise the terminal to *image.RGBA (PNG / GIF) with custom fonts, cursor styles, colour schemes, bold-as-bright, dim blending, italic synthesis, underlines, strikethrough, overline, and procedural box-drawing / braille characters
Colour Schemes 8 built-in schemes (Dracula, Nord, Solarized Dark/Light, Gruvbox Dark, One Dark, Monokai, Tango Dark) plus custom SchemeSpec
Session Recording Record input/output/snapshots, export as asciinema v2 JSON, replay with Player
Mock Terminal MockTerminal with assertion helpers (AssertCell, AssertLine, AssertCursor, AssertOutput, AssertStyle, AssertBold, AssertItalic, AssertUnderline, AssertCombining, AssertScrollbackLine); ideal for unit tests
AI / Automation AnalyzeScreen (line classification: blank, prompt, command, output, error, status-bar), FindPrompt, GetLastOutput, GetErrorLine, WaitForText, WaitForCursor, WaitForStable, WaitForPattern, ExpectEcho, SendCommandAndWait
Delta Tracking GetDelta returns incremental cell changes since last call
PTY Backends Unix ptys (Linux, macOS, BSDs, Solaris/illumos) and Windows ConPTY, via github.com/malivvan/pty
Mouse Protocols X10, VT200 highlight, button-event, drag, motion, SGR, UTF-8, URXVT
Keyboard Comprehensive key encoding with Shift/Ctrl/Alt/Meta modifiers
DEC Modes Alt screen, bracketed paste, focus events (1004), synchronised output (2026), origin mode, cursor keys, auto-wrap, insert/replace, reverse video, margin bells
Extended Sequences OSC 8 hyperlinks, OSC 52 clipboard, OSC 4/10/11 colour queries, DECRQSS, DECRQM, XTWINOPS, DECSCA protected cells, selective erase, DECALN
Box Drawing Procedural rendering of U+2500–259F (box drawing + block elements) and U+2800–28FF (Braille)
Demos 37 runnable example applications covering every major feature
Custom Surface Screen interface — swap in any rendering backend

Quick Start

Headless Terminal
package main

import (
    "fmt"
    "github.com/malivvan/terminal"
)

func main() {
    t, _ := terminal.NewTerminal(80, 24)
    defer t.Close()

    t.FeedString("Hello, 世界!\r\n")
    fmt.Println(t.String())           // "Hello, 世界!  " …
    fmt.Println(t.Cell(0, 0).Rune)    // 'H'
}
Image Rendering
t, _ := terminal.NewTerminal(80, 24)
defer t.Close()
t.FeedString("\x1b[31mRed text\x1b[0m normal\r\n")

opts := terminal.DefaultRenderOptions()
img := t.RenderImage(opts)
// img is *image.RGBA — save as PNG, GIF, encode to bytes, etc.
Mock Testing
func TestMyWidget(t *testing.T) {
    m := terminal.NewMockTerminal(t, 10, 3)
    defer m.Close()

    m.Feed("echo hello\r\n")

    m.AssertCell(0, 0, 'e')
    m.AssertLine(0, "echo hello")
    m.AssertContains("hello")
    m.AssertCursor(10, 0)
}

Installation

go get github.com/malivvan/terminal

Requires Go 1.25 or later.


Core Concepts

Terminal (Headless)

Terminal is the primary entry point for headless operation. It wraps a Session internally, drives the parser synchronously via Feed, and exposes the screen buffer directly through Cell, String, Lines, Cursor, and ScrollbackLine. No real PTY, no screen, no background goroutines — ideal for tests, fuzzing, CI, WASM, and programmatic automation.

t, _ := terminal.NewTerminal(80, 24)
t.FeedString("\x1b[32mgreen\x1b[0m")
col, row, visible := t.Cursor()
cell := t.Cell(5, 0)         // Cell{Rune:'g', Style:…}

Key methods: Feed, FeedString, HandleEvent, Resize, Size, Cell, String, Lines, Cursor, Output, GetModes, GetDelta, RenderImage, ScrollbackLen, ScrollbackLine, WaitForText, WaitForCursor, WaitForStable, WaitForPattern, ExpectEcho, SendCommandAndWait, AnalyzeScreen, FindPrompt, GetLastOutput, GetErrorLine, Close.

Session (PTY-backed)

Session models a live interactive terminal backed by a PTY subprocess. It processes input through the parser in a background goroutine and emits events (EventRedraw, EventTitle, EventBell, EventClosed, EventPanic, EventClipboard, EventDCS, EventDCSData, EventColour, EventDefaultColour) that you receive via Attach.

s := terminal.New()
s.SetSurface(mySurface)
err := s.Start(exec.Command("bash"))

Key methods: New, NewWithSize, Start, StartWithPty, Write, Resize, HandleEvent, Attach, Detach, Draw, Cursor, String, ScrollBy, ScrollOffset, IsAltScreen, SetSurface, HasSurface, SetOSC8, SetTERM, SetLogger, SetMaxClipboardLen, SetRedrawHandler, GetActiveCharset, GetMargins, GetTabStops, GetCursorStyle, GetDimensions, ClearEventLog, EventLog, GetClipboard, SetClipboard, Close.

Parser

The parser implements a faithful reproduction of Paul Flo Williams' VT500-series terminal state machine. You can use it directly to inspect parsed sequences without driving a full terminal:

p := terminal.NewParser(strings.NewReader("\x1b[31m"))
for {
    seq := p.Next()
    if _, ok := seq.(terminal.EOF); ok {
        break
    }
    switch s := seq.(type) {
    case terminal.CSI:
        fmt.Printf("CSI: final=%q params=%v\n", s.Final, s.Parameters)
    }
}

Sequence types: Print, C0, ESC, CSI, OSC, DCS, DCSData, DCSEndOfData, EOF.

Rendering

The package can rasterise the terminal screen into an *image.RGBA via Render (for Session) or RenderImage (for Terminal). Configure appearance through Options:

opts := terminal.DefaultRenderOptions()
opts.Font = myFont
opts.Scheme = myScheme
opts.BoldAsBright = true
opts.DimFactor = 0.5
opts.RenderCursor = true
opts.Scale = 2

img := t.RenderImage(opts)

Options include: Font, FontBold, FontItalic, FontBoldItalic, CellWidth, CellHeight, Padding, Scale, FgDefault, BgDefault, DimFactor, BoldAsBright, RenderCursor, DrawBoxChars, Scheme, CursorStyle (block, underline, bar).

The renderer handles:

  • Bold, dim, italic, underline, blink, reverse, strikethrough, overline text attributes
  • Bold-as-bright promotion of indexed palette colours (30–37 → 90–97)
  • Dim blending via blendRGBA
  • Italic synthesis via horizontal shear when no italic font is provided
  • Procedural box-drawing characters (lines, corners, tees, crosses) and block elements (full block, upper/lower/left/right halves, quarter shades)
  • Procedural Braille character rendering (U+2800–28FF)
  • Block cursor (inverts cell rectangle), underline cursor, bar cursor
  • Wide CJK characters spanning two cells
Colour Schemes

Override the terminal's palette colours at render time. 8 built-in schemes are available:

Function Name
SchemeDracula() dracula
SchemeNord() nord
SchemeSolarizedDark() solarized-dark
SchemeSolarizedLight() solarized-light
SchemeGruvboxDark() gruvbox-dark
SchemeOneDark() one-dark
SchemeMonokai() monokai
SchemeTangoDark() tango-dark
// Look up by name (case-insensitive, supports aliases)
scheme, ok := terminal.SchemeByName("dracula")

// Or build a custom scheme
scheme := terminal.SchemeSpec{
    Name:       "my-theme",
    Foreground: "#AABBCC",
    Background: "#112233",
    Cursor:     "#FFFFFF",
    Palette:    []string{"#000000", "#FF0000", /* … */},
}.Build()

Apply via Options.Scheme:

opts := terminal.DefaultRenderOptions()
opts.Scheme = terminal.SchemeDracula()
Recording & Replay

Record a session and replay it later, or export to asciinema v2 format:

// Record
t, _ := terminal.NewTerminal(80, 24)
rec := terminal.NewSessionRecorder(t)
rec.FeedString("echo hello\r\n")
rec.Close()

// Export asciinema v2
data, _ := rec.ExportAsciinema()
os.WriteFile("session.cast", data, 0644)

// Export raw JSON for replay
raw, _ := rec.ExportRaw()

// Replay
player, _ := terminal.NewSessionPlayer(raw)
for {
    frame, err := player.Next()
    if err == io.EOF {
        break
    }
    fmt.Printf("[%v] %s\n", frame.Timestamp, frame.Output)
}

// Player API: Next, Current, Seek, Pos, Elapsed, Metadata
Screen Analysis

The Terminal provides AI-oriented helpers that parse the visible screen into semantically classified lines:

lines := t.AnalyzeScreen()
for _, line := range lines {
    // line.Type is one of: LineTypeBlank, LineTypePrompt, LineTypeCommand,
    //                      LineTypeOutput, LineTypeError, LineTypeStatusBar
    fmt.Println(line.Text)
}

// Convenience wrappers:
promptRow := t.FindPrompt()
lastOutput := t.GetLastOutput()
errText, errRow, found := t.GetErrorLine()

Classification heuristics detect shell prompts ($, #, >, %), error keywords (error, fail, fatal, exception, panic, warning), red-foreground cells, and reverse-video status bars (bottom row).

MockTerminal

MockTerminal wraps Terminal with testify-compatible assertion helpers — ideal for unit-testing code that generates ANSI sequences:

func TestMyWidget(t *testing.T) {
    m := terminal.NewMockTerminal(t, 20, 5)
    defer m.Close()

    m.Feed("\x1b[31mERROR\x1b[0m")

    m.AssertCell(0, 0, 'E')
    m.AssertBold(0, 0)          // not bold
    m.AssertItalic(0, 0)        // not italic
    m.AssertUnderline(0, 0)     // not underlined
    m.AssertLine(0, "ERROR               ")  // width-padded
    m.AssertContains("ERROR")
    m.AssertCursor(5, 0)
    m.AssertStyle(0, 0, tcell.StyleDefault.Foreground(tcell.ColorRed))
    m.AssertForeground(0, 0, tcell.ColorRed)
    m.AssertOutput("\x1b[?2004h") // paste-mode enable
}
Delta Tracking

GetDelta returns a ScreenDelta containing only the cells that changed since the last call. Useful for incremental rendering or minimal update detection:

delta := t.GetDelta()
for _, d := range delta.Cells {
    fmt.Printf("(%d,%d): %c\n", d.X, d.Y, d.Cell.Rune)
}
// delta.Clear tells you whether the entire screen was cleared

PTY Support

Sessions are backed by github.com/malivvan/pty: Session.Start starts the command on the pseudo-terminal that module provides.

Platform Build Tag Notes
Linux / Android linux PTY via /dev/ptmx
macOS / iOS darwin BSD-style /dev/ptmx
FreeBSD freebsd BSD PTY
OpenBSD openbsd BSD PTY
NetBSD netbsd BSD PTY
DragonFly BSD dragonfly BSD PTY
Solaris / illumos solaris Solaris PTY
Windows windows ConPTY (CreatePseudoConsole)
Plan 9, AIX, js/wasm plan9, aix, js No pty backend: Session.Start returns pty.ErrUnsupported. Drive a session with StartWithPty and a stream of your own instead — demo 31 bridges a browser that way

Demos

The demos/ directory contains 37 runnable example applications, each demonstrating a specific feature:

Demo Topic
01_basic Minimal headless terminal
02_snapshot Periodic screen snapshots
03_animated_gif Render to animated GIF
04_keys_and_output Keyboard input and output capture
05_hyperlinks_osc8 OSC 8 hyperlink rendering
06_clipboard_osc52 OSC 52 clipboard access
07_scrollback Scrollback buffer navigation
08_mock_testing MockTerminal assertion helpers
09_shell_unix Interactive PTY shell
10_focus_events DECSET 1004 focus reporting
11_multiplex_headless Multiple headless terminals
12_mouse_tracking Mouse event tracking
13_multiplex_shell_unix Multiple PTY shells
14_selector_multiplex Interactive terminal selector
15_mouse_reporter Raw mouse protocol output
16_ai_automation Screen analysis helpers
17_start_with_pty_bridge SSH PTY proxying
18_custom_surface_minimal Custom Screen interface
19_redraw_handler_loop Event-driven redraw loop
20_sync_output_mode DECSET 2026 synchronised output
21_alt_screen_transition Alternate screen buffer
22_resize_preserve_content Resize preserves cells
23_parser_stream_inspector Raw sequence stream inspection
24_sgr_showcase_matrix SGR attribute matrix
25_decsed_decsel_protection Selective erase & protected cells
26_xtwinops_reports XTWINOPS window ops reports
27_mode_probe_dashboard Mode probing dashboard
28_session_record_replay_mock Recording, replay & mock test
29_render_options_fonts Font and colour scheme options
30_windows_conpty_shell Windows ConPTY shell
31_js_wasm_pty_bridge WASM virtual PTY bridge
32_ssh_pty_proxy SSH PTY proxy automation
33_mouse_protocol_compare Mouse protocol comparison
34_scrollback_viewport_ui Scrollback viewport UI
35_error_recovery_panic_event Panic recovery & EventPanic
36_multi_pane_scheduler Multi-pane layout & scheduler
# Run any demo:
cd demos/01_basic && go run .

Documentation

Full API documentation is available at pkg.go.dev/github.com/malivvan/terminal.


License

MIT — see LICENSE. Same license as the original tcell-term.


Acknowledgments

  • Tim Culverhouse — original author of tcell-term (licensed under MIT), which this project forked from at v0.10.0.
  • Paul Flo Williams — designer of the DEC/ANSI parser state machine that this parser implements.
  • The tcell project (github.com/gdamore/tcell) — terminal cell abstraction and event system used throughout this package.
  • Rob Pike — original text/template parser that inspired the concurrency-free state machine design.
  • All contributors and users of the original tcell-term and this fork.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Render

func Render(s *Session, opts Options) *image.RGBA

Render renders the Session's current active screen to a new *image.RGBA. It is safe to call from any goroutine; it takes the Session lock internally. The Session need not have a real Screen attached — it reads directly from the internal cell buffer, which is always kept up-to-date by the parse loop.

func Schemes

func Schemes() []string

Schemes returns the sorted list of built-in colour scheme names.

Types

type C0

type C0 rune

A C0 control code

func (C0) String

func (seq C0) String() string

type CSI

type CSI struct {
	Final        rune
	Intermediate []rune
	Parameters   []int
}

A CSI Sequence

func (CSI) String

func (seq CSI) String() string

type Cell

type Cell struct {
	Rune      rune
	Combining []rune
	Style     tcell.Style
	Width     int
	// Overline indicates the SGR 53 overline decoration is active.
	Overline bool
	// Protected indicates the cell is protected from selective erase (DECSCA).
	Protected bool
	// Wrapped indicates the line continued from the previous row without an
	// explicit newline.
	Wrapped bool
}

Cell is a public, immutable snapshot of a single grid cell.

It mirrors the unexported `cell` type but is safe to expose: callers cannot mutate it to confuse the Session, and it includes the rune width so wide-character handling can be reproduced by tests.

func (Cell) String

func (c Cell) String() string

String returns the rune (with combining marks) as a string. An empty cell renders as a single space, matching Session.String().

type DCS

type DCS struct {
	Final        rune
	Intermediate []rune
	Parameters   []int
}

Sent at the beginning of a DCS passthrough sequence.

type DCSData

type DCSData rune

A rune which is passed through during a DCS passthrough sequence

type DCSEndOfData

type DCSEndOfData struct{}

Sent at the end of a DCS passthrough sequence

type DeltaCell

type DeltaCell struct {
	X, Y  int
	Rune  rune
	Style tcell.Style
}

DeltaCell describes a single cell that has changed since the last delta snapshot.

type Drawable

type Drawable interface {
	Set(x, y int, c color.Color)
}

Drawable is the minimal interface required to render a font — any type that can set the colour of an individual pixel at (x, y). *image.RGBA satisfies this interface out of the box.

type EOF

type EOF struct{}

Sent when the underlying PTY is closed

func (EOF) String

func (seq EOF) String() string

type ESC

type ESC struct {
	Final        rune
	Intermediate []rune
}

An escape sequence with intermediate characters

func (ESC) String

func (seq ESC) String() string

type EventBell

type EventBell struct {
	*EventTerminal
}

EventBell is emitted when BEL is received

type EventClipboard

type EventClipboard struct {
	*EventTerminal
	// contains filtered or unexported fields
}

EventClipboard is emitted when an OSC 52 clipboard sequence is received

func (*EventClipboard) Data

func (ev *EventClipboard) Data() string

func (*EventClipboard) Selection

func (ev *EventClipboard) Selection() string

type EventClosed

type EventClosed struct {
	*EventTerminal
}

EventClosed is emitted when the terminal exits

type EventColour

type EventColour struct {
	*EventTerminal
	Index int
	Value string
}

EventColour is emitted when an OSC 4 sequence changes a palette entry.

type EventDCS

type EventDCS struct {
	*EventTerminal
	Final      rune
	Parameters []int
}

EventDCS is emitted when a DCS (Device Control String) sequence begins. External handlers can use this to implement Sixel rendering, DECRQSS, or other DCS-based protocols.

type EventDCSData

type EventDCSData struct {
	*EventTerminal
	Data rune
}

EventDCSData is emitted for each data rune within a DCS sequence.

type EventDefaultColour

type EventDefaultColour struct {
	*EventTerminal
	IsForeground bool
	Value        string
}

EventDefaultColour is emitted when OSC 10/11 changes the default fg/bg.

type EventLogEntry

type EventLogEntry struct {
	Time     time.Time
	Type     string      // "CSI", "OSC", "C0", "ESC", "ModeSet", "ModeReset", "Title"
	Sequence string      // raw sequence or description
	Args     interface{} // parsed parameters
}

EventLogEntry is a lightweight record of a terminal event suitable for debugging and audit trails. It is stored in a bounded ring-buffer on Session.

type EventMouseMode

type EventMouseMode struct {
	*EventTerminal
	// contains filtered or unexported fields
}

EventMouseMode is emitted when the terminal mouse mode changes

func (*EventMouseMode) Flags

func (ev *EventMouseMode) Flags() []tcell.MouseFlags

type EventPanic

type EventPanic struct {
	*EventTerminal
	Error error
}

type EventRedraw

type EventRedraw struct {
	*EventTerminal
}

EventRedraw is emitted when the terminal requires redrawing

type EventTerminal

type EventTerminal struct {
	// contains filtered or unexported fields
}

EventTerminal is a generic terminal event

func (*EventTerminal) Session

func (ev *EventTerminal) Session() *Session

func (*EventTerminal) When

func (ev *EventTerminal) When() time.Time

type EventTitle

type EventTitle struct {
	*EventTerminal
	// contains filtered or unexported fields
}

EventTitle is emitted when the terminal's title changes

func (*EventTitle) Title

func (ev *EventTitle) Title() string

type Font

type Font struct {
	// contains filtered or unexported fields
}

Font is a simple fixed-width (optionally variable-width) bitmap font. Glyphs are packed as bitfields inside a []uint32 data slice; a charmap maps each rune to its offset within that slice.

func NewFont

func NewFont(w, h uint8, cm map[rune]uint16, d []uint32) *Font

NewFont constructs a Font from the raw character dimensions, charmap and data slice produced by the fontgen tool.

func (*Font) DrawRune

func (p *Font) DrawRune(dr Drawable, x, y int, r rune, clr color.Color) (bool, int)

DrawRune draws a single rune r in colour clr at position (x, y) — the top-left corner of the glyph bounding box — onto dr.

It returns (true, advance) if the rune is present in the font, or (false, fallbackAdvance) when it is not. The caller should add the returned advance (plus spacing) to x before drawing the next rune.

func (*Font) GetHeight

func (p *Font) GetHeight() int

GetHeight returns the character height of the font in pixels.

func (*Font) GetWidth

func (p *Font) GetWidth() int

GetWidth returns the fixed character width of the font in pixels.

func (*Font) MeasureRune

func (p *Font) MeasureRune(r rune) (bool, int)

MeasureRune returns the pixel advance for a single rune without drawing.

func (*Font) SetVariableWidth

func (p *Font) SetVariableWidth(isVar bool)

SetVariableWidth switches between fixed-width and variable-width glyph advance. In variable-width mode only the columns that actually contain set pixels are counted, making proportional-looking text possible.

type Frame

type Frame struct {
	// Timestamp is the time elapsed since recording start.
	Timestamp time.Duration
	// EventType is "input", "output", or "snapshot".
	EventType string
	// Input holds the bytes injected by the automation (for input frames).
	Input []byte
	// Output holds the bytes emitted by the terminal (for output frames).
	Output []byte
	// ScreenSnapshot is an optional periodic screen capture.
	ScreenSnapshot string
}

Frame represents a single timestamped event in a session recording.

type LineType

type LineType int

LineType classifies the semantic role of a screen line.

const (
	// LineTypeUnknown is the default for unclassified lines.
	LineTypeUnknown LineType = iota
	// LineTypePrompt indicates a shell prompt (ends with $, #, >, %).
	LineTypePrompt
	// LineTypeCommand is a line printed immediately after a prompt.
	LineTypeCommand
	// LineTypeOutput is program output.
	LineTypeOutput
	// LineTypeError indicates an error (red colour or error keywords).
	LineTypeError
	// LineTypeStatusBar is a bottom-of-screen inverted line.
	LineTypeStatusBar
	// LineTypeBlank is an empty line.
	LineTypeBlank
)

func (LineType) String

func (lt LineType) String() string

String returns a human-readable name for the line type.

type MockTerminal

type MockTerminal struct {
	*Terminal
	// contains filtered or unexported fields
}

MockTerminal wraps Terminal with assertion helpers commonly needed when writing unit tests for code that emits ANSI/ECMA-48 sequences or for widgets that integrate with the terminal package.

Because Terminal.Feed is synchronous, no Sync/Wait barrier is needed between Feed and assertions.

func NewMockTerminal

func NewMockTerminal(t testingT, width, height int) *MockTerminal

NewMockTerminal creates a MockTerminal wrapping a fresh Terminal of the given dimensions.

func (*MockTerminal) AssertBackground

func (m *MockTerminal) AssertBackground(x, y int, want tcellcolor.Color)

AssertBackground checks that the background colour at (x, y) equals want.

func (*MockTerminal) AssertBold

func (m *MockTerminal) AssertBold(x, y int)

AssertBold checks that the cell at (x, y) has the bold attribute.

func (*MockTerminal) AssertCell

func (m *MockTerminal) AssertCell(x, y int, want rune)

AssertCell checks that the rune at (x, y) equals want.

func (*MockTerminal) AssertCombining

func (m *MockTerminal) AssertCombining(x, y int, want ...rune)

AssertCombining checks that the combining marks at (x, y) match want.

func (*MockTerminal) AssertContains

func (m *MockTerminal) AssertContains(substr string)

AssertContains checks that any visible row contains substr.

func (*MockTerminal) AssertCursor

func (m *MockTerminal) AssertCursor(col, row int)

AssertCursor checks that the cursor is at (col, row) and visible.

func (*MockTerminal) AssertForeground

func (m *MockTerminal) AssertForeground(x, y int, want tcellcolor.Color)

AssertForeground checks that the foreground colour at (x, y) equals want.

func (*MockTerminal) AssertItalic

func (m *MockTerminal) AssertItalic(x, y int)

AssertItalic checks that the cell at (x, y) has the italic attribute.

func (*MockTerminal) AssertLine

func (m *MockTerminal) AssertLine(y int, want string)

AssertLine checks that row y matches want exactly.

func (*MockTerminal) AssertOutput

func (m *MockTerminal) AssertOutput(want string)

AssertOutput drains the Session-to-host output buffer and checks that it equals want. Useful for verifying replies to DA/cursor-position queries or key bytes emitted by SendKey.

func (*MockTerminal) AssertScrollbackLine

func (m *MockTerminal) AssertScrollbackLine(n int, want string)

AssertScrollbackLine checks that scrollback row n matches want.

func (*MockTerminal) AssertStyle

func (m *MockTerminal) AssertStyle(x, y int, want tcell.Style)

AssertStyle checks that the tcell.Style at (x, y) equals want.

func (*MockTerminal) AssertUnderline

func (m *MockTerminal) AssertUnderline(x, y int)

AssertUnderline checks that the cell at (x, y) has the underline attribute.

func (*MockTerminal) Dump

func (m *MockTerminal) Dump() string

Dump returns a human-friendly multi-line string describing the current screen and cursor position. Intended for failure messages.

func (*MockTerminal) Feed

func (m *MockTerminal) Feed(s string) int

Feed writes the given string to the Session. Returns the number of bytes fed. Any error fails the test via Fatalf.

func (*MockTerminal) SendKey

func (m *MockTerminal) SendKey(key tcell.Key, str string, mod tcell.ModMask)

SendKey forwards a synthesized key press to the Session. The emitted byte sequence lands in the output buffer drainable via Output. The str argument carries the rune(s) for printable keys; pass "" for control keys identified by k.

func (*MockTerminal) SendRune

func (m *MockTerminal) SendRune(r rune)

SendRune is a convenience wrapper that synthesizes a printable rune keypress.

func (*MockTerminal) Snapshot

func (m *MockTerminal) Snapshot() string

Snapshot returns the screen as a newline-separated string, useful for golden-file comparisons.

type Modes

type Modes struct {
	// MouseMode is the currently active mouse tracking protocol.
	MouseMode TrackingMode
	// BracketedPaste indicates whether bracketed paste mode is active (DECSET 2004).
	BracketedPaste bool
	// Autowrap indicates whether line wrapping is active (DECAWM, DECSET 7).
	Autowrap bool
	// ReverseVideo indicates whether reverse video mode is active (DECSCNM, DECSET 5).
	ReverseVideo bool
	// FocusEvents indicates whether focus event reporting is active (DECSET 1004).
	FocusEvents bool
	// SynchronizedOutput indicates whether synchronized output is active (DECSET 2026).
	SynchronizedOutput bool
	// OriginMode indicates whether origin mode is active (DECOM, DECSET 6).
	OriginMode bool
	// CursorKeyMode indicates whether application cursor key mode is active (DECCKM, DECSET 1).
	CursorKeyMode bool
	// InsertMode indicates whether insert/replace mode is active (IRM, SM 4).
	InsertMode bool
	// CursorVisible indicates whether the text cursor is visible (DECTCEM, DECSET 25).
	CursorVisible bool
	// AltScreen indicates whether the alternate screen buffer is active.
	AltScreen bool
}

Modes is a public snapshot of the terminal's mode state, suitable for type-safe introspection by automation agents.

type OSC

type OSC struct {
	Payload []rune
}

An OSC sequence. The Payload is the raw runes received, and must be parsed externally

func (OSC) String

func (seq OSC) String() string

type Options

type Options struct {
	// Font is the monospaced font face used to draw characters.
	// Defaults to basicfont.Face7x13 (7×13 bitmap font).
	Font font.Face

	// FontBold, when set, is used for cells with the bold (SGR 1) attribute.
	// If nil, bold is synthesized by drawing the glyph twice with a +1px offset.
	FontBold font.Face

	// FontItalic, when set, is used for cells with the italic (SGR 3) attribute.
	// If nil, italic is synthesized by shearing the glyph.
	FontItalic font.Face

	// FontBoldItalic, when set, is used for cells with both bold and italic.
	FontBoldItalic font.Face

	// CellWidth is the width of a single character cell in pixels.
	// 0 means derive from Font (via GlyphAdvance of a space).
	CellWidth int

	// CellHeight is the height of a single character cell in pixels.
	// 0 means derive from Font metrics.
	CellHeight int

	// FgDefault is the foreground color used when a cell specifies
	// tcellcolor.Default. Defaults to light gray (#CCCCCC).
	FgDefault color.Color

	// BgDefault is the background color used when a cell specifies
	// tcellcolor.Default. Defaults to near-black (#0D0D0D).
	BgDefault color.Color

	// Padding is the number of pixels of empty space added around the
	// terminal content on all sides. Defaults to 8.
	Padding int

	// Scale multiplies all pixel dimensions (cell size, padding, font size).
	// Default 1.  Use 2 or 3 for high-DPI output.
	Scale int

	// RenderCursor, when true, draws a cursor indicator at the current
	// cursor position.
	RenderCursor bool

	// CursorStyle selects the cursor shape: block (default), underline, or bar.
	// CursorStyleBlock/CursorStyleUnderline/CursorStyleBar.  For block cursors,
	// the cell is inverted (fg↔bg) so the glyph remains legible.
	CursorStyle tcell.CursorStyle

	// CursorColour is the colour used for the cursor indicator for underline/bar
	// shapes.  For block cursors, it is ignored (inversion is used instead).
	// Defaults to white.
	CursorColour color.Color

	// Scheme, when non-nil, overrides the RGB values used for the 16 (or up
	// to 256) ANSI palette entries and, when its Foreground/Background/Cursor
	// fields are set, the default foreground, background, and cursor colors.
	// Scheme colors take precedence over FgDefault/BgDefault/CursorColour.
	Scheme *Scheme

	// DimFactor controls how much the foreground is blended toward the
	// background for dim (SGR 2) cells.  0 = no blending (fg unchanged),
	// 1 = fully blended to background.  Default 0.55.
	DimFactor float64

	// BoldAsBright, when true, promotes bold indexed colors (SGR 1 + 30–37)
	// to their bright counterparts (90–97).  Default false.
	BoldAsBright bool

	// DrawBoxChars, when true, renders box-drawing and block-element
	// characters (U+2500–259F), braille (U+2800–28FF), and similar glyphs
	// procedurally instead of via the font.  This ensures perfect tiling
	// without gaps or seams.  Default true.
	DrawBoxChars bool
}

Options configures how terminal content is rendered to an image.

func DefaultRenderOptions

func DefaultRenderOptions() Options

DefaultRenderOptions returns sensible defaults for PNG/GIF rendering.

type Parser

type Parser struct {
	// contains filtered or unexported fields
}

https://vt100.net/emu/dec_ansi_parser

parser is an implementation of Paul Flo Williams' VT500-series parser, as seen [here](https://vt100.net/emu/dec_ansi_parser). The architecture is designed after Rob Pike's text/template parser, with a few modifications.

Many of the comments are directly from Paul Flo Williams description of the parser, licensed under [CC-BY-4.0](https://creativecommons.org/licenses/by/4.0/)

func NewParser

func NewParser(r io.Reader) *Parser

func (*Parser) Next

func (p *Parser) Next() Sequence

Next returns the next Sequence. Sequences will be of the following types:

error          Sent on any parsing error
Print          Print the character to the screen
C0             Execute the C0 code
ESC            Execute the ESC sequence
CSI            Execute the CSI sequence
OSCStart       Signals the start of an OSC sequence
OSCData        Characters from the OSC sequence
OSCEnd         Signals end of the OSC sequence
DCS            Signals start of a DCS sequence, and DCS params/intermediates
DCSData        Raw DCS passthrough data
DCSEndOfData   Signals end of DCS sequence
EOF            Sent at end of input

func (*Parser) SetExitFunc

func (p *Parser) SetExitFunc(f func())

SetExitFunc replaces the parser exit callback. It is primarily useful for tests that need to observe exit handling.

type Player

type Player struct {
	// contains filtered or unexported fields
}

Player replays a previously recorded session.

func NewPlayer

func NewPlayer(data []byte) (*Player, error)

NewPlayer creates a Player from raw exported JSON data.

func NewPlayerFromReader

func NewPlayerFromReader(r io.Reader) (*Player, error)

NewPlayerFromReader reads a raw JSON recording from an io.Reader.

func (*Player) Current

func (p *Player) Current() Frame

Current returns the current frame without advancing.

func (*Player) Elapsed

func (p *Player) Elapsed() time.Duration

Elapsed returns the elapsed playback time.

func (*Player) Metadata

func (p *Player) Metadata() map[string]string

Metadata returns the recording metadata.

func (*Player) Next

func (p *Player) Next() (*Frame, error)

Next advances to the next frame and returns it. Returns io.EOF when all frames have been consumed.

func (*Player) Pos

func (p *Player) Pos() (current, total int)

Pos returns the current frame index and total frame count.

func (*Player) Seek

func (p *Player) Seek(offset time.Duration) error

Seek moves the playback position to the frame at or after the given offset from the start of the recording.

type Print

type Print rune

A character which should be printed to the screen

func (Print) String

func (seq Print) String() string

type Recording

type Recording struct {
	Start    time.Time
	Frames   []Frame
	Metadata map[string]string
	// contains filtered or unexported fields
}

Recording holds a complete recorded terminal session.

func NewRecorder

func NewRecorder(h *Terminal) *Recording

NewRecorder wraps a Terminal terminal and starts recording all input and output events, plus periodic screen snapshots (every second).

func (*Recording) Close

func (r *Recording) Close() error

Close stops the recording and releases the background goroutine.

func (*Recording) ExportAsciinema

func (r *Recording) ExportAsciinema() ([]byte, error)

ExportAsciinema exports the session recording in asciinema v2 JSON format. See https://docs.asciinema.org/manual/asciicast/v2/

func (*Recording) ExportRaw

func (r *Recording) ExportRaw() ([]byte, error)

ExportRaw returns the recording as a JSON array of frames, suitable for replay or analysis.

func (*Recording) Feed

func (r *Recording) Feed(b []byte) (int, error)

Feed records input bytes and feeds them to the underlying terminal. Any output bytes produced by the terminal are also recorded.

func (*Recording) FeedString

func (r *Recording) FeedString(s string) (int, error)

FeedString is a convenience wrapper around Feed.

func (*Recording) Snapshot

func (r *Recording) Snapshot()

Snapshot forces an immediate screen snapshot frame.

type Scheme

type Scheme struct {
	// Name is a human-readable identifier (optional).
	Name string

	// Foreground is the default text colour (used for cells with
	// tcell.ColorDefault foreground). nil falls back to Options.FgDefault.
	Foreground color.Color

	// Background is the default background colour (used for cells with
	// tcell.ColorDefault background and for padding). nil falls back to
	// Options.BgDefault.
	Background color.Color

	// Cursor is the colour of the cursor indicator. nil falls back to
	// Options.CursorColour (or white).
	Cursor color.Color

	// Palette holds up to 256 indexed colours. Index 0-7 are the standard
	// ANSI colours, 8-15 the bright variants, and 16-255 the extended
	// 256-colour cube / greyscale ramp. Entries left nil fall back to
	// tcell's built-in value for that index, so most schemes only need to
	// populate indices 0-15.
	Palette [256]color.Color
}

Scheme defines a customizable terminal colour palette used by the image renderer (Render / Terminal.RenderImage). It overrides the RGB values used for the 16 base ANSI colours (and, optionally, the full 256-colour palette), plus the default foreground, background, and cursor colours.

A Scheme only affects rasterised output; it does not change the tcell.Color values stored in the terminal grid. This mirrors how a real terminal maps palette indices to on-screen RGB at draw time, so the same terminal state can be rendered under different themes.

The zero value is valid but does nothing (all entries nil → fall back to tcell's built-in palette). Construct schemes with SchemeSpec.Build, one of the built-in Scheme* constructors, or by setting fields directly.

func SchemeByName

func SchemeByName(name string) (*Scheme, bool)

SchemeByName returns a freshly built built-in scheme by name (case-insensitive), or (nil, false) if no such scheme exists. Common aliases are accepted.

func (*Scheme) Color

func (s *Scheme) Color(i int) (color.Color, bool)

Color returns the RGB override for palette index i (0-255), or (nil, false) if the scheme does not override that index.

type SchemeSpec

type SchemeSpec struct {
	Name       string   `json:"name,omitempty"`
	Foreground string   `json:"foreground,omitempty"`
	Background string   `json:"background,omitempty"`
	Cursor     string   `json:"cursor,omitempty"`
	Palette    []string `json:"palette,omitempty"` // index-ordered, up to 256 entries
}

SchemeSpec is a string-based (hex "#RRGGBB") description of a colour scheme, convenient for configuration files and JSON. Empty fields are left unset (nil) on the built Scheme. Build converts it to a Scheme.

func (SchemeSpec) Build

func (spec SchemeSpec) Build() *Scheme

Build converts the spec into a *Scheme. Invalid or empty hex strings become nil entries (falling back to defaults at render time).

type Screen

type Screen interface {
	// SetContent is used to update the content of the Screen at the given
	// location.
	SetContent(x int, y int, ch rune, comb []rune, style tcell.Style)

	// Size represents the visible size.
	Size() (int, int)
}

Screen represents a logical view on an area. It uses a subset of methods from a tcell.Screen or a views.View, in order to be a more broad implementation. Both a Screen and a View are also a Screen

type ScreenDelta

type ScreenDelta struct {
	Changed       []DeltaCell
	CursorChanged bool
	CursorCol     int
	CursorRow     int
	CursorVisible bool
}

ScreenDelta holds the set of cells that changed since the last call to GetDelta, plus optional cursor change info.

type ScreenLine

type ScreenLine struct {
	Text   string
	Styles []tcell.Style
	Type   LineType
}

ScreenLine is a single row of the screen annotated with semantic metadata.

type Sequence

type Sequence interface{}

Sequence is the generic data type of items emitted from the parser. These can be control sequences, escape sequences, or printable characters.

type Session

type Session struct {
	Logger *log.Logger
	// If true, OSC8 enables the output of OSC8 strings. Otherwise, any OSC8
	// sequences will be stripped
	OSC8 bool
	// Set the TERM environment variable to be passed to the command's
	// environment. If not set, xterm-256color will be used
	TERM string
	// MaxClipboardLen is the maximum size in bytes of OSC 52 clipboard
	// data that will be forwarded via EventClipboard. Data exceeding
	// this limit is silently dropped and a warning is logged. Default
	// is 1 MB (1 << 20). Set to 0 to disable the limit.
	MaxClipboardLen int
	// contains filtered or unexported fields
}

Session models a virtual terminal

func New

func New() *Session

func NewWithSize

func NewWithSize(width, height int) *Session

NewWithSize is a convenience constructor equivalent to

s := New()
s.Resize(width, height)

It returns a Session with the given dimensions already applied, so callers can start printing or feeding output without an explicit resize step.

func (*Session) Attach

func (s *Session) Attach(fn func(ev tcell.Event))

func (*Session) ClearEventLog

func (s *Session) ClearEventLog()

ClearEventLog empties the event log. Safe to call from any goroutine.

func (*Session) Close

func (s *Session) Close()

func (*Session) Cursor

func (s *Session) Cursor() (int, int, tcell.CursorStyle, bool)

row, col, style, vis

func (*Session) Detach

func (s *Session) Detach()

func (*Session) Draw

func (s *Session) Draw()

func (*Session) EventLog

func (s *Session) EventLog(limit int) []EventLogEntry

EventLog returns a copy of the most recent sequence/mode event entries, up to limit. If limit <= 0, all entries are returned. Safe to call from any goroutine.

func (*Session) GetActiveCharset

func (s *Session) GetActiveCharset() string

GetActiveCharset returns the currently selected charset designator. The returned string is one of "G0", "G1", "G2", or "G3". Safe to call from any goroutine.

func (*Session) GetClipboard

func (s *Session) GetClipboard(selection string) (string, bool)

GetClipboard returns the decoded clipboard content for the given selection (typically "c" for system or "p" for primary), or ("", false) if no data has been received.

func (*Session) GetCursorStyle

func (s *Session) GetCursorStyle() tcell.CursorStyle

GetCursorStyle returns the current cursor shape (block, underline, bar). Safe to call from any goroutine.

func (*Session) GetDimensions

func (s *Session) GetDimensions() (width, height int)

GetDimensions returns the current terminal dimensions as (width, height). Safe to call from any goroutine.

func (*Session) GetMargins

func (s *Session) GetMargins() (top, bottom, left, right int)

GetMargins returns the current scroll region margins as (top, bottom, left, right). Safe to call from any goroutine.

func (*Session) GetModes

func (s *Session) GetModes() Modes

GetModes returns a snapshot of the current terminal mode state. Safe to call from any goroutine.

func (*Session) GetTabStops

func (s *Session) GetTabStops() []int

GetTabStops returns the current set of tab stop column positions. The returned slice is a copy; modifying it does not affect the terminal. Safe to call from any goroutine.

func (*Session) HandleEvent

func (s *Session) HandleEvent(e tcell.Event) bool

func (*Session) HasSurface

func (s *Session) HasSurface() bool

HasSurface reports whether a Screen has been attached to the Session. It is safe to call from any goroutine.

func (*Session) IsAltScreen

func (s *Session) IsAltScreen() bool

IsAltScreen reports whether the alternate screen buffer is currently active (e.g. while running vim, less, htop). Safe to call from any goroutine.

func (*Session) Resize

func (s *Session) Resize(w int, h int)

func (*Session) ScrollBy

func (s *Session) ScrollBy(n int)

ScrollBy shifts the viewport by n lines relative to its current position. Positive n scrolls toward older history (up); negative n scrolls toward the live screen (down). The offset is clamped to [0, len(scrollback)]. Safe to call from any goroutine.

func (*Session) ScrollOffset

func (s *Session) ScrollOffset() int

ScrollOffset returns the number of lines the viewport is currently scrolled back from the live screen (0 means live). Safe to call from any goroutine.

func (*Session) SendSignal

func (s *Session) SendSignal(sig os.Signal) error

SendSignal sends an OS signal to the underlying process, if one is running. Returns an error if no process is attached or the signal cannot be delivered.

func (*Session) SetClipboard

func (s *Session) SetClipboard(selection, data string)

SetClipboard stores clipboard data directly without going through OSC 52. Useful for testing or programmatic injection.

func (*Session) SetLogger

func (s *Session) SetLogger(logger *log.Logger)

SetLogger sets the logger used for parse errors and diagnostics. It is safe to call from any goroutine.

func (*Session) SetMaxClipboardLen

func (s *Session) SetMaxClipboardLen(n int)

SetMaxClipboardLen configures the maximum accepted length in bytes of an OSC 52 clipboard payload. Values <= 0 disable the limit and forward all clipboard data as-is. It is safe to call from any goroutine.

func (*Session) SetOSC8

func (s *Session) SetOSC8(enabled bool)

SetOSC8 sets whether OSC8 hyperlink sequences are processed. It is safe to call from any goroutine.

func (*Session) SetRedrawHandler

func (s *Session) SetRedrawHandler(fn func())

SetRedrawHandler registers a callback that is called when the terminal content has changed and should be re-rendered. The callback is invoked from the terminal's internal parse goroutine for each EventRedraw and should not block — hand off to a channel and process in your main loop. This is a lighter alternative to Attach when you only need to know when to call Draw().

func (*Session) SetSurface

func (s *Session) SetSurface(srf Screen)

func (*Session) SetTERM

func (s *Session) SetTERM(term string)

SetTERM sets the TERM environment variable that will be passed to the command's environment. It is safe to call from any goroutine but must be called before Start().

func (*Session) Start

func (s *Session) Start(cmd *exec.Cmd) error

Start starts the terminal with the specified command. Start returns when the command has been successfully started.

func (*Session) StartWithPty

func (s *Session) StartWithPty(p io.ReadWriteCloser) error

StartWithPty starts the terminal using an already-opened pty (or any io.ReadWriteCloser). No subprocess is spawned; the caller is responsible for driving the slave side of the pty. StartWithPty returns immediately.

func (*Session) String

func (s *Session) String() string

func (*Session) Write

func (s *Session) Write(p []byte) (int, error)

Write sends raw bytes to the PTY input. It is used for programmatic input injection (recording playback, tests, etc.). Returns an error if the Session has not been started yet.

type Terminal

type Terminal struct {
	// contains filtered or unexported fields
}

Terminal drives a Session entirely in-process without any tcell.Screen. It is intended for tests, fuzzing, snapshot-driven assertions, and any environment where a real renderer is unavailable (such as js/wasm).

Unlike Session.Start / Session.StartWithPty, the parser is driven synchronously by Feed: when Feed returns, all input bytes have been fully processed and the screen reflects the final state. There is no parser goroutine and no need to wait for redraw events.

The zero value is not usable; construct via NewTerminal.

func NewTerminal

func NewTerminal(width, height int) (*Terminal, error)

NewTerminal returns a Terminal terminal of the given dimensions.

func (*Terminal) AnalyzeScreen

func (t *Terminal) AnalyzeScreen() []ScreenLine

AnalyzeScreen scans the visible screen and classifies each line by its likely semantic role. It uses heuristics: terminal prompt patterns, colour, and keyword matching.

func (*Terminal) Cell

func (t *Terminal) Cell(x, y int) Cell

Cell returns a snapshot of the cell at the given coordinates. Out of range coordinates yield a zero Cell.

func (*Terminal) Close

func (t *Terminal) Close() error

Close releases resources. Subsequent calls to Feed return io.ErrClosedPipe. Safe to call multiple times.

func (*Terminal) Cursor

func (t *Terminal) Cursor() (col, row int, visible bool)

Cursor returns (col, row, visible).

func (*Terminal) ExpectEcho

func (t *Terminal) ExpectEcho(input string, timeout time.Duration) (echoed string, ok bool)

ExpectEcho sends input bytes to the terminal and waits for them to appear in the output buffer (simulating local echo). Returns the echoed bytes or an error on timeout. Useful for verifying that a PTY is responding correctly.

func (*Terminal) Feed

func (t *Terminal) Feed(b []byte) (int, error)

Feed processes input bytes synchronously: when it returns, every rune has been parsed and the screen has been painted to the buffer surface. Subsequent calls to Cell, Lines, String, etc. observe the resulting state.

func (*Terminal) FeedString

func (t *Terminal) FeedString(s string) (int, error)

FeedString is a convenience wrapper around Feed.

func (*Terminal) FindPrompt

func (t *Terminal) FindPrompt() int

FindPrompt locates the last shell prompt on the screen. Returns the line index or -1 if not found.

func (*Terminal) GetDelta

func (t *Terminal) GetDelta() ScreenDelta

GetDelta returns only the cells that have changed since the last call. On first call, the entire screen is returned as changed.

func (*Terminal) GetErrorLine

func (t *Terminal) GetErrorLine() (text string, line int, ok bool)

GetErrorLine returns the first error-classified line, or ("", -1, false).

func (*Terminal) GetLastOutput

func (t *Terminal) GetLastOutput() string

GetLastOutput returns the text output from the last prompt to the current cursor position.

func (*Terminal) GetModes

func (t *Terminal) GetModes() Modes

GetModes returns a snapshot of the current terminal mode state. See Session.GetModes for details.

func (*Terminal) HandleEvent

func (t *Terminal) HandleEvent(ev tcell.Event) bool

HandleEvent forwards a tcell.Event (key/mouse/paste/focus) to the Session, exactly as the Terminal widget does. The corresponding bytes are captured in the output buffer, accessible via Output.

func (*Terminal) Lines

func (t *Terminal) Lines() []string

Lines returns the visible screen as a slice of strings, one per row.

func (*Terminal) Output

func (t *Terminal) Output() []byte

Output returns and clears the bytes the Session has written back through its pty side (replies to DA/cursor reports, OSC52 echoes, key bytes from HandleEvent, etc.).

func (*Terminal) RenderImage

func (t *Terminal) RenderImage(opts Options) *image.RGBA

RenderImage renders the Terminal terminal's current screen state to a new *image.RGBA using the provided options. It is safe to call from any goroutine.

func (*Terminal) Resize

func (t *Terminal) Resize(width, height int)

Resize changes the headless terminal's dimensions and propagates the change to the underlying Session.

func (*Terminal) ScrollbackLen

func (t *Terminal) ScrollbackLen() int

ScrollbackLen returns the number of lines currently saved in the scrollback buffer. Scrollback is only populated for the primary screen.

func (*Terminal) ScrollbackLine

func (t *Terminal) ScrollbackLine(n int) (string, bool)

ScrollbackLine returns the content of scrollback row n as a string, or ("", false) if n is out of range.

func (*Terminal) SendCommandAndWait

func (t *Terminal) SendCommandAndWait(cmd string, prompts []string, timeout time.Duration) (output string, err error)

SendCommandAndWait is a high-level convenience for shell automation: it writes a command followed by Enter, waits for the echo and the prompt to reappear, and returns the accumulated output.

func (*Terminal) Session

func (t *Terminal) Session() *Session

Session exposes the underlying Session for advanced configuration (logger, TERM, OSC8, custom event handler, etc.). The Terminal instance retains ownership; callers must not call Session.Close directly — use Terminal.Close.

func (*Terminal) Size

func (t *Terminal) Size() (int, int)

Size returns the current (width, height).

func (*Terminal) String

func (t *Terminal) String() string

String returns the visible screen as a newline-separated string, matching Session.String().

func (*Terminal) WaitForCursor

func (t *Terminal) WaitForCursor(col, row int, timeout time.Duration) error

WaitForCursor blocks until the cursor reaches (col, row), or times out.

func (*Terminal) WaitForPattern

func (t *Terminal) WaitForPattern(re *regexp.Regexp, timeout time.Duration) (line string, y int, err error)

WaitForPattern blocks until a line on the visible screen matches re, returning the line text, row index, or an error on timeout.

func (*Terminal) WaitForStable

func (t *Terminal) WaitForStable(quietTime, maxWait time.Duration) error

WaitForStable blocks until the screen has not changed for quietTime, or until maxWait elapses. Useful for waiting for long-running commands to finish producing output.

func (*Terminal) WaitForText

func (t *Terminal) WaitForText(text string, timeout time.Duration) (col, row int, err error)

WaitForText blocks until text appears anywhere on the visible screen, returning the (col, row) of the first match or an error on timeout. The search checks all visible lines on each poll tick.

type TrackingMode

type TrackingMode int

TrackingMode identifies which mouse protocol is currently active.

const (
	// MouseModeNone indicates no mouse tracking mode is active.
	MouseModeNone TrackingMode = iota
	// MouseModeX10 indicates X10 mouse compatibility (DECSET 9).
	MouseModeX10
	// MouseModeVT200 indicates basic button tracking (DECSET 1000).
	MouseModeVT200
	// MouseModeVT200Drag indicates drag tracking (DECSET 1002).
	MouseModeVT200Drag
	// MouseModeVT200Motion indicates all-motion tracking (DECSET 1003).
	MouseModeVT200Motion
	// MouseModeSGR indicates SGR extended mouse encoding (DECSET 1006).
	MouseModeSGR
	// MouseModeUTF8 indicates UTF-8 mouse encoding (DECSET 1005).
	MouseModeUTF8
	// MouseModeURXVT indicates urxvt extended mouse encoding (DECSET 1015).
	MouseModeURXVT
)

func (TrackingMode) String

func (m TrackingMode) String() string

String returns a human-readable name for the mouse tracking mode.

Directories

Path Synopsis
demos
01_basic command
Package main demonstrates the simplest headless usage of the terminal package: create a Terminal Session, feed some bytes into it, and inspect the resulting screen state.
Package main demonstrates the simplest headless usage of the terminal package: create a Terminal Session, feed some bytes into it, and inspect the resulting screen state.
02_snapshot command
Package main renders the current terminal state to a PNG file.
Package main renders the current terminal state to a PNG file.
03_animated_gif command
Package main captures a sequence of terminal frames and encodes them as an animated GIF.
Package main captures a sequence of terminal frames and encodes them as an animated GIF.
04_keys_and_output command
Package main demonstrates sending synthesized key events into a Terminal Session and reading the bytes it emits back through the PTY.
Package main demonstrates sending synthesized key events into a Terminal Session and reading the bytes it emits back through the PTY.
05_hyperlinks_osc8 command
Package main demonstrates OSC 8 hyperlink ingestion.
Package main demonstrates OSC 8 hyperlink ingestion.
06_clipboard_osc52 command
Package main shows OSC 52 clipboard events being surfaced via the event handler.
Package main shows OSC 52 clipboard events being surfaced via the event handler.
07_scrollback command
Package main demonstrates the scrollback ring buffer and viewport control via ScrollBy / ScrollOffset.
Package main demonstrates the scrollback ring buffer and viewport control via ScrollBy / ScrollOffset.
08_mock_testing command
Package main shows the MockTerminal helper being driven the same way a unit test would drive it.
Package main shows the MockTerminal helper being driven the same way a unit test would drive it.
09_shell_unix command
Package main runs /bin/sh inside a real PTY, renders the terminal to a tcell.Screen, and forwards key/mouse events until the shell exits.
Package main runs /bin/sh inside a real PTY, renders the terminal to a tcell.Screen, and forwards key/mouse events until the shell exits.
10_focus_events command
Package main enables DECSET 1004 focus event reporting and shows the byte sequences the Session emits when tcell focus events are delivered.
Package main enables DECSET 1004 focus event reporting and shows the byte sequences the Session emits when tcell focus events are delivered.
11_multiplex_headless command
Package main demonstrates a "headless terminal multiplexer": four independent Terminal VTs each render into their own image, and the four images are composited into a single 2x2 tiled PNG.
Package main demonstrates a "headless terminal multiplexer": four independent Terminal VTs each render into their own image, and the four images are composited into a single 2x2 tiled PNG.
12_mouse_tracking command
Package main showcases how DECSET mouse tracking modes interact with tcell mouse events fed through HandleEvent.
Package main showcases how DECSET mouse tracking modes interact with tcell mouse events fed through HandleEvent.
13_multiplex_shell_unix command
Package main is a compact side-by-side shell multiplexer inspired by tmux.
Package main is a compact side-by-side shell multiplexer inspired by tmux.
14_selector_multiplex command
Package main runs three headless VTs concurrently, feeds each of them a ticker output on its own goroutine, and periodically composites their visible screen state side by side into stdout for five seconds.
Package main runs three headless VTs concurrently, feeds each of them a ticker output on its own goroutine, and periodically composites their visible screen state side by side into stdout for five seconds.
15_mouse_reporter command
Package main is a live inspector: it opens a tcell.Screen, hands every mouse event to a Terminal Session that has SGR mouse mode enabled, and prints the byte sequence the Session would forward to a running application in a status line at the bottom of the screen.
Package main is a live inspector: it opens a tcell.Screen, hands every mouse event to a Terminal Session that has SGR mouse mode enabled, and prints the byte sequence the Session would forward to a running application in a status line at the bottom of the screen.
16_ai_automation command
Package main AI agent automation patterns with terminal.
Package main AI agent automation patterns with terminal.
17_start_with_pty_bridge command
Package main shows how to drive a Session with StartWithPty and a custom io.ReadWriteCloser instead of spawning a subprocess.
Package main shows how to drive a Session with StartWithPty and a custom io.ReadWriteCloser instead of spawning a subprocess.
18_custom_surface_minimal command
Package main proves the renderer is backend-independent: the Session only needs a Screen with two methods (SetContent + Size).
Package main proves the renderer is backend-independent: the Session only needs a Screen with two methods (SetContent + Size).
19_redraw_handler_loop command
Package main contrasts the two ways to learn when a terminal needs repainting:
Package main contrasts the two ways to learn when a terminal needs repainting:
20_sync_output_mode command
Package main demonstrates DECSET 2026 (synchronized output).
Package main demonstrates DECSET 2026 (synchronized output).
21_alt_screen_transition command
Package main demonstrates the alternate-screen transition triggered by DECSET 1049 (?1049h / ?1049l).
Package main demonstrates the alternate-screen transition triggered by DECSET 1049 (?1049h / ?1049l).
22_resize_preserve_content command
Package main visualizes the resize copy-preservation semantics of the VT.
Package main visualizes the resize copy-preservation semantics of the VT.
23_parser_stream_inspector command
Package main uses terminal.NewParser directly to inspect the Sequence stream a byte buffer decodes into.
Package main uses terminal.NewParser directly to inspect the Sequence stream a byte buffer decodes into.
24_sgr_showcase_matrix command
Package main renders a full SGR style/colour matrix to a PNG and prints a text summary.
Package main renders a full SGR style/colour matrix to a PNG and prints a text summary.
25_decsed_decsel_protection command
Package main demonstrates DECSCA character protection together with the selective erase operations DECSED (CSI ? Ps J) and DECSEL (CSI ? Ps K).
Package main demonstrates DECSCA character protection together with the selective erase operations DECSED (CSI ? Ps J) and DECSEL (CSI ? Ps K).
26_xtwinops_reports command
Package main issues XTWINOPS window queries (CSI 14 t, CSI 18 t) plus a few related reports and inspects the byte sequences the terminal emits in response.
Package main issues XTWINOPS window queries (CSI 14 t, CSI 18 t) plus a few related reports and inspects the byte sequences the terminal emits in response.
27_mode_probe_dashboard command
Package main is a live dashboard of terminal mode state.
Package main is a live dashboard of terminal mode state.
28_session_record_replay_mock command
Package main shows a minimal record/replay workflow built on the current public APIs: a Recording captures everything fed to a Terminal terminal, ExportRaw serializes it, and a Player replays the frames into a fresh terminal so the final screen is reproduced exactly.
Package main shows a minimal record/replay workflow built on the current public APIs: a Recording captures everything fed to a Terminal terminal, ExportRaw serializes it, and a Player replays the frames into a fresh terminal so the final screen is reproduced exactly.
29_render_options_fonts command
Package main compares several Options configurations side-by-side by rendering the same terminal content with different padding, cell sizes, cursor rendering and default colours.
Package main compares several Options configurations side-by-side by rendering the same terminal content with different padding, cell sizes, cursor rendering and default colours.
32_ssh_pty_proxy command
Package main relays a remote shell over SSH into a local TERMINAL terminal.
Package main relays a remote shell over SSH into a local TERMINAL terminal.
33_mouse_protocol_compare command
Package main compares the byte sequences different mouse-reporting protocols emit for the same input events.
Package main compares the byte sequences different mouse-reporting protocols emit for the same input events.
34_scrollback_viewport_ui command
Package main is a scripted walk-through of scrollback paging and search over a large volume of output.
Package main is a scripted walk-through of scrollback paging and search over a large volume of output.
35_error_recovery_panic_event command
Package main demonstrates the terminal's panic-recovery path.
Package main demonstrates the terminal's panic-recovery path.
36_multi_pane_scheduler command
Package main demonstrates fair, deterministic scheduling across several independent Terminal terminals, each advancing on its own logical clock.
Package main demonstrates fair, deterministic scheduling across several independent Terminal terminals, each advancing on its own logical clock.

Jump to

Keyboard shortcuts

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