Documentation
¶
Overview ¶
Package headlessterm provides a headless VT220-compatible terminal emulator.
This package emulates a terminal without any display, making it ideal for:
- Testing terminal applications without a GUI
- Building terminal multiplexers and recorders
- Creating terminal-based web applications
- Automated testing of CLI tools
- Screen scraping and automation
Quick Start ¶
Create a terminal and write ANSI sequences to it:
term := headlessterm.New()
term.WriteString("\x1b[31mHello \x1b[32mWorld\x1b[0m!")
fmt.Println(term.String()) // "Hello World!"
Architecture ¶
The package is organized around these core types:
- Terminal: The main emulator that processes ANSI sequences
- Buffer: A 2D grid of cells with scrollback support
- Cell: A single character with colors and attributes
- Cursor: Tracks position and rendering style
Terminal ¶
Terminal is the main entry point. It implements io.Writer so you can write raw bytes containing ANSI escape sequences:
term := headlessterm.New(
headlessterm.WithSize(24, 80), // 24 rows, 80 columns
headlessterm.WithScrollback(storage), // Enable scrollback
headlessterm.WithResponse(ptyWriter), // Handle terminal responses
)
// Process output from a command
cmd := exec.Command("ls", "-la", "--color")
cmd.Stdout = term
cmd.Run()
// Read the result
for row := 0; row < term.Rows(); row++ {
fmt.Println(term.LineContent(row))
}
Dual Buffers ¶
Terminal maintains two buffers:
- Primary buffer: Normal mode with optional scrollback storage
- Alternate buffer: Used by full-screen apps (vim, less, htop), no scrollback
Applications switch buffers via ANSI sequences (CSI ?1049h/l). Check which buffer is active:
if term.IsAlternateScreen() {
// Full-screen app is running
}
Cells and Attributes ¶
Each cell stores a character with styling information:
cell := term.Cell(row, col)
if cell != nil {
fmt.Printf("Char: %c\n", cell.Char)
fmt.Printf("Bold: %v\n", cell.HasFlag(headlessterm.CellFlagBold))
fmt.Printf("FG: %v\n", cell.Fg)
fmt.Printf("BG: %v\n", cell.Bg)
}
Cell flags include: Bold, Dim, Italic, Underline, Blink, Reverse, Hidden, Strike.
Colors ¶
Colors are stored using Go's image/color interface. The package supports:
- Named colors (indices 0-15 for standard ANSI colors)
- 256-color palette (indices 0-255)
- True color (24-bit RGB via color.RGBA)
Use ResolveDefaultColor to convert any color to RGBA:
rgba := headlessterm.ResolveDefaultColor(cell.Fg, true)
Scrollback ¶
Lines scrolled off the top of the primary buffer can be stored for later access. Implement ScrollbackProvider or use the built-in memory storage:
// In-memory scrollback with 10000 line limit
storage := headlessterm.NewMemoryScrollback(10000)
term := headlessterm.New(headlessterm.WithScrollback(storage))
// Access scrollback
for i := 0; i < term.ScrollbackLen(); i++ {
line := term.ScrollbackLine(i) // []Cell
}
PTY Writer ¶
PTYWriter writes terminal responses back to the PTY (cursor position reports, etc.):
term := headlessterm.New(headlessterm.WithPTYWriter(os.Stdout))
Providers ¶
Providers handle terminal events and queries. All are optional with no-op defaults:
- BellProvider: Handles bell/beep events
- TitleProvider: Handles window title changes (OSC 0/1/2)
- ClipboardProvider: Handles clipboard operations (OSC 52)
- ScrollbackProvider: Stores lines scrolled off screen
- RecordingProvider: Captures raw input for replay
- SizeProvider: Provides pixel dimensions for queries
- SemanticPromptHandler: Handles semantic prompt marks (OSC 133)
Example with providers:
term := headlessterm.New(
headlessterm.WithPTYWriter(os.Stdout),
headlessterm.WithBell(&MyBellHandler{}),
headlessterm.WithTitle(&MyTitleHandler{}),
)
Middleware ¶
Middleware intercepts ANSI handler calls for custom behavior:
mw := &headlessterm.Middleware{
Input: func(r rune, next func(rune)) {
log.Printf("Input: %c", r)
next(r) // Call default handler
},
Bell: func(next func()) {
log.Println("Bell!")
// Don't call next() to suppress the bell
},
}
term := headlessterm.New(headlessterm.WithMiddleware(mw))
Terminal Modes ¶
Various terminal behaviors are controlled by mode flags:
term.HasMode(headlessterm.ModeLineWrap) // Auto line wrap enabled? term.HasMode(headlessterm.ModeShowCursor) // Cursor visible? term.HasMode(headlessterm.ModeBracketedPaste) // Bracketed paste enabled?
See TerminalMode for all available modes.
Dirty Tracking ¶
Track which cells changed for efficient rendering:
if term.HasDirty() {
for _, pos := range term.DirtyCells() {
// Redraw cell at pos.Row, pos.Col
}
term.ClearDirty()
}
Selection ¶
Manage text selections for copy/paste:
term.SetSelection(
headlessterm.Position{Row: 0, Col: 0},
headlessterm.Position{Row: 2, Col: 10},
)
text := term.GetSelectedText()
term.ClearSelection()
Search ¶
Find text in the visible screen or scrollback:
matches := term.Search("error")
for _, pos := range matches {
fmt.Printf("Found at row %d, col %d\n", pos.Row, pos.Col)
}
// Search scrollback (returns negative row numbers)
scrollbackMatches := term.SearchScrollback("error")
Snapshots ¶
Capture the terminal state for serialization or rendering:
// Text only (smallest) snap := term.Snapshot(headlessterm.SnapshotDetailText) // With style segments (good for HTML rendering) snap := term.Snapshot(headlessterm.SnapshotDetailStyled) // Full cell data (complete state, includes image references) snap := term.Snapshot(headlessterm.SnapshotDetailFull) // Convert to JSON data, _ := json.Marshal(snap)
Snapshots include detailed attribute information:
- Underline styles: "single", "double", "curly", "dotted", "dashed"
- Blink types: "slow", "fast"
- Underline color (separate from foreground)
- Cell image references with UV coordinates for texture mapping
Image Support ¶
The terminal supports inline images via Sixel and Kitty graphics protocols:
// Check if images are enabled
if term.SixelEnabled() || term.KittyEnabled() {
// Process image sequences
}
// Access stored images
for _, placement := range term.ImagePlacements() {
img := term.Image(placement.ImageID)
// img.Data contains RGBA pixels
}
// Configure image memory budget
term.SetImageMaxMemory(100 * 1024 * 1024) // 100MB
Shell Integration ¶
Track shell prompts and command output (OSC 133):
term := headlessterm.New(
headlessterm.WithSemanticPromptHandler(&MyHandler{}),
)
// Navigate between prompts (uses absolute rows, including scrollback)
currentAbsRow := term.ViewportRowToAbsolute(0) // Convert viewport row to absolute
nextAbsRow := term.NextPromptRow(currentAbsRow, -1)
prevAbsRow := term.PrevPromptRow(currentAbsRow, -1)
// Convert absolute row back to viewport for display
viewportRow := term.AbsoluteRowToViewport(nextAbsRow) // -1 if in scrollback
// Get last command output
output := term.GetLastCommandOutput()
Auto-Resize Mode ¶
In auto-resize mode, the buffer grows instead of scrolling:
term := headlessterm.New(headlessterm.WithAutoResize())
// Capture complete output without truncation
cmd.Stdout = term
cmd.Run()
// Buffer has grown to fit all output
fmt.Printf("Total rows: %d\n", term.Rows())
Thread Safety ¶
All Terminal methods are safe for concurrent use. The terminal uses internal locking to protect state. However, if you need to perform multiple operations atomically, you should use your own synchronization.
Supported ANSI Sequences ¶
The terminal supports a comprehensive set of ANSI escape sequences including:
- Cursor movement (CUU, CUD, CUF, CUB, CUP, HVP, etc.)
- Cursor save/restore (DECSC, DECRC)
- Erase commands (ED, EL, ECH)
- Insert/delete (ICH, DCH, IL, DL)
- Scrolling (SU, SD, DECSTBM)
- Character attributes (SGR) with full color support
- Terminal modes (DECSET, DECRST)
- Device status reports (DSR)
- Alternate screen buffer
- Bracketed paste mode
- Mouse reporting
- Window title (OSC 0/1/2)
- Clipboard (OSC 52)
- Hyperlinks (OSC 8)
- Shell integration (OSC 133)
- Sixel and Kitty graphics
For the complete list of supported sequences, see the go-ansicode package documentation.
Index ¶
- Constants
- Variables
- func FormatKittyResponse(imageID uint32, message string, isError bool) string
- func ResolveDefaultColor(c color.Color, fg bool) color.RGBA
- func StringWidth(s string) int
- type APCProvider
- type BellProvider
- type Buffer
- func (b *Buffer) Cell(row, col int) *Cell
- func (b *Buffer) ClearAll()
- func (b *Buffer) ClearAllDirty()
- func (b *Buffer) ClearAllTabStops()
- func (b *Buffer) ClearRow(row int)
- func (b *Buffer) ClearRowRange(row, startCol, endCol int)
- func (b *Buffer) ClearScrollback()
- func (b *Buffer) ClearTabStop(col int)
- func (b *Buffer) Cols() int
- func (b *Buffer) DeleteChars(row, col, n int)
- func (b *Buffer) DeleteLines(row, n, bottom int)
- func (b *Buffer) DirtyCells() []Position
- func (b *Buffer) FillWithE()
- func (b *Buffer) GrowCols(row, minCols int)
- func (b *Buffer) GrowRows(n int)
- func (b *Buffer) HasDirty() bool
- func (b *Buffer) InsertBlanks(row, col, n int)
- func (b *Buffer) InsertLines(row, n, bottom int)
- func (b *Buffer) IsWrapped(row int) bool
- func (b *Buffer) LineContent(row int) string
- func (b *Buffer) MarkDirty(row, col int)
- func (b *Buffer) MaxScrollback() int
- func (b *Buffer) NextTabStop(col int) int
- func (b *Buffer) PrevTabStop(col int) int
- func (b *Buffer) Resize(rows, cols int)
- func (b *Buffer) Rows() int
- func (b *Buffer) ScrollDown(top, bottom, n int)
- func (b *Buffer) ScrollUp(top, bottom, n int)
- func (b *Buffer) ScrollbackLen() int
- func (b *Buffer) ScrollbackLine(index int) []Cell
- func (b *Buffer) ScrollbackProvider() ScrollbackProvider
- func (b *Buffer) SetCell(row, col int, cell Cell)
- func (b *Buffer) SetMaxScrollback(max int)
- func (b *Buffer) SetScrollbackProvider(storage ScrollbackProvider)
- func (b *Buffer) SetTabStop(col int)
- func (b *Buffer) SetWrapped(row int, wrapped bool)
- type Cell
- func (c *Cell) ClearDirty()
- func (c *Cell) ClearFlag(flag CellFlags)
- func (c *Cell) Copy() Cell
- func (c *Cell) HasFlag(flag CellFlags) bool
- func (c *Cell) HasImage() bool
- func (c *Cell) IsDirty() bool
- func (c *Cell) IsWide() bool
- func (c *Cell) IsWideSpacer() bool
- func (c *Cell) MarkDirty()
- func (c *Cell) Reset()
- func (c *Cell) SetFlag(flag CellFlags)
- type CellFlags
- type CellImage
- type CellTemplate
- type Charset
- type CharsetIndex
- type ClipboardProvider
- type Cursor
- type CursorStyle
- type Hyperlink
- type ImageData
- type ImageFormat
- type ImageManager
- func (m *ImageManager) Clear()
- func (m *ImageManager) ClearPlacements()
- func (m *ImageManager) DeleteImage(id uint32)
- func (m *ImageManager) DeletePlacementsAbove(row int)
- func (m *ImageManager) DeletePlacementsBelow(row int)
- func (m *ImageManager) DeletePlacementsByPosition(row, col int)
- func (m *ImageManager) DeletePlacementsByZIndex(z int32)
- func (m *ImageManager) DeletePlacementsInColumn(col int)
- func (m *ImageManager) DeletePlacementsInRow(row int)
- func (m *ImageManager) DeletePlacementsInRowRange(startRow, endRow int)
- func (m *ImageManager) Image(id uint32) *ImageData
- func (m *ImageManager) ImageCount() int
- func (m *ImageManager) Place(p *ImagePlacement) uint32
- func (m *ImageManager) Placement(id uint32) *ImagePlacement
- func (m *ImageManager) PlacementCount() int
- func (m *ImageManager) Placements() []*ImagePlacement
- func (m *ImageManager) RemovePlacement(id uint32)
- func (m *ImageManager) RemovePlacementsForImage(imageID uint32)
- func (m *ImageManager) SetMaxMemory(bytes int64)
- func (m *ImageManager) Store(width, height uint32, data []byte) uint32
- func (m *ImageManager) StoreWithID(id, width, height uint32, data []byte)
- func (m *ImageManager) UsedMemory() int64
- type ImagePlacement
- type ImageSnapshot
- type IndexedColor
- type KittyAction
- type KittyCommand
- type KittyDelete
- type KittyFormat
- type KittyTransmission
- type MemoryRecording
- type MemoryScrollback
- type Middleware
- type NamedColor
- type NoopAPC
- type NoopBell
- type NoopClipboard
- type NoopNotification
- type NoopPM
- type NoopPTYWriter
- type NoopRecording
- type NoopSOS
- type NoopScrollback
- type NoopSemanticPromptHandler
- type NoopSizeProvider
- type NoopTitle
- type NotificationPayload
- type NotificationProvider
- type Option
- func WithAPC(p APCProvider) Option
- func WithAutoResize() Option
- func WithBell(p BellProvider) Option
- func WithClipboard(p ClipboardProvider) Option
- func WithKitty(enabled bool) Option
- func WithMiddleware(mw *Middleware) Option
- func WithNotification(p NotificationProvider) Option
- func WithPM(p PMProvider) Option
- func WithPTYWriter(p PTYWriter) Option
- func WithRecording(p RecordingProvider) Option
- func WithSOS(p SOSProvider) Option
- func WithScrollback(storage ScrollbackProvider) Option
- func WithSemanticPromptHandler(h SemanticPromptHandler) Option
- func WithSixel(enabled bool) Option
- func WithSize(rows, cols int) Option
- func WithSizeProvider(p SizeProvider) Option
- func WithTitle(p TitleProvider) Option
- type PMProvider
- type PTYWriter
- type Position
- type PromptMark
- type RecordingProvider
- type SOSProvider
- type SavedCursor
- type ScrollbackProvider
- type Selection
- type SemanticPromptHandler
- type SixelImage
- type SizeProvider
- type Snapshot
- type SnapshotAttrs
- type SnapshotCell
- type SnapshotCellImage
- type SnapshotCursor
- type SnapshotDetail
- type SnapshotImage
- type SnapshotLine
- type SnapshotLink
- type SnapshotSegment
- type SnapshotSize
- type Terminal
- func (t *Terminal) APCProvider() APCProvider
- func (t *Terminal) AbsoluteRowToViewport(absoluteRow int) int
- func (t *Terminal) ApplicationCommandReceived(data []byte)
- func (t *Terminal) AutoResize() bool
- func (t *Terminal) Backspace()
- func (t *Terminal) Bell()
- func (t *Terminal) BellProvider() BellProvider
- func (t *Terminal) CarriageReturn()
- func (t *Terminal) Cell(row, col int) *Cell
- func (t *Terminal) CellSizePixels()
- func (t *Terminal) ClearDirty()
- func (t *Terminal) ClearImages()
- func (t *Terminal) ClearLine(mode ansicode.LineClearMode)
- func (t *Terminal) ClearPromptMarks()
- func (t *Terminal) ClearRecording()
- func (t *Terminal) ClearScreen(mode ansicode.ClearMode)
- func (t *Terminal) ClearScrollback()
- func (t *Terminal) ClearSelection()
- func (t *Terminal) ClearTabs(mode ansicode.TabulationClearMode)
- func (t *Terminal) ClearUserVars()
- func (t *Terminal) ClipboardLoad(clipboard byte, terminator string)
- func (t *Terminal) ClipboardProvider() ClipboardProvider
- func (t *Terminal) ClipboardStore(clipboard byte, data []byte)
- func (t *Terminal) Cols() int
- func (t *Terminal) ConfigureCharset(index ansicode.CharsetIndex, charset ansicode.Charset)
- func (t *Terminal) CursorPos() (row, col int)
- func (t *Terminal) CursorStyle() CursorStyle
- func (t *Terminal) CursorVisible() bool
- func (t *Terminal) Decaln()
- func (t *Terminal) DeleteChars(n int)
- func (t *Terminal) DeleteLines(n int)
- func (t *Terminal) DesktopNotification(payload *NotificationPayload)
- func (t *Terminal) DeviceStatus(n int)
- func (t *Terminal) DirtyCells() []Position
- func (t *Terminal) EraseChars(n int)
- func (t *Terminal) GetImageData(id uint32) *ImageSnapshot
- func (t *Terminal) GetLastCommandOutput() string
- func (t *Terminal) GetPromptMarkAt(absRow int) *PromptMark
- func (t *Terminal) GetSelectedText() string
- func (t *Terminal) GetSelection() Selection
- func (t *Terminal) GetUserVar(name string) string
- func (t *Terminal) GetUserVars() map[string]string
- func (t *Terminal) Goto(row, col int)
- func (t *Terminal) GotoCol(col int)
- func (t *Terminal) GotoLine(row int)
- func (t *Terminal) HasDirty() bool
- func (t *Terminal) HasMode(mode TerminalMode) bool
- func (t *Terminal) HasSelection() bool
- func (t *Terminal) HorizontalTabSet()
- func (t *Terminal) IdentifyTerminal(b byte)
- func (t *Terminal) Image(id uint32) *ImageData
- func (t *Terminal) ImageCount() int
- func (t *Terminal) ImagePlacementCount() int
- func (t *Terminal) ImagePlacements() []*ImagePlacement
- func (t *Terminal) ImageUsedMemory() int64
- func (t *Terminal) Input(r rune)
- func (t *Terminal) InsertBlank(n int)
- func (t *Terminal) InsertBlankLines(n int)
- func (t *Terminal) IsAlternateScreen() bool
- func (t *Terminal) IsSelected(row, col int) bool
- func (t *Terminal) IsWrapped(row int) bool
- func (t *Terminal) KittyEnabled() bool
- func (t *Terminal) LineContent(row int) string
- func (t *Terminal) LineFeed()
- func (t *Terminal) MaxScrollback() int
- func (t *Terminal) Middleware() *Middleware
- func (t *Terminal) MoveBackward(n int)
- func (t *Terminal) MoveBackwardTabs(n int)
- func (t *Terminal) MoveDown(n int)
- func (t *Terminal) MoveDownCr(n int)
- func (t *Terminal) MoveForward(n int)
- func (t *Terminal) MoveForwardTabs(n int)
- func (t *Terminal) MoveUp(n int)
- func (t *Terminal) MoveUpCr(n int)
- func (t *Terminal) NextPromptRow(currentAbsRow int, markType ansicode.ShellIntegrationMark) int
- func (t *Terminal) NotificationProvider() NotificationProvider
- func (t *Terminal) PMProvider() PMProvider
- func (t *Terminal) PTYWriter() PTYWriter
- func (t *Terminal) PopKeyboardMode(n int)
- func (t *Terminal) PopTitle()
- func (t *Terminal) PrevPromptRow(currentAbsRow int, markType ansicode.ShellIntegrationMark) int
- func (t *Terminal) PrivacyMessageReceived(data []byte)
- func (t *Terminal) PromptMarkCount() int
- func (t *Terminal) PromptMarks() []PromptMark
- func (t *Terminal) PushKeyboardMode(mode ansicode.KeyboardMode)
- func (t *Terminal) PushTitle()
- func (t *Terminal) RecordedData() []byte
- func (t *Terminal) RecordingProvider() RecordingProvider
- func (t *Terminal) ReportKeyboardMode()
- func (t *Terminal) ReportModifyOtherKeys()
- func (t *Terminal) ResetColor(i int)
- func (t *Terminal) ResetState()
- func (t *Terminal) Resize(rows, cols int)
- func (t *Terminal) RestoreCursorPosition()
- func (t *Terminal) ReverseIndex()
- func (t *Terminal) Rows() int
- func (t *Terminal) SOSProvider() SOSProvider
- func (t *Terminal) SaveCursorPosition()
- func (t *Terminal) ScrollDown(n int)
- func (t *Terminal) ScrollRegion() (top, bottom int)
- func (t *Terminal) ScrollUp(n int)
- func (t *Terminal) ScrollbackLen() int
- func (t *Terminal) ScrollbackLine(index int) []Cell
- func (t *Terminal) ScrollbackProvider() ScrollbackProvider
- func (t *Terminal) Search(pattern string) []Position
- func (t *Terminal) SearchScrollback(pattern string) []Position
- func (t *Terminal) SemanticPromptHandlerValue() SemanticPromptHandler
- func (t *Terminal) SetAPCProvider(p APCProvider)
- func (t *Terminal) SetActiveCharset(n int)
- func (t *Terminal) SetBellProvider(p BellProvider)
- func (t *Terminal) SetClipboardProvider(c ClipboardProvider)
- func (t *Terminal) SetColor(index int, c color.Color)
- func (t *Terminal) SetCursorStyle(style ansicode.CursorStyle)
- func (t *Terminal) SetDynamicColor(prefix string, index int, terminator string)
- func (t *Terminal) SetHyperlink(hyperlink *ansicode.Hyperlink)
- func (t *Terminal) SetImageMaxMemory(bytes int64)
- func (t *Terminal) SetKeyboardMode(mode ansicode.KeyboardMode, behavior ansicode.KeyboardModeBehavior)
- func (t *Terminal) SetKeypadApplicationMode()
- func (t *Terminal) SetMaxScrollback(max int)
- func (t *Terminal) SetMiddleware(mw *Middleware)
- func (t *Terminal) SetMode(mode ansicode.TerminalMode)
- func (t *Terminal) SetModifyOtherKeys(modify ansicode.ModifyOtherKeys)
- func (t *Terminal) SetNotificationProvider(p NotificationProvider)
- func (t *Terminal) SetPMProvider(p PMProvider)
- func (t *Terminal) SetPTYWriter(p PTYWriter)
- func (t *Terminal) SetRecordingProvider(p RecordingProvider)
- func (t *Terminal) SetSOSProvider(p SOSProvider)
- func (t *Terminal) SetScrollbackProvider(storage ScrollbackProvider)
- func (t *Terminal) SetScrollingRegion(top, bottom int)
- func (t *Terminal) SetSelection(start, end Position)
- func (t *Terminal) SetSemanticPromptHandler(h SemanticPromptHandler)
- func (t *Terminal) SetSizeProvider(p SizeProvider)
- func (t *Terminal) SetTerminalCharAttribute(attr ansicode.TerminalCharAttribute)
- func (t *Terminal) SetTitle(title string)
- func (t *Terminal) SetTitleProvider(p TitleProvider)
- func (t *Terminal) SetUserVar(name, value string)
- func (t *Terminal) SetWorkingDirectory(uri string)
- func (t *Terminal) SetWrapped(row int, wrapped bool)
- func (t *Terminal) ShellIntegrationMark(mark ansicode.ShellIntegrationMark, exitCode int)
- func (t *Terminal) SixelEnabled() bool
- func (t *Terminal) SixelReceived(params [][]uint16, data []byte)
- func (t *Terminal) Snapshot(detail SnapshotDetail) *Snapshot
- func (t *Terminal) StartOfStringReceived(data []byte)
- func (t *Terminal) String() string
- func (t *Terminal) Substitute()
- func (t *Terminal) Tab(n int)
- func (t *Terminal) TextAreaSizeChars()
- func (t *Terminal) TextAreaSizePixels()
- func (t *Terminal) Title() string
- func (t *Terminal) TitleProvider() TitleProvider
- func (t *Terminal) UnsetKeypadApplicationMode()
- func (t *Terminal) UnsetMode(mode ansicode.TerminalMode)
- func (t *Terminal) ViewportRowToAbsolute(viewportRow int) int
- func (t *Terminal) WorkingDirectory() string
- func (t *Terminal) WorkingDirectoryPath() string
- func (t *Terminal) Write(data []byte) (int, error)
- func (t *Terminal) WriteString(s string) (int, error)
- type TerminalMode
- type TitleProvider
Constants ¶
const ( NamedColorForeground = 256 // Default foreground text color NamedColorBackground = 257 // Default background color NamedColorCursor = 258 // Cursor color NamedColorDimBlack = 259 // Dim black NamedColorDimRed = 260 // Dim red NamedColorDimGreen = 261 // Dim green NamedColorDimYellow = 262 // Dim yellow NamedColorDimBlue = 263 // Dim blue NamedColorDimMagenta = 264 // Dim magenta NamedColorDimCyan = 265 // Dim cyan NamedColorDimWhite = 266 // Dim white NamedColorBrightForeground = 267 // Bright foreground (white) NamedColorDimForeground = 268 // Dim foreground )
Named color indices for semantic colors (used with NamedColor).
const ( // DEFAULT_ROWS is the default number of terminal rows. DEFAULT_ROWS = 24 // DEFAULT_COLS is the default number of terminal columns. DEFAULT_COLS = 80 )
const ImagePlaceholderChar = '\U0010EEEE'
ImagePlaceholderChar is the Unicode character used to mark cells occupied by images. This is in the Private Use Area (Plane 16) and used by Kitty Graphics Protocol.
Variables ¶
var DefaultBackground = color.RGBA{0, 0, 0, 255}
DefaultBackground is the default background color (black).
var DefaultCursorColor = color.RGBA{229, 229, 229, 255}
DefaultCursorColor is the default cursor rendering color (light gray).
var DefaultForeground = color.RGBA{229, 229, 229, 255}
DefaultForeground is the default text color (light gray).
var DefaultPalette = [256]color.RGBA{
{0, 0, 0, 255},
{205, 49, 49, 255},
{13, 188, 121, 255},
{229, 229, 16, 255},
{36, 114, 200, 255},
{188, 63, 188, 255},
{17, 168, 205, 255},
{229, 229, 229, 255},
{102, 102, 102, 255},
{241, 76, 76, 255},
{35, 209, 139, 255},
{245, 245, 67, 255},
{59, 142, 234, 255},
{214, 112, 214, 255},
{41, 184, 219, 255},
{255, 255, 255, 255},
}
DefaultPalette is the standard 256-color palette: 16 named colors (0-15), 216 color cube (16-231), 24 grayscale (232-255).
Functions ¶
func FormatKittyResponse ¶ added in v1.0.1
FormatKittyResponse formats a Kitty graphics response.
func ResolveDefaultColor ¶ added in v1.0.6
ResolveDefaultColor converts a color.Color to RGBA using the default palette. If c is nil, returns the default foreground or background based on the fg parameter. IndexedColor and NamedColor are resolved using DefaultPalette.
Example:
cell := term.Cell(0, 0) fgColor := headlessterm.ResolveDefaultColor(cell.Fg, true) bgColor := headlessterm.ResolveDefaultColor(cell.Bg, false)
func StringWidth ¶
StringWidth returns the total display width of a string (sum of rune widths).
Types ¶
type APCProvider ¶
type APCProvider interface {
// Receive is called with the payload of an APC sequence.
Receive(data []byte)
}
APCProvider handles Application Program Command sequences (OSC _).
type BellProvider ¶
type BellProvider interface {
// Ring is called when a bell character is received.
Ring()
}
BellProvider handles bell/beep events triggered by BEL (0x07) characters.
type Buffer ¶
type Buffer struct {
// contains filtered or unexported fields
}
Buffer stores a 2D grid of cells and tracks line wrapping state. Supports optional scrollback storage for lines scrolled off the top.
func NewBufferWithStorage ¶
func NewBufferWithStorage(rows, cols int, storage ScrollbackProvider) *Buffer
NewBufferWithStorage creates a buffer with custom scrollback storage. Tab stops are initialized every 8 columns.
func (*Buffer) Cell ¶
Cell returns a pointer to the cell at (row, col). Returns nil if coordinates are out of bounds.
func (*Buffer) ClearAll ¶
func (b *Buffer) ClearAll()
ClearAll resets all cells in the buffer to default state.
func (*Buffer) ClearAllDirty ¶
func (b *Buffer) ClearAllDirty()
ClearAllDirty resets the dirty state of all cells.
func (*Buffer) ClearAllTabStops ¶
func (b *Buffer) ClearAllTabStops()
ClearAllTabStops disables all tab stops.
func (*Buffer) ClearRow ¶
ClearRow resets all cells in the row to default state and marks them dirty.
func (*Buffer) ClearRowRange ¶
ClearRowRange resets cells in the row from startCol (inclusive) to endCol (exclusive).
func (*Buffer) ClearScrollback ¶
func (b *Buffer) ClearScrollback()
ClearScrollback removes all stored scrollback lines.
func (*Buffer) ClearTabStop ¶
ClearTabStop disables the tab stop at the specified column.
func (*Buffer) DeleteChars ¶
DeleteChars removes n characters at (row, col), shifting remaining characters left.
func (*Buffer) DeleteLines ¶
DeleteLines removes n lines at row, shifting remaining lines up. Equivalent to ScrollUp(row, bottom, n).
func (*Buffer) DirtyCells ¶
DirtyCells returns positions of all modified cells.
func (*Buffer) FillWithE ¶
func (b *Buffer) FillWithE()
FillWithE fills all cells with 'E' (used by DECALN alignment test pattern).
func (*Buffer) GrowCols ¶
GrowCols expands a single row to at least minCols columns. Does nothing if the row is already wider. Tab stops are extended if needed.
func (*Buffer) GrowRows ¶
GrowRows appends n new rows to the bottom of the buffer. New cells are initialized to default state and marked dirty.
func (*Buffer) HasDirty ¶
HasDirty returns true if any cell has been modified since the last ClearAllDirty call.
func (*Buffer) InsertBlanks ¶
InsertBlanks inserts n blank cells at (row, col), shifting existing characters right.
func (*Buffer) InsertLines ¶
InsertLines inserts n blank lines at row, shifting existing lines down. Equivalent to ScrollDown(row, bottom, n).
func (*Buffer) LineContent ¶
LineContent returns the text content of a line, trimming trailing spaces. Wide character spacers are skipped. Returns empty string if the line is empty or out of bounds.
func (*Buffer) MarkDirty ¶
MarkDirty marks the cell at (row, col) as modified. Does nothing if coordinates are out of bounds.
func (*Buffer) MaxScrollback ¶
MaxScrollback returns the current maximum scrollback capacity.
func (*Buffer) NextTabStop ¶
NextTabStop returns the column index of the next enabled tab stop after col. Returns the last column if no tab stop is found.
func (*Buffer) PrevTabStop ¶
PrevTabStop returns the column index of the previous enabled tab stop before col. Returns 0 if no tab stop is found.
func (*Buffer) Resize ¶
Resize changes buffer dimensions, preserving existing cells where possible. Content is kept at the top-left corner. When shrinking, bottom/right content is lost. When growing, new empty cells are added at the bottom/right. Tab stops are extended if columns increase.
func (*Buffer) ScrollDown ¶
ScrollDown shifts lines down by n positions within [top, bottom). Top lines are cleared and marked dirty.
func (*Buffer) ScrollUp ¶
ScrollUp shifts lines up by n positions within [top, bottom). Lines scrolled off the top are pushed to scrollback if enabled and top==0. Bottom lines are cleared and marked dirty.
func (*Buffer) ScrollbackLen ¶
ScrollbackLen returns the number of lines stored in scrollback.
func (*Buffer) ScrollbackLine ¶
ScrollbackLine returns a line from scrollback, where 0 is the oldest line. Returns nil if index is out of range or scrollback is disabled.
func (*Buffer) ScrollbackProvider ¶
func (b *Buffer) ScrollbackProvider() ScrollbackProvider
ScrollbackProvider returns the current scrollback storage implementation.
func (*Buffer) SetCell ¶
SetCell replaces the cell at (row, col) and marks it dirty. Does nothing if coordinates are out of bounds.
func (*Buffer) SetMaxScrollback ¶
SetMaxScrollback sets the maximum number of scrollback lines to retain.
func (*Buffer) SetScrollbackProvider ¶
func (b *Buffer) SetScrollbackProvider(storage ScrollbackProvider)
SetScrollbackProvider replaces the scrollback storage implementation.
func (*Buffer) SetTabStop ¶
SetTabStop enables a tab stop at the specified column.
func (*Buffer) SetWrapped ¶
SetWrapped sets whether the line was wrapped or ended with an explicit newline.
type Cell ¶
type Cell struct {
Char rune
Fg color.Color
Bg color.Color
UnderlineColor color.Color
Flags CellFlags
Hyperlink *Hyperlink
Image *CellImage // Image reference, nil if no image
}
Cell stores the character, colors, and formatting attributes for one grid position. Wide characters (2 columns) use a spacer cell in the second position.
func NewCell ¶
func NewCell() Cell
NewCell creates a cell initialized with space character and default colors.
func (*Cell) Copy ¶
Copy returns a deep copy of the cell, including the hyperlink and image pointers.
func (*Cell) IsDirty ¶
IsDirty returns true if the cell was modified since the last ClearDirty call.
func (*Cell) IsWide ¶
IsWide returns true if this cell contains a wide character (CJK, emoji, etc.) that occupies 2 columns.
func (*Cell) IsWideSpacer ¶
IsWideSpacer returns true if this is the second cell of a wide character (should be skipped during rendering).
func (*Cell) MarkDirty ¶
func (c *Cell) MarkDirty()
MarkDirty marks the cell as modified for dirty tracking.
type CellFlags ¶
type CellFlags uint16
CellFlags is a bitmask of cell rendering attributes.
const ( CellFlagBold CellFlags = 1 << iota CellFlagDim CellFlagItalic CellFlagUnderline CellFlagDoubleUnderline CellFlagCurlyUnderline CellFlagDottedUnderline CellFlagDashedUnderline CellFlagBlinkSlow CellFlagBlinkFast CellFlagReverse CellFlagHidden CellFlagStrike CellFlagWideChar CellFlagWideCharSpacer CellFlagDirty )
type CellImage ¶ added in v1.0.1
type CellImage struct {
PlacementID uint32 // Reference to ImagePlacement
ImageID uint32 // Direct reference to ImageData for quick lookup
// Normalized texture coordinates (0.0 - 1.0)
U0, V0 float32 // Top-left corner
U1, V1 float32 // Bottom-right corner
// Scale factors for rendering (1.0 = no scaling)
ScaleX, ScaleY float32
// Z-index for render ordering
ZIndex int32
}
CellImage is a lightweight reference stored in each Cell. It contains UV coordinates for rendering the correct slice of the image.
type CellTemplate ¶
type CellTemplate struct {
Cell
}
CellTemplate defines default attributes applied to newly written characters. Modified by SGR (Select Graphic Rendition) escape sequences.
func NewCellTemplate ¶
func NewCellTemplate() CellTemplate
NewCellTemplate creates a template with default attributes (no colors, no flags).
type CharsetIndex ¶
type CharsetIndex int
CharsetIndex selects one of four character set slots (G0-G3).
const ( CharsetIndexG0 CharsetIndex = iota CharsetIndexG1 CharsetIndexG2 CharsetIndexG3 )
type ClipboardProvider ¶
type ClipboardProvider interface {
// Read returns content from the specified clipboard ('c' for clipboard, 'p' for primary selection).
Read(clipboard byte) string
// Write stores content to the specified clipboard.
Write(clipboard byte, data []byte)
}
ClipboardProvider handles clipboard read/write operations (OSC 52).
type Cursor ¶
type Cursor struct {
Row int
Col int
Style CursorStyle
Visible bool
}
Cursor tracks the current position and rendering style (0-based coordinates).
type CursorStyle ¶
type CursorStyle int
CursorStyle determines how the cursor is rendered.
const ( CursorStyleBlinkingBlock CursorStyle = iota CursorStyleSteadyBlock CursorStyleBlinkingUnderline CursorStyleSteadyUnderline CursorStyleBlinkingBar CursorStyleSteadyBar )
type ImageData ¶ added in v1.0.1
type ImageData struct {
ID uint32 // Unique image ID
Width uint32 // Image width in pixels
Height uint32 // Image height in pixels
Data []byte // RGBA pixel data (always converted to RGBA internally)
Hash [32]byte // SHA-256 hash for deduplication
CreatedAt time.Time // For LRU eviction
AccessedAt time.Time // Last access time
}
ImageData stores decoded image pixels and metadata.
type ImageFormat ¶ added in v1.0.1
type ImageFormat uint8
ImageFormat represents the format of image data.
const ( ImageFormatRGBA ImageFormat = iota // 32-bit RGBA (4 bytes per pixel) ImageFormatRGB // 24-bit RGB (3 bytes per pixel) ImageFormatPNG // PNG encoded )
type ImageManager ¶ added in v1.0.1
type ImageManager struct {
// contains filtered or unexported fields
}
ImageManager handles storage, placement, and lifecycle of terminal images.
func NewImageManager ¶ added in v1.0.1
func NewImageManager() *ImageManager
NewImageManager creates a new ImageManager with default settings.
func (*ImageManager) Clear ¶ added in v1.0.1
func (m *ImageManager) Clear()
Clear removes all images and placements.
func (*ImageManager) ClearPlacements ¶ added in v1.0.4
func (m *ImageManager) ClearPlacements()
ClearPlacements removes all placements but keeps image data.
func (*ImageManager) DeleteImage ¶ added in v1.0.1
func (m *ImageManager) DeleteImage(id uint32)
DeleteImage removes an image and all its placements.
func (*ImageManager) DeletePlacementsAbove ¶ added in v1.0.4
func (m *ImageManager) DeletePlacementsAbove(row int)
DeletePlacementsAbove removes all placements at or above the given row.
func (*ImageManager) DeletePlacementsBelow ¶ added in v1.0.4
func (m *ImageManager) DeletePlacementsBelow(row int)
DeletePlacementsBelow removes all placements at or below the given row.
func (*ImageManager) DeletePlacementsByPosition ¶ added in v1.0.1
func (m *ImageManager) DeletePlacementsByPosition(row, col int)
DeletePlacementsByPosition removes placements that overlap a given cell position.
func (*ImageManager) DeletePlacementsByZIndex ¶ added in v1.0.1
func (m *ImageManager) DeletePlacementsByZIndex(z int32)
DeletePlacementsByZIndex removes placements with a specific z-index.
func (*ImageManager) DeletePlacementsInColumn ¶ added in v1.0.1
func (m *ImageManager) DeletePlacementsInColumn(col int)
DeletePlacementsInColumn removes all placements that intersect a given column.
func (*ImageManager) DeletePlacementsInRow ¶ added in v1.0.1
func (m *ImageManager) DeletePlacementsInRow(row int)
DeletePlacementsInRow removes all placements that intersect a given row.
func (*ImageManager) DeletePlacementsInRowRange ¶ added in v1.0.4
func (m *ImageManager) DeletePlacementsInRowRange(startRow, endRow int)
DeletePlacementsInRowRange removes all placements that intersect rows in [startRow, endRow).
func (*ImageManager) Image ¶ added in v1.0.1
func (m *ImageManager) Image(id uint32) *ImageData
Image returns the image data for the given ID, or nil if not found.
func (*ImageManager) ImageCount ¶ added in v1.0.1
func (m *ImageManager) ImageCount() int
ImageCount returns the number of stored images.
func (*ImageManager) Place ¶ added in v1.0.1
func (m *ImageManager) Place(p *ImagePlacement) uint32
Place creates a new placement and returns its ID.
func (*ImageManager) Placement ¶ added in v1.0.1
func (m *ImageManager) Placement(id uint32) *ImagePlacement
Placement returns the placement for the given ID, or nil if not found.
func (*ImageManager) PlacementCount ¶ added in v1.0.1
func (m *ImageManager) PlacementCount() int
PlacementCount returns the number of active placements.
func (*ImageManager) Placements ¶ added in v1.0.1
func (m *ImageManager) Placements() []*ImagePlacement
Placements returns all current placements.
func (*ImageManager) RemovePlacement ¶ added in v1.0.1
func (m *ImageManager) RemovePlacement(id uint32)
RemovePlacement removes a placement by ID.
func (*ImageManager) RemovePlacementsForImage ¶ added in v1.0.1
func (m *ImageManager) RemovePlacementsForImage(imageID uint32)
RemovePlacementsForImage removes all placements for a given image ID.
func (*ImageManager) SetMaxMemory ¶ added in v1.0.1
func (m *ImageManager) SetMaxMemory(bytes int64)
SetMaxMemory sets the maximum memory budget for images.
func (*ImageManager) Store ¶ added in v1.0.1
func (m *ImageManager) Store(width, height uint32, data []byte) uint32
Store adds image data and returns its ID. If an identical image exists (same hash), returns the existing ID.
func (*ImageManager) StoreWithID ¶ added in v1.0.1
func (m *ImageManager) StoreWithID(id, width, height uint32, data []byte)
StoreWithID adds image data with a specific ID (used by Kitty protocol).
func (*ImageManager) UsedMemory ¶ added in v1.0.1
func (m *ImageManager) UsedMemory() int64
UsedMemory returns the current memory usage in bytes.
type ImagePlacement ¶ added in v1.0.1
type ImagePlacement struct {
ID uint32 // Unique placement ID
ImageID uint32 // Reference to ImageData
// Position in terminal (cell coordinates, viewport-relative)
Row, Col int
// Size in cells
Cols, Rows int
// Source region (crop from original image)
SrcX, SrcY uint32
SrcW, SrcH uint32
// Z-index for layering (-1 = behind text, 0+ = in front)
ZIndex int32
// Sub-cell offset in pixels
OffsetX, OffsetY uint32
}
ImagePlacement represents a displayed instance of an image.
type ImageSnapshot ¶ added in v1.0.6
type ImageSnapshot struct {
ID uint32 `json:"id"`
Width uint32 `json:"width"`
Height uint32 `json:"height"`
Format string `json:"format"` // "rgba" (raw RGBA pixels, base64 encoded)
Data string `json:"data"` // Base64 encoded image data
}
ImageSnapshot holds complete image data for retrieval.
type IndexedColor ¶
type IndexedColor struct {
Index int
}
IndexedColor references a color by palette index (0-255). Resolution to actual RGBA happens at render time using the palette.
func (*IndexedColor) RGBA ¶
func (c *IndexedColor) RGBA() (r, g, b, a uint32)
RGBA implements color.Color, returning a placeholder (actual resolution happens at render time).
type KittyAction ¶ added in v1.0.1
type KittyAction byte
KittyAction represents the action to perform.
const ( KittyActionTransmit KittyAction = 't' // Transmit image data KittyActionTransmitDisplay KittyAction = 'T' // Transmit and display KittyActionQuery KittyAction = 'q' // Query terminal support KittyActionDisplay KittyAction = 'p' // Display (put) image KittyActionDelete KittyAction = 'd' // Delete image(s) KittyActionFrame KittyAction = 'f' // Transmit animation frame KittyActionAnimate KittyAction = 'a' // Control animation KittyActionCompose KittyAction = 'c' // Compose animation frames )
type KittyCommand ¶ added in v1.0.1
type KittyCommand struct {
Action KittyAction
Transmission KittyTransmission
Format KittyFormat
Compression byte // 'z' for zlib
// Image identification
ImageID uint32 // i=
ImageNumber uint32 // I=
PlacementID uint32 // p=
// Transmission parameters
Width uint32 // s= (source width in pixels)
Height uint32 // v= (source height in pixels)
Size uint32 // S= (data size for file/shm)
Offset uint32 // O= (data offset for file/shm)
More bool // m= (more data chunks coming)
// Display parameters
SrcX, SrcY uint32 // x=, y= (source region origin)
SrcW, SrcH uint32 // w=, h= (source region size)
Cols, Rows uint32 // c=, r= (target cell size)
CellOffsetX uint32 // X= (x offset within cell)
CellOffsetY uint32 // Y= (y offset within cell)
ZIndex int32 // z= (z-index for layering)
DoNotMoveCursor bool // C= (1 = don't move cursor)
// Delete parameters
Delete KittyDelete // d=
// Query/response
Quiet uint32 // q= (0=normal, 1=suppress OK, 2=suppress all)
// Payload data (base64 decoded)
Payload []byte
}
KittyCommand represents a parsed Kitty graphics command.
func ParseKittyGraphics ¶ added in v1.0.1
func ParseKittyGraphics(data []byte) (*KittyCommand, error)
ParseKittyGraphics parses a Kitty graphics APC sequence. The data should be the content after ESC_G (without the ESC_G prefix and ST terminator).
func (*KittyCommand) DecodeImageData ¶ added in v1.0.1
func (cmd *KittyCommand) DecodeImageData() ([]byte, uint32, uint32, error)
DecodeImageData decodes the image payload based on format and compression. Returns RGBA pixel data, width, and height.
type KittyDelete ¶ added in v1.0.1
type KittyDelete byte
KittyDelete represents what to delete.
const ( KittyDeleteAll KittyDelete = 'a' // All visible placements KittyDeleteAllWithData KittyDelete = 'A' // All visible + image data KittyDeleteByID KittyDelete = 'i' // By image ID KittyDeleteByIDWithData KittyDelete = 'I' // By image ID + image data KittyDeleteByNumber KittyDelete = 'n' // By image number KittyDeleteByNumData KittyDelete = 'N' // By image number + data KittyDeleteAtCursor KittyDelete = 'c' // At cursor position KittyDeleteAtCursorData KittyDelete = 'C' // At cursor + data KittyDeleteAtPos KittyDelete = 'p' // At specific position KittyDeleteAtPosData KittyDelete = 'P' // At position + data KittyDeleteByCol KittyDelete = 'x' // By column KittyDeleteByColData KittyDelete = 'X' // By column + data KittyDeleteByRow KittyDelete = 'y' // By row KittyDeleteByRowData KittyDelete = 'Y' // By row + data KittyDeleteByZIndex KittyDelete = 'z' // By z-index KittyDeleteByZIndexData KittyDelete = 'Z' // By z-index + data )
type KittyFormat ¶ added in v1.0.1
type KittyFormat uint32
KittyFormat represents the image format.
const ( KittyFormatRGB KittyFormat = 24 // 24-bit RGB KittyFormatRGBA KittyFormat = 32 // 32-bit RGBA (default) KittyFormatPNG KittyFormat = 100 // PNG encoded )
type KittyTransmission ¶ added in v1.0.1
type KittyTransmission byte
KittyTransmission represents how image data is transmitted.
const ( KittyTransmitDirect KittyTransmission = 'd' // Direct (inline base64) KittyTransmitFile KittyTransmission = 'f' // File path KittyTransmitTempFile KittyTransmission = 't' // Temporary file )
type MemoryRecording ¶ added in v1.0.6
type MemoryRecording struct {
// contains filtered or unexported fields
}
MemoryRecording stores raw input bytes in memory for replay or debugging.
Example:
recorder := headlessterm.NewMemoryRecording() term := headlessterm.New(headlessterm.WithRecording(recorder)) // ... process terminal output ... data := recorder.Data() // Get all recorded bytes
func NewMemoryRecording ¶ added in v1.0.6
func NewMemoryRecording() *MemoryRecording
NewMemoryRecording creates a new in-memory recording buffer.
func (*MemoryRecording) Clear ¶ added in v1.0.6
func (r *MemoryRecording) Clear()
Clear discards all recorded data.
func (*MemoryRecording) Data ¶ added in v1.0.6
func (r *MemoryRecording) Data() []byte
Data returns all captured bytes since the last Clear call.
func (*MemoryRecording) Record ¶ added in v1.0.6
func (r *MemoryRecording) Record(data []byte)
Record appends raw bytes to the recording.
type MemoryScrollback ¶ added in v1.0.6
type MemoryScrollback struct {
// contains filtered or unexported fields
}
MemoryScrollback stores scrollback lines in memory with a configurable limit. When the limit is reached, the oldest lines are removed to make room for new ones.
Example:
storage := headlessterm.NewMemoryScrollback(10000) term := headlessterm.New(headlessterm.WithScrollback(storage))
func NewMemoryScrollback ¶ added in v1.0.6
func NewMemoryScrollback(maxLines int) *MemoryScrollback
NewMemoryScrollback creates a new in-memory scrollback buffer with the given capacity. If maxLines is 0, scrollback is unlimited (be careful with memory usage).
func (*MemoryScrollback) Clear ¶ added in v1.0.6
func (m *MemoryScrollback) Clear()
Clear removes all stored lines.
func (*MemoryScrollback) Len ¶ added in v1.0.6
func (m *MemoryScrollback) Len() int
Len returns the current number of stored lines.
func (*MemoryScrollback) Line ¶ added in v1.0.6
func (m *MemoryScrollback) Line(index int) []Cell
Line returns the line at index, where 0 is the oldest line. Returns nil if index is out of range.
func (*MemoryScrollback) MaxLines ¶ added in v1.0.6
func (m *MemoryScrollback) MaxLines() int
MaxLines returns the current maximum capacity.
func (*MemoryScrollback) Pop ¶ added in v1.0.8
func (m *MemoryScrollback) Pop() []Cell
Pop removes and returns the most recent (newest) line from scrollback. Returns nil if scrollback is empty.
func (*MemoryScrollback) Push ¶ added in v1.0.6
func (m *MemoryScrollback) Push(line []Cell)
Push appends a line to scrollback. If maxLines is exceeded, the oldest line is removed.
func (*MemoryScrollback) SetMaxLines ¶ added in v1.0.6
func (m *MemoryScrollback) SetMaxLines(max int)
SetMaxLines sets the maximum capacity. If the current length exceeds the new max, the oldest lines are removed.
type Middleware ¶
type Middleware struct {
// Input wraps the Input handler
Input func(r rune, next func(rune))
// Bell wraps the Bell handler
Bell func(next func())
// Backspace wraps the Backspace handler
Backspace func(next func())
// CarriageReturn wraps the CarriageReturn handler
CarriageReturn func(next func())
// LineFeed wraps the LineFeed handler
LineFeed func(next func())
// Tab wraps the Tab handler
Tab func(n int, next func(int))
// ClearLine wraps the ClearLine handler
ClearLine func(mode ansicode.LineClearMode, next func(ansicode.LineClearMode))
// ClearScreen wraps the ClearScreen handler
ClearScreen func(mode ansicode.ClearMode, next func(ansicode.ClearMode))
// ClearTabs wraps the ClearTabs handler
ClearTabs func(mode ansicode.TabulationClearMode, next func(ansicode.TabulationClearMode))
// Goto wraps the Goto handler
Goto func(row, col int, next func(int, int))
// GotoLine wraps the GotoLine handler
GotoLine func(row int, next func(int))
// GotoCol wraps the GotoCol handler
GotoCol func(col int, next func(int))
// MoveUp wraps the MoveUp handler
MoveUp func(n int, next func(int))
// MoveDown wraps the MoveDown handler
MoveDown func(n int, next func(int))
// MoveForward wraps the MoveForward handler
MoveForward func(n int, next func(int))
// MoveBackward wraps the MoveBackward handler
MoveBackward func(n int, next func(int))
// MoveUpCr wraps the MoveUpCr handler
MoveUpCr func(n int, next func(int))
// MoveDownCr wraps the MoveDownCr handler
MoveDownCr func(n int, next func(int))
// MoveForwardTabs wraps the MoveForwardTabs handler
MoveForwardTabs func(n int, next func(int))
// MoveBackwardTabs wraps the MoveBackwardTabs handler
MoveBackwardTabs func(n int, next func(int))
// InsertBlank wraps the InsertBlank handler
InsertBlank func(n int, next func(int))
// InsertBlankLines wraps the InsertBlankLines handler
InsertBlankLines func(n int, next func(int))
// DeleteChars wraps the DeleteChars handler
DeleteChars func(n int, next func(int))
// DeleteLines wraps the DeleteLines handler
DeleteLines func(n int, next func(int))
// EraseChars wraps the EraseChars handler
EraseChars func(n int, next func(int))
// ScrollUp wraps the ScrollUp handler
ScrollUp func(n int, next func(int))
// ScrollDown wraps the ScrollDown handler
ScrollDown func(n int, next func(int))
// SetScrollingRegion wraps the SetScrollingRegion handler
SetScrollingRegion func(top, bottom int, next func(int, int))
// SetMode wraps the SetMode handler
SetMode func(mode ansicode.TerminalMode, next func(ansicode.TerminalMode))
// UnsetMode wraps the UnsetMode handler
UnsetMode func(mode ansicode.TerminalMode, next func(ansicode.TerminalMode))
// SetTerminalCharAttribute wraps the SetTerminalCharAttribute handler
SetTerminalCharAttribute func(attr ansicode.TerminalCharAttribute, next func(ansicode.TerminalCharAttribute))
// SetTitle wraps the SetTitle handler
SetTitle func(title string, next func(string))
// SetCursorStyle wraps the SetCursorStyle handler
SetCursorStyle func(style ansicode.CursorStyle, next func(ansicode.CursorStyle))
// SaveCursorPosition wraps the SaveCursorPosition handler
SaveCursorPosition func(next func())
// RestoreCursorPosition wraps the RestoreCursorPosition handler
RestoreCursorPosition func(next func())
// ReverseIndex wraps the ReverseIndex handler
ReverseIndex func(next func())
// ResetState wraps the ResetState handler
ResetState func(next func())
// Substitute wraps the Substitute handler
Substitute func(next func())
// Decaln wraps the Decaln handler
Decaln func(next func())
// DeviceStatus wraps the DeviceStatus handler
DeviceStatus func(n int, next func(int))
// IdentifyTerminal wraps the IdentifyTerminal handler
IdentifyTerminal func(b byte, next func(byte))
// ConfigureCharset wraps the ConfigureCharset handler
ConfigureCharset func(index ansicode.CharsetIndex, charset ansicode.Charset, next func(ansicode.CharsetIndex, ansicode.Charset))
// SetActiveCharset wraps the SetActiveCharset handler
SetActiveCharset func(n int, next func(int))
// SetKeypadApplicationMode wraps the SetKeypadApplicationMode handler
SetKeypadApplicationMode func(next func())
// UnsetKeypadApplicationMode wraps the UnsetKeypadApplicationMode handler
UnsetKeypadApplicationMode func(next func())
// SetColor wraps the SetColor handler
SetColor func(index int, c color.Color, next func(int, color.Color))
// ResetColor wraps the ResetColor handler
ResetColor func(i int, next func(int))
// SetDynamicColor wraps the SetDynamicColor handler
SetDynamicColor func(prefix string, index int, terminator string, next func(string, int, string))
// ClipboardLoad wraps the ClipboardLoad handler
ClipboardLoad func(clipboard byte, terminator string, next func(byte, string))
// ClipboardStore wraps the ClipboardStore handler
ClipboardStore func(clipboard byte, data []byte, next func(byte, []byte))
// SetHyperlink wraps the SetHyperlink handler
SetHyperlink func(hyperlink *ansicode.Hyperlink, next func(*ansicode.Hyperlink))
// PushTitle wraps the PushTitle handler
PushTitle func(next func())
// PopTitle wraps the PopTitle handler
PopTitle func(next func())
// TextAreaSizeChars wraps the TextAreaSizeChars handler
TextAreaSizeChars func(next func())
// TextAreaSizePixels wraps the TextAreaSizePixels handler
TextAreaSizePixels func(next func())
// HorizontalTabSet wraps the HorizontalTabSet handler
HorizontalTabSet func(next func())
// SetKeyboardMode wraps the SetKeyboardMode handler
SetKeyboardMode func(mode ansicode.KeyboardMode, behavior ansicode.KeyboardModeBehavior, next func(ansicode.KeyboardMode, ansicode.KeyboardModeBehavior))
// PushKeyboardMode wraps the PushKeyboardMode handler
PushKeyboardMode func(mode ansicode.KeyboardMode, next func(ansicode.KeyboardMode))
// PopKeyboardMode wraps the PopKeyboardMode handler
PopKeyboardMode func(n int, next func(int))
// ReportKeyboardMode wraps the ReportKeyboardMode handler
ReportKeyboardMode func(next func())
// SetModifyOtherKeys wraps the SetModifyOtherKeys handler
SetModifyOtherKeys func(modify ansicode.ModifyOtherKeys, next func(ansicode.ModifyOtherKeys))
// ReportModifyOtherKeys wraps the ReportModifyOtherKeys handler
ReportModifyOtherKeys func(next func())
// ApplicationCommandReceived wraps the ApplicationCommandReceived handler
ApplicationCommandReceived func(data []byte, next func([]byte))
// PrivacyMessageReceived wraps the PrivacyMessageReceived handler
PrivacyMessageReceived func(data []byte, next func([]byte))
// StartOfStringReceived wraps the StartOfStringReceived handler
StartOfStringReceived func(data []byte, next func([]byte))
// SemanticPromptMark wraps the SemanticPromptMark handler
SemanticPromptMark func(mark ansicode.ShellIntegrationMark, exitCode int, next func(ansicode.ShellIntegrationMark, int))
// SetWorkingDirectory wraps the SetWorkingDirectory handler
SetWorkingDirectory func(uri string, next func(string))
// SixelReceived wraps the SixelReceived handler
SixelReceived func(params [][]uint16, data []byte, next func([][]uint16, []byte))
// DesktopNotification wraps the DesktopNotification handler (OSC 99)
DesktopNotification func(payload *NotificationPayload, next func(*NotificationPayload))
// SetUserVar wraps the SetUserVar handler (OSC 1337)
SetUserVar func(name, value string, next func(string, string))
}
Middleware intercepts ANSI handler calls, allowing custom behavior before/after execution. Each field wraps one handler: receive original parameters and a next function to call the default implementation.
func (*Middleware) Merge ¶
func (m *Middleware) Merge(other *Middleware)
Merge copies non-nil middleware functions from other into this, overwriting existing values.
type NamedColor ¶
type NamedColor struct {
Name int
}
NamedColor references a color by semantic name (foreground, background, cursor, etc.). Resolution to actual RGBA happens at render time using the palette and defaults.
func (*NamedColor) RGBA ¶
func (c *NamedColor) RGBA() (r, g, b, a uint32)
RGBA implements color.Color, returning a placeholder (actual resolution happens at render time).
type NoopClipboard ¶
type NoopClipboard struct{}
NoopClipboard ignores all clipboard operations.
func (NoopClipboard) Read ¶
func (NoopClipboard) Read(clipboard byte) string
func (NoopClipboard) Write ¶
func (NoopClipboard) Write(clipboard byte, data []byte)
type NoopNotification ¶ added in v1.0.7
type NoopNotification struct{}
NoopNotification ignores all notification events.
func (NoopNotification) Notify ¶ added in v1.0.7
func (NoopNotification) Notify(payload *NotificationPayload) string
Notify discards the notification and returns no response.
type NoopPTYWriter ¶ added in v1.0.9
type NoopPTYWriter struct{}
NoopPTYWriter discards all response data (useful when responses are not needed).
type NoopRecording ¶
type NoopRecording struct{}
NoopRecording discards all input recordings.
func (NoopRecording) Clear ¶
func (NoopRecording) Clear()
func (NoopRecording) Data ¶
func (NoopRecording) Data() []byte
func (NoopRecording) Record ¶
func (NoopRecording) Record([]byte)
type NoopScrollback ¶
type NoopScrollback struct{}
NoopScrollback discards all scrollback lines (useful for alternate buffer which has no scrollback).
func (NoopScrollback) Clear ¶
func (NoopScrollback) Clear()
func (NoopScrollback) Len ¶
func (NoopScrollback) Len() int
func (NoopScrollback) Line ¶
func (NoopScrollback) Line(index int) []Cell
func (NoopScrollback) MaxLines ¶
func (NoopScrollback) MaxLines() int
func (NoopScrollback) Pop ¶ added in v1.0.8
func (NoopScrollback) Pop() []Cell
func (NoopScrollback) Push ¶
func (NoopScrollback) Push(line []Cell)
func (NoopScrollback) SetMaxLines ¶
func (NoopScrollback) SetMaxLines(max int)
type NoopSemanticPromptHandler ¶ added in v1.0.8
type NoopSemanticPromptHandler struct{}
NoopSemanticPromptHandler ignores all semantic prompt events.
func (NoopSemanticPromptHandler) OnMark ¶ added in v1.0.8
func (NoopSemanticPromptHandler) OnMark(mark ansicode.ShellIntegrationMark, exitCode int)
type NoopSizeProvider ¶ added in v1.0.1
type NoopSizeProvider struct{}
NoopSizeProvider returns default values for size queries.
func (NoopSizeProvider) CellSizePixels ¶ added in v1.0.1
func (NoopSizeProvider) CellSizePixels() (width, height int)
func (NoopSizeProvider) WindowSizePixels ¶ added in v1.0.1
func (NoopSizeProvider) WindowSizePixels() (width, height int)
type NotificationPayload ¶ added in v1.0.7
type NotificationPayload = ansicode.NotificationPayload
NotificationPayload is re-exported from go-ansicode for use by notification providers. This allows consumers to implement NotificationProvider without importing go-ansicode directly.
type NotificationProvider ¶ added in v1.0.7
type NotificationProvider interface {
// Notify processes a notification payload and optionally returns a response.
// For query requests (PayloadType == "?"), implementations should return
// a string describing supported capabilities in OSC 99 format.
// For other requests, return empty string.
Notify(payload *NotificationPayload) string
}
NotificationProvider handles OSC 99 desktop notifications (Kitty protocol). Implementations can display native desktop notifications, log them, or process them in any other way appropriate for the platform.
The Kitty notification protocol supports:
- Title and body text
- Urgency levels (low, normal, critical)
- Icons (by name or PNG data)
- Sound control (system, silent, error, etc.)
- Chunking for large payloads
- Query mechanism for capability discovery
- Close tracking for notification lifecycle
Note: Buttons are NOT supported (same as Kitty on macOS). Applications that query capabilities will see buttons are not reported, and button payloads are silently ignored.
type Option ¶
type Option func(*Terminal)
Option configures a Terminal during construction.
func WithAPC ¶
func WithAPC(p APCProvider) Option
WithAPC sets the handler for Application Program Command sequences. Defaults to a no-op if not set.
func WithAutoResize ¶
func WithAutoResize() Option
WithAutoResize enables growth mode: the buffer expands instead of scrolling or wrapping. Useful for capturing complete output without truncation.
func WithBell ¶
func WithBell(p BellProvider) Option
WithBell sets the handler for bell/beep events. Defaults to a no-op if not set.
func WithClipboard ¶
func WithClipboard(p ClipboardProvider) Option
WithClipboard sets the handler for clipboard read/write operations (OSC 52). Defaults to a no-op if not set.
func WithKitty ¶ added in v1.0.5
WithKitty enables or disables Kitty graphics protocol support. When disabled, Kitty graphics APC sequences are ignored. Default is true (enabled).
func WithMiddleware ¶
func WithMiddleware(mw *Middleware) Option
WithMiddleware sets functions to intercept ANSI handler calls. Each middleware receives the original parameters and a next function to call the default implementation.
func WithNotification ¶ added in v1.0.7
func WithNotification(p NotificationProvider) Option
WithNotification sets the handler for OSC 99 desktop notifications (Kitty protocol). The provider receives notification payloads and can display native desktop notifications. Query requests (PayloadType == "?") should return a capability string that is written back to the terminal. Defaults to a no-op if not set.
func WithPM ¶
func WithPM(p PMProvider) Option
WithPM sets the handler for Privacy Message sequences. Defaults to a no-op if not set.
func WithPTYWriter ¶ added in v1.0.9
WithPTYWriter sets the writer for terminal responses (e.g., cursor position reports). If nil, responses are discarded.
func WithRecording ¶
func WithRecording(p RecordingProvider) Option
WithRecording sets the handler for capturing raw input bytes before ANSI parsing. Useful for replay, debugging, or regression testing.
func WithSOS ¶
func WithSOS(p SOSProvider) Option
WithSOS sets the handler for Start of String sequences. Defaults to a no-op if not set.
func WithScrollback ¶
func WithScrollback(storage ScrollbackProvider) Option
WithScrollback sets the storage for scrollback lines. Lines scrolled off the top are pushed here. Defaults to a no-op if not set.
func WithSemanticPromptHandler ¶ added in v1.0.8
func WithSemanticPromptHandler(h SemanticPromptHandler) Option
WithSemanticPromptHandler sets the handler for semantic prompt events (OSC 133).
func WithSixel ¶ added in v1.0.5
WithSixel enables or disables Sixel graphics protocol support. When disabled, Sixel sequences are ignored. Default is true (enabled).
func WithSize ¶
WithSize sets the terminal dimensions. Values <= 0 are replaced with defaults (24x80).
func WithSizeProvider ¶ added in v1.0.1
func WithSizeProvider(p SizeProvider) Option
WithSizeProvider sets the provider for pixel dimension queries.
func WithTitle ¶
func WithTitle(p TitleProvider) Option
WithTitle sets the handler for window title changes. Defaults to a no-op if not set.
type PMProvider ¶
type PMProvider interface {
// Receive is called with the payload of a PM sequence.
Receive(data []byte)
}
PMProvider handles Privacy Message sequences (OSC ^).
type PTYWriter ¶ added in v1.0.9
PTYWriter writes terminal responses (e.g., cursor position reports) back to the PTY. This is used for DSR (Device Status Report), DA (Device Attributes), and other terminal queries that require a response to be sent back to the controlling process.
type Position ¶
Position identifies a cell location in the terminal grid (0-based). Row semantics depend on the API:
- Search(), SetSelection(), GetSelectedText(): viewport-relative (0 to Rows()-1)
- SearchScrollback(): negative for scrollback (-1 = most recent scrollback line)
- Shell integration (PromptMark.Row): absolute (includes scrollback offset)
Use ViewportRowToAbsolute/AbsoluteRowToViewport to convert between systems.
type PromptMark ¶ added in v1.0.1
type PromptMark struct {
// Type is the mark type (PromptStart, CommandStart, CommandExecuted, CommandFinished).
Type ansicode.ShellIntegrationMark
// Row is the absolute row position (including scrollback offset).
// Negative values indicate scrollback lines (-1 is most recent scrollback line).
Row int
// ExitCode is the command exit code (only valid for CommandFinished marks, -1 otherwise).
ExitCode int
}
PromptMark stores information about a semantic prompt mark (OSC 133). Used for prompt-based navigation in scrollback.
type RecordingProvider ¶
type RecordingProvider interface {
// Record appends raw bytes to the recording.
Record(data []byte)
// Data returns all captured bytes since the last Clear call.
Data() []byte
// Clear discards all recorded data.
Clear()
}
RecordingProvider captures raw input bytes before ANSI parsing for replay or debugging.
type SOSProvider ¶
type SOSProvider interface {
// Receive is called with the payload of a SOS sequence.
Receive(data []byte)
}
SOSProvider handles Start of String sequences (OSC X).
type SavedCursor ¶
type SavedCursor struct {
Row int
Col int
Attrs CellTemplate
OriginMode bool
CharsetIndex int
Charsets [4]Charset
}
SavedCursor stores cursor position, cell attributes, and charset state for restoration. Used when switching between primary and alternate screens.
type ScrollbackProvider ¶
type ScrollbackProvider interface {
// Push appends a line to scrollback. Oldest lines should be removed if MaxLines is exceeded.
Push(line []Cell)
// Pop removes and returns the most recent (newest) line from scrollback.
// Returns nil if scrollback is empty.
Pop() []Cell
// Len returns the current number of stored lines.
Len() int
// Line returns the line at index, where 0 is the oldest line. Returns nil if out of range.
Line(index int) []Cell
// Clear removes all stored lines.
Clear()
// SetMaxLines sets the maximum capacity. Implementations should trim oldest lines if needed.
SetMaxLines(max int)
// MaxLines returns the current maximum capacity.
MaxLines() int
}
ScrollbackProvider stores lines scrolled off the top of the primary buffer. Implementations can use in-memory storage, disk, database, etc.
type Selection ¶
Selection defines a rectangular text region in the terminal. Start and End are normalized so Start is always before or equal to End.
type SemanticPromptHandler ¶ added in v1.0.8
type SemanticPromptHandler interface {
// OnMark is called when a semantic prompt mark is received.
OnMark(mark ansicode.ShellIntegrationMark, exitCode int)
}
SemanticPromptHandler handles semantic prompt events (OSC 133).
type SixelImage ¶ added in v1.0.1
type SixelImage struct {
Width uint32
Height uint32
Data []byte // RGBA pixel data
Transparent bool // Whether background is transparent
}
SixelImage represents a decoded Sixel image.
func ParseSixel ¶ added in v1.0.1
func ParseSixel(params []int64, data []byte) (*SixelImage, error)
ParseSixel parses Sixel data and returns an RGBA image. params contains the DCS parameters (P1;P2;P3). data contains the raw Sixel bytes after 'q'.
type SizeProvider ¶ added in v1.0.1
type SizeProvider interface {
// WindowSizePixels returns the terminal window size in pixels.
WindowSizePixels() (width, height int)
// CellSizePixels returns the size of a single cell in pixels.
CellSizePixels() (width, height int)
}
SizeProvider provides pixel dimensions for CSI queries.
type Snapshot ¶ added in v1.0.6
type Snapshot struct {
Size SnapshotSize `json:"size"`
Cursor SnapshotCursor `json:"cursor"`
Lines []SnapshotLine `json:"lines"`
Images []SnapshotImage `json:"images,omitempty"`
}
Snapshot represents a complete terminal screen capture.
type SnapshotAttrs ¶ added in v1.0.6
type SnapshotAttrs struct {
Bold bool `json:"bold,omitempty"`
Dim bool `json:"dim,omitempty"`
Italic bool `json:"italic,omitempty"`
Underline string `json:"underline,omitempty"` // "", "single", "double", "curly", "dotted", "dashed"
Blink string `json:"blink,omitempty"` // "", "slow", "fast"
Reverse bool `json:"reverse,omitempty"`
Hidden bool `json:"hidden,omitempty"`
Strikethrough bool `json:"strikethrough,omitempty"`
}
SnapshotAttrs holds text formatting attributes.
type SnapshotCell ¶ added in v1.0.6
type SnapshotCell struct {
Char string `json:"char"`
Fg string `json:"fg"`
Bg string `json:"bg"`
UnderlineColor string `json:"underline_color,omitempty"`
Attributes SnapshotAttrs `json:"attrs,omitempty"`
Hyperlink *SnapshotLink `json:"hyperlink,omitempty"`
Image *SnapshotCellImage `json:"image,omitempty"`
Wide bool `json:"wide,omitempty"`
WideSpacer bool `json:"wide_spacer,omitempty"`
}
SnapshotCell represents a single cell with full attributes.
type SnapshotCellImage ¶ added in v1.0.6
type SnapshotCellImage struct {
ImageID uint32 `json:"image_id"`
PlacementID uint32 `json:"placement_id"`
U0 float32 `json:"u0"` // Texture coordinates
V0 float32 `json:"v0"`
U1 float32 `json:"u1"`
V1 float32 `json:"v1"`
ScaleX float32 `json:"scale_x"`
ScaleY float32 `json:"scale_y"`
}
SnapshotCellImage holds image reference information for a cell.
type SnapshotCursor ¶ added in v1.0.6
type SnapshotCursor struct {
Row int `json:"row"`
Col int `json:"col"`
Visible bool `json:"visible"`
Style string `json:"style"`
}
SnapshotCursor holds cursor state.
type SnapshotDetail ¶ added in v1.0.6
type SnapshotDetail string
SnapshotDetail specifies the level of detail in a snapshot.
const ( // SnapshotDetailText returns plain text only. SnapshotDetailText SnapshotDetail = "text" // SnapshotDetailStyled returns text with style segments per line. SnapshotDetailStyled SnapshotDetail = "styled" // SnapshotDetailFull returns full cell-by-cell data. SnapshotDetailFull SnapshotDetail = "full" )
type SnapshotImage ¶ added in v1.0.6
type SnapshotImage struct {
ID uint32 `json:"id"` // Unique image ID
PlacementID uint32 `json:"placement_id"` // Unique placement ID
Row int `json:"row"` // Position row (cells)
Col int `json:"col"` // Position column (cells)
Rows int `json:"rows"` // Size in rows (cells)
Cols int `json:"cols"` // Size in columns (cells)
PixelWidth uint32 `json:"pixel_width"` // Original image width (pixels)
PixelHeight uint32 `json:"pixel_height"` // Original image height (pixels)
ZIndex int32 `json:"z_index"` // Z-index for layering
}
SnapshotImage holds image placement metadata (without pixel data).
type SnapshotLine ¶ added in v1.0.6
type SnapshotLine struct {
Text string `json:"text"`
Segments []SnapshotSegment `json:"segments,omitempty"`
Cells []SnapshotCell `json:"cells,omitempty"`
}
SnapshotLine represents a single line in the snapshot.
type SnapshotLink ¶ added in v1.0.6
SnapshotLink holds hyperlink information.
type SnapshotSegment ¶ added in v1.0.6
type SnapshotSegment struct {
Text string `json:"text"`
Fg string `json:"fg,omitempty"`
Bg string `json:"bg,omitempty"`
UnderlineColor string `json:"underline_color,omitempty"`
Attributes SnapshotAttrs `json:"attrs,omitempty"`
Hyperlink *SnapshotLink `json:"hyperlink,omitempty"`
}
SnapshotSegment represents a styled text segment within a line.
type SnapshotSize ¶ added in v1.0.6
SnapshotSize holds terminal dimensions.
type Terminal ¶
type Terminal struct {
// contains filtered or unexported fields
}
Terminal emulates a VT220-compatible terminal without a display. It maintains two buffers: primary (with scrollback) and alternate (no scrollback). The active buffer switches when entering/exiting alternate screen mode. All operations are thread-safe via internal locking.
func New ¶
New creates a terminal with the given options. Defaults to 24x80 with line wrap and cursor visible.
func (*Terminal) APCProvider ¶
func (t *Terminal) APCProvider() APCProvider
APCProvider returns the current APC provider.
func (*Terminal) AbsoluteRowToViewport ¶ added in v1.0.8
AbsoluteRowToViewport converts an absolute row to a viewport row. Returns -1 if the row is in scrollback or beyond the visible viewport. Use this to convert shell integration row values (like PromptMark.Row) to viewport coordinates for functions like Cell() or LineContent().
func (*Terminal) ApplicationCommandReceived ¶
ApplicationCommandReceived processes an APC sequence and delegates to the configured provider.
func (*Terminal) AutoResize ¶
AutoResize returns true if growth mode is enabled (buffer expands instead of scrolling/wrapping).
func (*Terminal) Backspace ¶
func (t *Terminal) Backspace()
Backspace moves the cursor one column left, stopping at column 0.
func (*Terminal) BellProvider ¶
func (t *Terminal) BellProvider() BellProvider
BellProvider returns the current bell provider.
func (*Terminal) CarriageReturn ¶
func (t *Terminal) CarriageReturn()
CarriageReturn moves the cursor to column 0 of the current row.
func (*Terminal) Cell ¶
Cell returns the cell at (row, col) in the active buffer. Row is viewport-relative (0 to Rows()-1), not absolute. Returns nil if coordinates are out of bounds.
func (*Terminal) CellSizePixels ¶ added in v1.0.1
func (t *Terminal) CellSizePixels()
CellSizePixels sends the cell size in pixels via DSR response.
func (*Terminal) ClearDirty ¶
func (t *Terminal) ClearDirty()
ClearDirty marks all cells as clean, resetting the dirty tracking state.
func (*Terminal) ClearImages ¶ added in v1.0.1
func (t *Terminal) ClearImages()
ClearImages removes all images and placements.
func (*Terminal) ClearLine ¶
func (t *Terminal) ClearLine(mode ansicode.LineClearMode)
ClearLine clears portions of the current line based on mode (right of cursor, left of cursor, or entire line).
func (*Terminal) ClearPromptMarks ¶ added in v1.0.1
func (t *Terminal) ClearPromptMarks()
ClearPromptMarks removes all recorded prompt marks.
func (*Terminal) ClearRecording ¶
func (t *Terminal) ClearRecording()
ClearRecording discards all captured input data.
func (*Terminal) ClearScreen ¶
ClearScreen clears screen regions based on mode (below cursor, above cursor, entire screen, or saved lines).
func (*Terminal) ClearScrollback ¶
func (t *Terminal) ClearScrollback()
ClearScrollback removes all stored scrollback lines.
func (*Terminal) ClearSelection ¶
func (t *Terminal) ClearSelection()
ClearSelection deactivates the current selection.
func (*Terminal) ClearTabs ¶
func (t *Terminal) ClearTabs(mode ansicode.TabulationClearMode)
ClearTabs removes tab stops at the current column or all columns based on mode.
func (*Terminal) ClearUserVars ¶ added in v1.0.8
func (t *Terminal) ClearUserVars()
ClearUserVars removes all user variables.
func (*Terminal) ClipboardLoad ¶
ClipboardLoad reads from the clipboard provider and sends the response via OSC 52.
func (*Terminal) ClipboardProvider ¶
func (t *Terminal) ClipboardProvider() ClipboardProvider
ClipboardProvider returns the current clipboard provider.
func (*Terminal) ClipboardStore ¶
ClipboardStore writes data to the clipboard provider via OSC 52.
func (*Terminal) ConfigureCharset ¶
func (t *Terminal) ConfigureCharset(index ansicode.CharsetIndex, charset ansicode.Charset)
ConfigureCharset sets the character set for one of the four slots (G0-G3).
func (*Terminal) CursorStyle ¶
func (t *Terminal) CursorStyle() CursorStyle
CursorStyle returns the current cursor rendering style.
func (*Terminal) CursorVisible ¶
CursorVisible returns true if the cursor is currently visible.
func (*Terminal) Decaln ¶
func (t *Terminal) Decaln()
Decaln fills the entire screen with 'E' characters (DEC screen alignment test).
func (*Terminal) DeleteChars ¶
DeleteChars removes n characters at the cursor, shifting remaining characters left.
func (*Terminal) DeleteLines ¶
DeleteLines removes n lines at the cursor within the scroll region, shifting remaining lines up.
func (*Terminal) DesktopNotification ¶ added in v1.0.7
func (t *Terminal) DesktopNotification(payload *NotificationPayload)
DesktopNotification handles OSC 99 desktop notification sequences (Kitty protocol). It delegates to the configured NotificationProvider if present. Responses from the provider (e.g., for query requests) are written back to the terminal.
func (*Terminal) DeviceStatus ¶
DeviceStatus sends a device status report (DSR) response: ready (n=5) or cursor position (n=6).
func (*Terminal) DirtyCells ¶
DirtyCells returns positions of all cells modified since the last ClearDirty call.
func (*Terminal) EraseChars ¶
EraseChars resets n characters at the cursor to default state without shifting.
func (*Terminal) GetImageData ¶ added in v1.0.6
func (t *Terminal) GetImageData(id uint32) *ImageSnapshot
GetImageData returns the image data for the given ID, or nil if not found.
func (*Terminal) GetLastCommandOutput ¶ added in v1.0.1
GetLastCommandOutput returns the output of the last executed command. It finds the text between the last CommandExecuted (C) mark and the last CommandFinished (D) mark. Returns empty string if no complete command output is available.
func (*Terminal) GetPromptMarkAt ¶ added in v1.0.1
func (t *Terminal) GetPromptMarkAt(absRow int) *PromptMark
GetPromptMarkAt returns the prompt mark at the given absolute row, or nil if none exists.
func (*Terminal) GetSelectedText ¶
GetSelectedText extracts and returns the text content within the active selection. Empty cells are converted to spaces, and newlines separate rows.
func (*Terminal) GetSelection ¶
GetSelection returns the current selection state.
func (*Terminal) GetUserVar ¶ added in v1.0.8
GetUserVar returns the value of a user variable, or empty string if not set.
func (*Terminal) GetUserVars ¶ added in v1.0.8
GetUserVars returns a copy of all user variables.
func (*Terminal) GotoCol ¶
GotoCol moves the cursor to the specified column, keeping the current row.
func (*Terminal) GotoLine ¶
GotoLine moves the cursor to the specified row, adjusting for origin mode if enabled.
func (*Terminal) HasDirty ¶
HasDirty returns true if any cell in the active buffer was modified since the last ClearDirty call.
func (*Terminal) HasMode ¶
func (t *Terminal) HasMode(mode TerminalMode) bool
HasMode returns true if the specified mode flag is enabled.
func (*Terminal) HasSelection ¶
HasSelection returns true if a selection is currently active.
func (*Terminal) HorizontalTabSet ¶
func (t *Terminal) HorizontalTabSet()
HorizontalTabSet enables a tab stop at the current column.
func (*Terminal) IdentifyTerminal ¶
IdentifyTerminal sends a terminal identification response (default: VT220).
func (*Terminal) Image ¶ added in v1.0.1
Image returns the image data for the given ID, or nil if not found.
func (*Terminal) ImageCount ¶ added in v1.0.1
ImageCount returns the number of stored images.
func (*Terminal) ImagePlacementCount ¶ added in v1.0.1
ImagePlacementCount returns the number of active image placements.
func (*Terminal) ImagePlacements ¶ added in v1.0.1
func (t *Terminal) ImagePlacements() []*ImagePlacement
ImagePlacements returns all current image placements.
func (*Terminal) ImageUsedMemory ¶ added in v1.0.1
ImageUsedMemory returns the current image memory usage in bytes.
func (*Terminal) Input ¶
Input writes a character to the buffer at the cursor position. Handles wide characters, line wrapping, insert mode, and charset translation.
func (*Terminal) InsertBlank ¶
InsertBlank inserts n blank cells at the cursor, shifting existing characters right.
func (*Terminal) InsertBlankLines ¶
InsertBlankLines inserts n blank lines at the cursor within the scroll region, shifting remaining lines down.
func (*Terminal) IsAlternateScreen ¶
IsAlternateScreen returns true if the alternate buffer is currently active. The alternate buffer has no scrollback and is typically used by full-screen applications.
func (*Terminal) IsSelected ¶
IsSelected returns true if the cell at (row, col) is within the active selection.
func (*Terminal) IsWrapped ¶
IsWrapped returns true if the line was wrapped due to column overflow, false if it ended with an explicit newline. Row is viewport-relative (0 to Rows()-1), not absolute.
func (*Terminal) KittyEnabled ¶ added in v1.0.5
KittyEnabled returns true if Kitty graphics protocol is enabled.
func (*Terminal) LineContent ¶
LineContent returns the text content of a line, trimming trailing spaces. Row is viewport-relative (0 to Rows()-1), not absolute. Returns empty string if the line contains only spaces or is out of bounds.
func (*Terminal) LineFeed ¶
func (t *Terminal) LineFeed()
LineFeed moves the cursor down one row. If ModeLineFeedNewLine is set, also moves to column 0. Clears the wrapped flag for the current line (indicates explicit newline).
func (*Terminal) MaxScrollback ¶
MaxScrollback returns the current maximum scrollback capacity.
func (*Terminal) Middleware ¶
func (t *Terminal) Middleware() *Middleware
Middleware returns the current middleware.
func (*Terminal) MoveBackward ¶
MoveBackward moves the cursor left n columns, stopping at column 0.
func (*Terminal) MoveBackwardTabs ¶
MoveBackwardTabs moves the cursor left to the previous n tab stops.
func (*Terminal) MoveDownCr ¶
MoveDownCr moves the cursor down n rows and to column 0.
func (*Terminal) MoveForward ¶
MoveForward moves the cursor right n columns, stopping at the last column.
func (*Terminal) MoveForwardTabs ¶
MoveForwardTabs moves the cursor right to the next n tab stops.
func (*Terminal) NextPromptRow ¶ added in v1.0.1
func (t *Terminal) NextPromptRow(currentAbsRow int, markType ansicode.ShellIntegrationMark) int
NextPromptRow returns the absolute row of the next prompt mark after the given absolute row. Returns -1 if no next prompt exists. If markType is specified (not -1), only returns marks of that type.
func (*Terminal) NotificationProvider ¶ added in v1.0.7
func (t *Terminal) NotificationProvider() NotificationProvider
NotificationProvider returns the current notification provider.
func (*Terminal) PMProvider ¶
func (t *Terminal) PMProvider() PMProvider
PMProvider returns the current PM provider.
func (*Terminal) PopKeyboardMode ¶
PopKeyboardMode removes n keyboard mode entries from the stack.
func (*Terminal) PopTitle ¶
func (t *Terminal) PopTitle()
PopTitle restores the previous title from the stack.
func (*Terminal) PrevPromptRow ¶ added in v1.0.1
func (t *Terminal) PrevPromptRow(currentAbsRow int, markType ansicode.ShellIntegrationMark) int
PrevPromptRow returns the absolute row of the previous prompt mark before the given absolute row. Returns -1 if no previous prompt exists. If markType is specified (not -1), only returns marks of that type.
func (*Terminal) PrivacyMessageReceived ¶
PrivacyMessageReceived processes a PM sequence and delegates to the configured provider.
func (*Terminal) PromptMarkCount ¶ added in v1.0.1
PromptMarkCount returns the number of recorded prompt marks.
func (*Terminal) PromptMarks ¶ added in v1.0.1
func (t *Terminal) PromptMarks() []PromptMark
PromptMarks returns all recorded prompt marks.
func (*Terminal) PushKeyboardMode ¶
func (t *Terminal) PushKeyboardMode(mode ansicode.KeyboardMode)
PushKeyboardMode adds a keyboard mode to the stack.
func (*Terminal) PushTitle ¶
func (t *Terminal) PushTitle()
PushTitle saves the current title to the stack.
func (*Terminal) RecordedData ¶
RecordedData returns all raw input bytes captured since the last ClearRecording call.
func (*Terminal) RecordingProvider ¶
func (t *Terminal) RecordingProvider() RecordingProvider
RecordingProvider returns the current recording handler.
func (*Terminal) ReportKeyboardMode ¶
func (t *Terminal) ReportKeyboardMode()
ReportKeyboardMode sends the current keyboard mode via DSR response.
func (*Terminal) ReportModifyOtherKeys ¶
func (t *Terminal) ReportModifyOtherKeys()
ReportModifyOtherKeys sends the current modify-other-keys mode via DSR response.
func (*Terminal) ResetColor ¶
ResetColor removes a custom color from the palette at the given index.
func (*Terminal) ResetState ¶
func (t *Terminal) ResetState()
ResetState clears the screen, resets cursor to (0,0), and restores default modes and attributes.
func (*Terminal) Resize ¶
Resize changes the terminal dimensions and adjusts buffers accordingly. When shrinking rows, lines above cursor are moved to scrollback to preserve content near the cursor. Cursor position is clamped to the new bounds. Invalid dimensions (<= 0) are ignored.
func (*Terminal) RestoreCursorPosition ¶
func (t *Terminal) RestoreCursorPosition()
RestoreCursorPosition restores cursor position, attributes, and charset state from the saved cursor.
func (*Terminal) ReverseIndex ¶
func (t *Terminal) ReverseIndex()
ReverseIndex moves the cursor up one row. If at the top of the scroll region, scrolls down instead.
func (*Terminal) SOSProvider ¶
func (t *Terminal) SOSProvider() SOSProvider
SOSProvider returns the current SOS provider.
func (*Terminal) SaveCursorPosition ¶
func (t *Terminal) SaveCursorPosition()
SaveCursorPosition saves cursor position, attributes, charset state, and origin mode for later restoration.
func (*Terminal) ScrollDown ¶
ScrollDown shifts lines down within the scroll region, clearing top lines.
func (*Terminal) ScrollRegion ¶
ScrollRegion returns the current scrolling boundaries (0-based, exclusive bottom). When origin mode is enabled, cursor positioning is relative to scrollTop.
func (*Terminal) ScrollUp ¶
ScrollUp shifts lines up within the scroll region, pushing top lines to scrollback if enabled.
func (*Terminal) ScrollbackLen ¶
ScrollbackLen returns the number of lines stored in scrollback (primary buffer only).
func (*Terminal) ScrollbackLine ¶
ScrollbackLine returns a line from scrollback, where 0 is the oldest line. Returns nil if index is out of range.
func (*Terminal) ScrollbackProvider ¶
func (t *Terminal) ScrollbackProvider() ScrollbackProvider
ScrollbackProvider returns the current scrollback storage implementation.
func (*Terminal) Search ¶
Search finds all occurrences of pattern in the visible screen content. Returns positions of the first character of each match.
func (*Terminal) SearchScrollback ¶
SearchScrollback finds all occurrences of pattern in scrollback lines. Returned row values are negative, where -1 is the most recent scrollback line.
func (*Terminal) SemanticPromptHandlerValue ¶ added in v1.0.8
func (t *Terminal) SemanticPromptHandlerValue() SemanticPromptHandler
SemanticPromptHandlerValue returns the current semantic prompt handler.
func (*Terminal) SetAPCProvider ¶
func (t *Terminal) SetAPCProvider(p APCProvider)
SetAPCProvider sets the APC provider at runtime.
func (*Terminal) SetActiveCharset ¶
SetActiveCharset selects which charset slot (0-3, G0-G3) is currently active for character rendering.
func (*Terminal) SetBellProvider ¶
func (t *Terminal) SetBellProvider(p BellProvider)
SetBellProvider sets the bell provider at runtime.
func (*Terminal) SetClipboardProvider ¶
func (t *Terminal) SetClipboardProvider(c ClipboardProvider)
SetClipboardProvider sets the clipboard provider at runtime.
func (*Terminal) SetColor ¶
SetColor stores a custom color in the palette at the given index (used for indexed color resolution).
func (*Terminal) SetCursorStyle ¶
func (t *Terminal) SetCursorStyle(style ansicode.CursorStyle)
SetCursorStyle changes the cursor rendering style (block, underline, bar, blinking/steady).
func (*Terminal) SetDynamicColor ¶
SetDynamicColor responds to a dynamic color query (OSC 10/11/12) with the current color value.
func (*Terminal) SetHyperlink ¶
SetHyperlink sets the active hyperlink (OSC 8) for subsequently written characters. Pass nil to clear the hyperlink.
func (*Terminal) SetImageMaxMemory ¶ added in v1.0.1
SetImageMaxMemory sets the maximum memory budget for images.
func (*Terminal) SetKeyboardMode ¶
func (t *Terminal) SetKeyboardMode(mode ansicode.KeyboardMode, behavior ansicode.KeyboardModeBehavior)
SetKeyboardMode modifies the top keyboard mode on the stack using the specified behavior (replace, union, or difference).
func (*Terminal) SetKeypadApplicationMode ¶
func (t *Terminal) SetKeypadApplicationMode()
SetKeypadApplicationMode enables application keypad mode (numeric keypad sends escape sequences).
func (*Terminal) SetMaxScrollback ¶
SetMaxScrollback sets the maximum number of scrollback lines to retain. Older lines are automatically removed when the limit is exceeded.
func (*Terminal) SetMiddleware ¶
func (t *Terminal) SetMiddleware(mw *Middleware)
SetMiddleware sets the middleware at runtime.
func (*Terminal) SetMode ¶
func (t *Terminal) SetMode(mode ansicode.TerminalMode)
SetMode enables a terminal mode flag. Some modes have side effects (e.g., ModeOrigin moves cursor to scrollTop).
func (*Terminal) SetModifyOtherKeys ¶
func (t *Terminal) SetModifyOtherKeys(modify ansicode.ModifyOtherKeys)
SetModifyOtherKeys sets how modifier keys are reported in keyboard input.
func (*Terminal) SetNotificationProvider ¶ added in v1.0.7
func (t *Terminal) SetNotificationProvider(p NotificationProvider)
SetNotificationProvider sets the notification provider at runtime.
func (*Terminal) SetPMProvider ¶
func (t *Terminal) SetPMProvider(p PMProvider)
SetPMProvider sets the PM provider at runtime.
func (*Terminal) SetPTYWriter ¶ added in v1.0.9
SetPTYWriter sets the PTY writer at runtime.
func (*Terminal) SetRecordingProvider ¶
func (t *Terminal) SetRecordingProvider(p RecordingProvider)
SetRecordingProvider replaces the recording handler at runtime.
func (*Terminal) SetSOSProvider ¶
func (t *Terminal) SetSOSProvider(p SOSProvider)
SetSOSProvider sets the SOS provider at runtime.
func (*Terminal) SetScrollbackProvider ¶
func (t *Terminal) SetScrollbackProvider(storage ScrollbackProvider)
SetScrollbackProvider replaces the scrollback storage implementation at runtime.
func (*Terminal) SetScrollingRegion ¶
SetScrollingRegion sets the scroll boundaries (1-based, converted to 0-based internally). Moves cursor to home position (top-left of region if origin mode, else absolute top-left).
func (*Terminal) SetSelection ¶
SetSelection sets the active text selection region. Start and end are automatically normalized so start is before or equal to end.
func (*Terminal) SetSemanticPromptHandler ¶ added in v1.0.8
func (t *Terminal) SetSemanticPromptHandler(h SemanticPromptHandler)
SetSemanticPromptHandler sets the semantic prompt handler at runtime.
func (*Terminal) SetSizeProvider ¶ added in v1.0.4
func (t *Terminal) SetSizeProvider(p SizeProvider)
SetSizeProvider sets the provider for pixel dimension queries.
func (*Terminal) SetTerminalCharAttribute ¶
func (t *Terminal) SetTerminalCharAttribute(attr ansicode.TerminalCharAttribute)
SetTerminalCharAttribute applies SGR attributes to the cell template (colors, bold, underline, etc.).
func (*Terminal) SetTitleProvider ¶
func (t *Terminal) SetTitleProvider(p TitleProvider)
SetTitleProvider sets the title provider at runtime.
func (*Terminal) SetUserVar ¶ added in v1.0.8
SetUserVar stores a user variable (OSC 1337 SetUserVar).
func (*Terminal) SetWorkingDirectory ¶ added in v1.0.1
SetWorkingDirectory stores the current working directory (OSC 7).
func (*Terminal) SetWrapped ¶
SetWrapped sets whether the line was wrapped or ended with an explicit newline.
func (*Terminal) ShellIntegrationMark ¶ added in v1.0.1
func (t *Terminal) ShellIntegrationMark(mark ansicode.ShellIntegrationMark, exitCode int)
ShellIntegrationMark processes a semantic prompt mark (OSC 133). Records the mark position for prompt-based navigation. This method name is required by the ansicode.Handler interface.
func (*Terminal) SixelEnabled ¶ added in v1.0.5
SixelEnabled returns true if Sixel graphics protocol is enabled.
func (*Terminal) SixelReceived ¶ added in v1.0.1
SixelReceived handles incoming Sixel graphics data.
func (*Terminal) Snapshot ¶ added in v1.0.6
func (t *Terminal) Snapshot(detail SnapshotDetail) *Snapshot
Snapshot creates a snapshot of the current terminal state. The detail parameter controls how much information is included.
func (*Terminal) StartOfStringReceived ¶
StartOfStringReceived processes a SOS sequence and delegates to the configured provider.
func (*Terminal) String ¶
String returns the visible screen content as a newline-separated string. Trailing empty lines are omitted. Implements fmt.Stringer.
func (*Terminal) Substitute ¶
func (t *Terminal) Substitute()
Substitute replaces the character at the cursor with '?' (used for error indication).
func (*Terminal) TextAreaSizeChars ¶
func (t *Terminal) TextAreaSizeChars()
TextAreaSizeChars sends the terminal dimensions in characters via DSR response.
func (*Terminal) TextAreaSizePixels ¶
func (t *Terminal) TextAreaSizePixels()
TextAreaSizePixels sends the terminal dimensions in pixels via DSR response (assumes 10x20 pixel cells).
func (*Terminal) TitleProvider ¶
func (t *Terminal) TitleProvider() TitleProvider
TitleProvider returns the current title provider.
func (*Terminal) UnsetKeypadApplicationMode ¶
func (t *Terminal) UnsetKeypadApplicationMode()
UnsetKeypadApplicationMode disables application keypad mode (numeric keypad sends digits).
func (*Terminal) UnsetMode ¶
func (t *Terminal) UnsetMode(mode ansicode.TerminalMode)
UnsetMode disables a terminal mode flag. Some modes have side effects (e.g., ModeSwapScreenAndSetRestoreCursor restores primary buffer).
func (*Terminal) ViewportRowToAbsolute ¶ added in v1.0.8
ViewportRowToAbsolute converts a viewport row (0 to Rows()-1) to an absolute row. Absolute rows include the scrollback offset and are used by shell integration functions like NextPromptRow, PrevPromptRow, and GetPromptMarkAt.
func (*Terminal) WorkingDirectory ¶ added in v1.0.1
WorkingDirectory returns the current working directory URI (OSC 7).
func (*Terminal) WorkingDirectoryPath ¶ added in v1.0.1
WorkingDirectoryPath extracts the path from the working directory URI.
type TerminalMode ¶
type TerminalMode uint32
TerminalMode is a bitmask of terminal behavior flags. Multiple modes can be active simultaneously.
const ( // ModeCursorKeys enables cursor key mode (DECCKM). ModeCursorKeys TerminalMode = 1 << iota // ModeColumnMode enables 132-column mode. ModeColumnMode // ModeInsert enables insert mode (characters shift right instead of overwrite). ModeInsert // ModeOrigin enables origin mode (cursor positioning relative to scroll region). ModeOrigin // ModeLineWrap enables automatic line wrapping at column boundaries. ModeLineWrap // ModeBlinkingCursor enables blinking cursor. ModeBlinkingCursor // ModeLineFeedNewLine makes line feed also move to column 0. ModeLineFeedNewLine // ModeShowCursor makes the cursor visible. ModeShowCursor // ModeReportMouseClicks enables mouse click reporting. ModeReportMouseClicks // ModeReportCellMouseMotion enables mouse motion reporting (cell-based). ModeReportCellMouseMotion // ModeReportAllMouseMotion enables reporting of all mouse motion events. ModeReportAllMouseMotion // ModeReportFocusInOut enables focus in/out event reporting. ModeReportFocusInOut // ModeUTF8Mouse enables UTF-8 mouse encoding. ModeUTF8Mouse // ModeSGRMouse enables SGR mouse encoding. ModeSGRMouse // ModeAlternateScroll enables alternate scroll mode. ModeAlternateScroll // ModeUrgencyHints enables urgency hints. ModeUrgencyHints // ModeSwapScreenAndSetRestoreCursor swaps to alternate screen and saves cursor. // When unset, restores primary screen and cursor position. ModeSwapScreenAndSetRestoreCursor // ModeBracketedPaste enables bracketed paste mode. ModeBracketedPaste // ModeKeypadApplication enables application keypad mode. ModeKeypadApplication )
type TitleProvider ¶
type TitleProvider interface {
// SetTitle is called when the title changes.
SetTitle(title string)
// PushTitle saves the current title to the stack.
PushTitle()
// PopTitle restores the title from the stack.
PopTitle()
}
TitleProvider handles window title changes (OSC 0, 1, 2).

