Documentation
¶
Index ¶
- func Render(s *Session, opts Options) *image.RGBA
- func Schemes() []string
- type C0
- type CSI
- type Cell
- type DCS
- type DCSData
- type DCSEndOfData
- type DeltaCell
- type Drawable
- type EOF
- type ESC
- type EventBell
- type EventClipboard
- type EventClosed
- type EventColour
- type EventDCS
- type EventDCSData
- type EventDefaultColour
- type EventLogEntry
- type EventMouseMode
- type EventPanic
- type EventRedraw
- type EventTerminal
- type EventTitle
- type Font
- type Frame
- type LineType
- type MockTerminal
- func (m *MockTerminal) AssertBackground(x, y int, want tcellcolor.Color)
- func (m *MockTerminal) AssertBold(x, y int)
- func (m *MockTerminal) AssertCell(x, y int, want rune)
- func (m *MockTerminal) AssertCombining(x, y int, want ...rune)
- func (m *MockTerminal) AssertContains(substr string)
- func (m *MockTerminal) AssertCursor(col, row int)
- func (m *MockTerminal) AssertForeground(x, y int, want tcellcolor.Color)
- func (m *MockTerminal) AssertItalic(x, y int)
- func (m *MockTerminal) AssertLine(y int, want string)
- func (m *MockTerminal) AssertOutput(want string)
- func (m *MockTerminal) AssertScrollbackLine(n int, want string)
- func (m *MockTerminal) AssertStyle(x, y int, want tcell.Style)
- func (m *MockTerminal) AssertUnderline(x, y int)
- func (m *MockTerminal) Dump() string
- func (m *MockTerminal) Feed(s string) int
- func (m *MockTerminal) SendKey(key tcell.Key, str string, mod tcell.ModMask)
- func (m *MockTerminal) SendRune(r rune)
- func (m *MockTerminal) Snapshot() string
- type Modes
- type OSC
- type Options
- type Parser
- type Player
- type Print
- type Recording
- type Scheme
- type SchemeSpec
- type Screen
- type ScreenDelta
- type ScreenLine
- type Sequence
- type Session
- func (s *Session) Attach(fn func(ev tcell.Event))
- func (s *Session) ClearEventLog()
- func (s *Session) Close()
- func (s *Session) Cursor() (int, int, tcell.CursorStyle, bool)
- func (s *Session) Detach()
- func (s *Session) Draw()
- func (s *Session) EventLog(limit int) []EventLogEntry
- func (s *Session) GetActiveCharset() string
- func (s *Session) GetClipboard(selection string) (string, bool)
- func (s *Session) GetCursorStyle() tcell.CursorStyle
- func (s *Session) GetDimensions() (width, height int)
- func (s *Session) GetMargins() (top, bottom, left, right int)
- func (s *Session) GetModes() Modes
- func (s *Session) GetTabStops() []int
- func (s *Session) HandleEvent(e tcell.Event) bool
- func (s *Session) HasSurface() bool
- func (s *Session) IsAltScreen() bool
- func (s *Session) Resize(w int, h int)
- func (s *Session) ScrollBy(n int)
- func (s *Session) ScrollOffset() int
- func (s *Session) SendSignal(sig os.Signal) error
- func (s *Session) SetClipboard(selection, data string)
- func (s *Session) SetLogger(logger *log.Logger)
- func (s *Session) SetMaxClipboardLen(n int)
- func (s *Session) SetOSC8(enabled bool)
- func (s *Session) SetRedrawHandler(fn func())
- func (s *Session) SetSurface(srf Screen)
- func (s *Session) SetTERM(term string)
- func (s *Session) Start(cmd *exec.Cmd) error
- func (s *Session) StartWithPty(p io.ReadWriteCloser) error
- func (s *Session) String() string
- func (s *Session) Write(p []byte) (int, error)
- type Terminal
- func (t *Terminal) AnalyzeScreen() []ScreenLine
- func (t *Terminal) Cell(x, y int) Cell
- func (t *Terminal) Close() error
- func (t *Terminal) Cursor() (col, row int, visible bool)
- func (t *Terminal) ExpectEcho(input string, timeout time.Duration) (echoed string, ok bool)
- func (t *Terminal) Feed(b []byte) (int, error)
- func (t *Terminal) FeedString(s string) (int, error)
- func (t *Terminal) FindPrompt() int
- func (t *Terminal) GetDelta() ScreenDelta
- func (t *Terminal) GetErrorLine() (text string, line int, ok bool)
- func (t *Terminal) GetLastOutput() string
- func (t *Terminal) GetModes() Modes
- func (t *Terminal) HandleEvent(ev tcell.Event) bool
- func (t *Terminal) Lines() []string
- func (t *Terminal) Output() []byte
- func (t *Terminal) RenderImage(opts Options) *image.RGBA
- func (t *Terminal) Resize(width, height int)
- func (t *Terminal) ScrollbackLen() int
- func (t *Terminal) ScrollbackLine(n int) (string, bool)
- func (t *Terminal) SendCommandAndWait(cmd string, prompts []string, timeout time.Duration) (output string, err error)
- func (t *Terminal) Session() *Session
- func (t *Terminal) Size() (int, int)
- func (t *Terminal) String() string
- func (t *Terminal) WaitForCursor(col, row int, timeout time.Duration) error
- func (t *Terminal) WaitForPattern(re *regexp.Regexp, timeout time.Duration) (line string, y int, err error)
- func (t *Terminal) WaitForStable(quietTime, maxWait time.Duration) error
- func (t *Terminal) WaitForText(text string, timeout time.Duration) (col, row int, err error)
- type TrackingMode
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Render ¶
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.
Types ¶
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.
type Drawable ¶
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 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 ¶
NewFont constructs a Font from the raw character dimensions, charmap and data slice produced by the fontgen tool.
func (*Font) DrawRune ¶
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) MeasureRune ¶
MeasureRune returns the pixel advance for a single rune without drawing.
func (*Font) SetVariableWidth ¶
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 )
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 ¶
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
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 (*Parser) Next ¶
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 NewPlayerFromReader ¶
NewPlayerFromReader reads a raw JSON recording from an io.Reader.
func (*Player) Next ¶
Next advances to the next frame and returns it. Returns io.EOF when all frames have been consumed.
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 ¶
NewRecorder wraps a Terminal terminal and starts recording all input and output events, plus periodic screen snapshots (every second).
func (*Recording) ExportAsciinema ¶
ExportAsciinema exports the session recording in asciinema v2 JSON format. See https://docs.asciinema.org/manual/asciicast/v2/
func (*Recording) ExportRaw ¶
ExportRaw returns the recording as a JSON array of frames, suitable for replay or analysis.
func (*Recording) Feed ¶
Feed records input bytes and feeds them to the underlying terminal. Any output bytes produced by the terminal are also recorded.
func (*Recording) FeedString ¶
FeedString is a convenience wrapper around Feed.
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 ¶
SchemeByName returns a freshly built built-in scheme by name (case-insensitive), or (nil, false) if no such scheme exists. Common aliases are accepted.
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 ¶
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 NewWithSize ¶
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) ClearEventLog ¶
func (s *Session) ClearEventLog()
ClearEventLog empties the event log. Safe to call from any goroutine.
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 ¶
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 ¶
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 ¶
GetDimensions returns the current terminal dimensions as (width, height). Safe to call from any goroutine.
func (*Session) GetMargins ¶
GetMargins returns the current scroll region margins as (top, bottom, left, right). Safe to call from any goroutine.
func (*Session) GetModes ¶
GetModes returns a snapshot of the current terminal mode state. Safe to call from any goroutine.
func (*Session) GetTabStops ¶
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) HasSurface ¶
HasSurface reports whether a Screen has been attached to the Session. It is safe to call from any goroutine.
func (*Session) IsAltScreen ¶
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) ScrollBy ¶
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 ¶
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 ¶
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 ¶
SetClipboard stores clipboard data directly without going through OSC 52. Useful for testing or programmatic injection.
func (*Session) SetLogger ¶
SetLogger sets the logger used for parse errors and diagnostics. It is safe to call from any goroutine.
func (*Session) SetMaxClipboardLen ¶
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 ¶
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 (*Session) SetTERM ¶
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 ¶
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.
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 ¶
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 ¶
Cell returns a snapshot of the cell at the given coordinates. Out of range coordinates yield a zero Cell.
func (*Terminal) Close ¶
Close releases resources. Subsequent calls to Feed return io.ErrClosedPipe. Safe to call multiple times.
func (*Terminal) ExpectEcho ¶
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 ¶
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 ¶
FeedString is a convenience wrapper around Feed.
func (*Terminal) FindPrompt ¶
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 ¶
GetErrorLine returns the first error-classified line, or ("", -1, false).
func (*Terminal) GetLastOutput ¶
GetLastOutput returns the text output from the last prompt to the current cursor position.
func (*Terminal) GetModes ¶
GetModes returns a snapshot of the current terminal mode state. See Session.GetModes for details.
func (*Terminal) HandleEvent ¶
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) Output ¶
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 ¶
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 ¶
Resize changes the headless terminal's dimensions and propagates the change to the underlying Session.
func (*Terminal) ScrollbackLen ¶
ScrollbackLen returns the number of lines currently saved in the scrollback buffer. Scrollback is only populated for the primary screen.
func (*Terminal) ScrollbackLine ¶
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 ¶
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) String ¶
String returns the visible screen as a newline-separated string, matching Session.String().
func (*Terminal) WaitForCursor ¶
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 ¶
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 ¶
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.
Source Files
¶
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. |
|
30_windows_conpty_shell
command
|
|
|
31_js_wasm_pty_bridge
command
|
|
|
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. |