headlessterm

package module
v1.0.9 Latest Latest
Warning

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

Go to latest
Published: Jan 2, 2026 License: MIT Imports: 15 Imported by: 0

README

go-headless-term

Go Report Card License MIT Go Doc

logo

A VT220-compatible terminal emulator for Go that processes ANSI escape sequences and maintains terminal state without a display. You feed it bytes, it updates internal buffers, cursor position, colors, and modes. Useful for parsing terminal output, testing ANSI applications, or building terminal UIs.

When should I use this?

  • Parsing terminal output: Process ANSI-colored output from commands and extract text/formatting
  • ANSI testing: Verify that applications produce correct escape sequences
  • Terminal UI backends: Build headless terminal interfaces that can be rendered later
  • Log analysis: Parse ANSI-formatted logs while preserving structure and colors
  • Output capture: Record complete terminal state including scrollback for replay

When should I NOT use this?

  • Interactive terminals: This is not a PTY. It doesn't handle input, process management, or shell interaction
  • Real terminal emulators: No rendering, no window management, no user interaction
  • Simple text extraction: If you just need plain text, use strings or regex instead
  • Live terminal sessions: This processes static byte streams, not bidirectional communication
  • Full VT100+ compatibility: Focuses on VT220 subset; some edge cases may differ

Mental model

The library processes a stream of bytes incrementally:

Raw bytes → ANSI decoder → Handler methods → State updates

State model:

  • Two buffers: Primary (with scrollback) and alternate (no scrollback, for full-screen apps)
  • Active buffer: Switches automatically when entering/exiting alternate screen mode
  • Cell grid: 2D array where each cell stores character, colors, and formatting flags
  • Cursor: Tracks position, visibility, and style
  • Cell template: Default attributes (colors, bold, etc.) applied to new characters
  • Modes: Bitmask of terminal behaviors (line wrap, insert mode, origin mode, etc.)

Flow:

  1. You call Write() or WriteString() with raw bytes
  2. Internal decoder parses ANSI sequences and calls handler methods (e.g., Input(), Goto(), SetTerminalCharAttribute())
  3. Handlers update buffers, cursor, colors, or modes
  4. You read state via Cell(), CursorPos(), String()

Thread safety: All public methods are safe for concurrent use (internal locking).

Providers: Optional callbacks for external events (bell, title changes, clipboard, etc.). Default to no-ops.

Installation

go get github.com/danielgatis/go-headless-term

Minimal example

package main

import (
	"fmt"
	headlessterm "github.com/danielgatis/go-headless-term"
)

func main() {
	term := headlessterm.New()

	// Write ANSI sequences
	term.WriteString("\x1b[31mHello ")  // Red text
	term.WriteString("\x1b[32mWorld")  // Green text
	term.WriteString("\x1b[0m!\r\n")   // Reset and newline

	// Read terminal content
	fmt.Println(term.String())

	// Get cursor position
	row, col := term.CursorPos()
	fmt.Printf("Cursor: row=%d, col=%d\n", row, col)
}

Examples

The repository includes working examples in the examples/ directory:

Basic usage (examples/basic/)

Demonstrates basic terminal operations: writing ANSI sequences, reading content, and checking cursor position.

cd examples/basic
go run main.go

Shows:

  • Setting terminal title (OSC 0)
  • Text colors and formatting (SGR codes)
  • Screen clearing
  • Reading terminal state

Core concepts / API overview

Terminal

The main type. Created with New() and configured via options:

term := headlessterm.New(
    headlessterm.WithSize(24, 80),
    headlessterm.WithAutoResize(),
    headlessterm.WithScrollback(storage),
)

Key methods:

  • Write([]byte) / WriteString(string): Process raw bytes (implements io.Writer)
  • Cell(row, col): Get cell at position (returns *Cell or nil)
  • CursorPos(): Get cursor position (0-based)
  • String(): Get visible screen content as text
  • Resize(rows, cols): Change dimensions
  • IsAlternateScreen(): Check if alternate buffer is active
Buffer

Stores the 2D cell grid. Two buffers exist:

  • Primary: Has scrollback (lines scrolled off top are saved)
  • Alternate: No scrollback (cleared when switching back)

Access via Terminal.Cell() (reads from active buffer).

Cell

Represents one grid position:

  • Char: The rune (character)
  • Fg / Bg: Foreground/background colors (color.Color)
  • Flags: Bitmask (bold, underline, reverse, etc.)
  • Hyperlink: Optional OSC 8 hyperlink
  • IsWide(): True if character occupies 2 columns (CJK, emoji)
  • IsWideSpacer(): True if this is the second cell of a wide character
Options

Configure terminal at creation:

  • WithSize(rows, cols): Set dimensions (default: 24x80)
  • WithAutoResize(): Buffer grows instead of scrolling/wrapping
  • WithScrollback(provider): Custom scrollback storage
  • WithResponse(writer): Writer for terminal responses (DSR, etc.)
  • WithBell(provider): Handler for bell events
  • WithTitle(provider): Handler for title changes
  • WithClipboard(provider): Handler for OSC 52 clipboard
  • WithNotification(provider): Handler for OSC 99 desktop notifications (Kitty protocol)
  • WithMiddleware(mw): Intercept handler calls
Providers

Interfaces for external events (all optional, default to no-ops):

  • BellProvider: Called on BEL (0x07)
  • TitleProvider: Called on OSC 0/1/2 (title changes)
  • ClipboardProvider: Called on OSC 52 (clipboard read/write)
  • ScrollbackProvider: Stores lines scrolled off top
  • RecordingProvider: Captures raw input bytes
  • NotificationProvider: Called on OSC 99 (desktop notifications, Kitty protocol)
Dirty tracking

Cells track modification state:

  • HasDirty(): True if any cell modified since last ClearDirty()
  • DirtyCells(): List of modified positions
  • ClearDirty(): Reset tracking

Useful for incremental rendering (only redraw changed cells).

Desktop Notifications (OSC 99)

The terminal supports the Kitty desktop notification protocol (OSC 99). Implement NotificationProvider to handle notifications:

type MyNotificationHandler struct{}

func (h *MyNotificationHandler) Notify(payload *headlessterm.NotificationPayload) string {
    // Handle the notification
    fmt.Printf("Notification: %s\n", string(payload.Data))

    // For query requests, return capabilities
    if payload.PayloadType == "?" {
        return "\x1b]99;i=test;p=title:body\x1b\\"
    }
    return ""
}

term := headlessterm.New(
    headlessterm.WithNotification(&MyNotificationHandler{}),
)

The NotificationPayload contains:

  • ID: Unique identifier for chunking/tracking
  • PayloadType: Type of data ("title", "body", "icon", "?", etc.)
  • Data: Payload content (decoded if base64)
  • Urgency: 0 (low), 1 (normal), 2 (critical)
  • Sound: Notification sound ("system", "silent", etc.)
  • Actions: Click behavior ("focus", "report")
  • And more fields for icons, timeouts, app name, etc.

See Kitty Desktop Notifications for protocol details.

Buy me a coffee

Liked some of my work? Buy me a coffee (or more likely a beer)

Buy Me A Coffee

License

Copyright (c) 2020-present Daniel Gatis

Licensed under MIT License

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:

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()

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

View Source
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).

View Source
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
)
View Source
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

View Source
var DefaultBackground = color.RGBA{0, 0, 0, 255}

DefaultBackground is the default background color (black).

View Source
var DefaultCursorColor = color.RGBA{229, 229, 229, 255}

DefaultCursorColor is the default cursor rendering color (light gray).

View Source
var DefaultForeground = color.RGBA{229, 229, 229, 255}

DefaultForeground is the default text color (light gray).

View Source
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

func FormatKittyResponse(imageID uint32, message string, isError bool) string

FormatKittyResponse formats a Kitty graphics response.

func ResolveDefaultColor added in v1.0.6

func ResolveDefaultColor(c color.Color, fg bool) color.RGBA

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

func StringWidth(s string) int

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 NewBuffer

func NewBuffer(rows, cols int) *Buffer

NewBuffer creates a buffer with the given dimensions and no scrollback.

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

func (b *Buffer) Cell(row, col int) *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

func (b *Buffer) ClearRow(row int)

ClearRow resets all cells in the row to default state and marks them dirty.

func (*Buffer) ClearRowRange

func (b *Buffer) ClearRowRange(row, startCol, endCol int)

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

func (b *Buffer) ClearTabStop(col int)

ClearTabStop disables the tab stop at the specified column.

func (*Buffer) Cols

func (b *Buffer) Cols() int

Cols returns the buffer width in character columns.

func (*Buffer) DeleteChars

func (b *Buffer) DeleteChars(row, col, n int)

DeleteChars removes n characters at (row, col), shifting remaining characters left.

func (*Buffer) DeleteLines

func (b *Buffer) DeleteLines(row, n, bottom int)

DeleteLines removes n lines at row, shifting remaining lines up. Equivalent to ScrollUp(row, bottom, n).

func (*Buffer) DirtyCells

func (b *Buffer) DirtyCells() []Position

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

func (b *Buffer) GrowCols(row, minCols int)

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

func (b *Buffer) GrowRows(n int)

GrowRows appends n new rows to the bottom of the buffer. New cells are initialized to default state and marked dirty.

func (*Buffer) HasDirty

func (b *Buffer) HasDirty() bool

HasDirty returns true if any cell has been modified since the last ClearAllDirty call.

func (*Buffer) InsertBlanks

func (b *Buffer) InsertBlanks(row, col, n int)

InsertBlanks inserts n blank cells at (row, col), shifting existing characters right.

func (*Buffer) InsertLines

func (b *Buffer) InsertLines(row, n, bottom int)

InsertLines inserts n blank lines at row, shifting existing lines down. Equivalent to ScrollDown(row, bottom, n).

func (*Buffer) IsWrapped

func (b *Buffer) IsWrapped(row int) bool

IsWrapped returns true if the line was wrapped due to column overflow.

func (*Buffer) LineContent

func (b *Buffer) LineContent(row int) string

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

func (b *Buffer) MarkDirty(row, col int)

MarkDirty marks the cell at (row, col) as modified. Does nothing if coordinates are out of bounds.

func (*Buffer) MaxScrollback

func (b *Buffer) MaxScrollback() int

MaxScrollback returns the current maximum scrollback capacity.

func (*Buffer) NextTabStop

func (b *Buffer) NextTabStop(col int) int

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

func (b *Buffer) PrevTabStop(col int) int

PrevTabStop returns the column index of the previous enabled tab stop before col. Returns 0 if no tab stop is found.

func (*Buffer) Resize

func (b *Buffer) Resize(rows, cols int)

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) Rows

func (b *Buffer) Rows() int

Rows returns the buffer height in character rows.

func (*Buffer) ScrollDown

func (b *Buffer) ScrollDown(top, bottom, n int)

ScrollDown shifts lines down by n positions within [top, bottom). Top lines are cleared and marked dirty.

func (*Buffer) ScrollUp

func (b *Buffer) ScrollUp(top, bottom, n int)

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

func (b *Buffer) ScrollbackLen() int

ScrollbackLen returns the number of lines stored in scrollback.

func (*Buffer) ScrollbackLine

func (b *Buffer) ScrollbackLine(index int) []Cell

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

func (b *Buffer) SetCell(row, col int, cell Cell)

SetCell replaces the cell at (row, col) and marks it dirty. Does nothing if coordinates are out of bounds.

func (*Buffer) SetMaxScrollback

func (b *Buffer) SetMaxScrollback(max int)

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

func (b *Buffer) SetTabStop(col int)

SetTabStop enables a tab stop at the specified column.

func (*Buffer) SetWrapped

func (b *Buffer) SetWrapped(row int, wrapped bool)

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) ClearDirty

func (c *Cell) ClearDirty()

ClearDirty resets the dirty tracking flag.

func (*Cell) ClearFlag

func (c *Cell) ClearFlag(flag CellFlags)

ClearFlag disables the specified flag without affecting others.

func (*Cell) Copy

func (c *Cell) Copy() Cell

Copy returns a deep copy of the cell, including the hyperlink and image pointers.

func (*Cell) HasFlag

func (c *Cell) HasFlag(flag CellFlags) bool

HasFlag returns true if the specified flag is set.

func (*Cell) HasImage added in v1.0.1

func (c *Cell) HasImage() bool

HasImage returns true if this cell has an image reference.

func (*Cell) IsDirty

func (c *Cell) IsDirty() bool

IsDirty returns true if the cell was modified since the last ClearDirty call.

func (*Cell) IsWide

func (c *Cell) IsWide() bool

IsWide returns true if this cell contains a wide character (CJK, emoji, etc.) that occupies 2 columns.

func (*Cell) IsWideSpacer

func (c *Cell) IsWideSpacer() bool

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.

func (*Cell) Reset

func (c *Cell) Reset()

Reset clears all attributes and sets the cell to default state (space character, default colors).

func (*Cell) SetFlag

func (c *Cell) SetFlag(flag CellFlags)

SetFlag enables the specified flag without affecting others.

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 Charset

type Charset int

Charset selects the character encoding variant.

const (
	CharsetASCII Charset = iota
	CharsetLineDrawing
)

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).

func NewCursor

func NewCursor() *Cursor

NewCursor creates a cursor at (0, 0) with blinking block style, visible.

type CursorStyle

type CursorStyle int

CursorStyle determines how the cursor is rendered.

const (
	CursorStyleBlinkingBlock CursorStyle = iota
	CursorStyleSteadyBlock
	CursorStyleBlinkingUnderline
	CursorStyleSteadyUnderline
	CursorStyleBlinkingBar
	CursorStyleSteadyBar
)
type Hyperlink struct {
	ID  string
	URI string
}

Hyperlink associates a cell with a clickable link (OSC 8).

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
	KittyTransmitSharedMem KittyTransmission = 's' // Shared memory
)

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 NoopAPC

type NoopAPC struct{}

NoopAPC ignores all APC sequences.

func (NoopAPC) Receive

func (NoopAPC) Receive(data []byte)

type NoopBell

type NoopBell struct{}

NoopBell ignores all bell events.

func (NoopBell) Ring

func (NoopBell) Ring()

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 NoopPM

type NoopPM struct{}

NoopPM ignores all PM sequences.

func (NoopPM) Receive

func (NoopPM) Receive(data []byte)

type NoopPTYWriter added in v1.0.9

type NoopPTYWriter struct{}

NoopPTYWriter discards all response data (useful when responses are not needed).

func (NoopPTYWriter) Write added in v1.0.9

func (NoopPTYWriter) Write(p []byte) (n int, err error)

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 NoopSOS

type NoopSOS struct{}

NoopSOS ignores all SOS sequences.

func (NoopSOS) Receive

func (NoopSOS) Receive(data []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

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 NoopTitle

type NoopTitle struct{}

NoopTitle ignores all title operations.

func (NoopTitle) PopTitle

func (NoopTitle) PopTitle()

func (NoopTitle) PushTitle

func (NoopTitle) PushTitle()

func (NoopTitle) SetTitle

func (NoopTitle) SetTitle(title string)

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.

See: https://sw.kovidgoyal.net/kitty/desktop-notifications/

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

func WithKitty(enabled bool) Option

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.

See: https://sw.kovidgoyal.net/kitty/desktop-notifications/

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

func WithPTYWriter(p PTYWriter) Option

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

func WithSixel(enabled bool) Option

WithSixel enables or disables Sixel graphics protocol support. When disabled, Sixel sequences are ignored. Default is true (enabled).

func WithSize

func WithSize(rows, cols int) Option

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

type PTYWriter = io.Writer

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

type Position struct {
	Row int
	Col int
}

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.

func (Position) Before

func (p Position) Before(other Position) bool

Before returns true if this position comes before other in reading order (top-to-bottom, left-to-right).

func (Position) Equal

func (p Position) Equal(other Position) bool

Equal returns true if both row and column match.

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

type Selection struct {
	Start  Position
	End    Position
	Active bool
}

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 struct {
	ID  string `json:"id,omitempty"`
	URI string `json:"uri"`
}

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

type SnapshotSize struct {
	Rows int `json:"rows"`
	Cols int `json:"cols"`
}

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

func New(opts ...Option) *Terminal

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

func (t *Terminal) AbsoluteRowToViewport(absoluteRow int) int

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

func (t *Terminal) ApplicationCommandReceived(data []byte)

ApplicationCommandReceived processes an APC sequence and delegates to the configured provider.

func (*Terminal) AutoResize

func (t *Terminal) AutoResize() bool

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) Bell

func (t *Terminal) Bell()

Bell triggers the bell provider if configured.

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

func (t *Terminal) Cell(row, col int) *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

func (t *Terminal) ClearScreen(mode ansicode.ClearMode)

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

func (t *Terminal) ClipboardLoad(clipboard byte, terminator string)

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

func (t *Terminal) ClipboardStore(clipboard byte, data []byte)

ClipboardStore writes data to the clipboard provider via OSC 52.

func (*Terminal) Cols

func (t *Terminal) Cols() int

Cols returns the terminal width in character columns.

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) CursorPos

func (t *Terminal) CursorPos() (row, col int)

CursorPos returns the current cursor position (0-based).

func (*Terminal) CursorStyle

func (t *Terminal) CursorStyle() CursorStyle

CursorStyle returns the current cursor rendering style.

func (*Terminal) CursorVisible

func (t *Terminal) CursorVisible() bool

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

func (t *Terminal) DeleteChars(n int)

DeleteChars removes n characters at the cursor, shifting remaining characters left.

func (*Terminal) DeleteLines

func (t *Terminal) DeleteLines(n int)

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

func (t *Terminal) DeviceStatus(n int)

DeviceStatus sends a device status report (DSR) response: ready (n=5) or cursor position (n=6).

func (*Terminal) DirtyCells

func (t *Terminal) DirtyCells() []Position

DirtyCells returns positions of all cells modified since the last ClearDirty call.

func (*Terminal) EraseChars

func (t *Terminal) EraseChars(n int)

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

func (t *Terminal) GetLastCommandOutput() string

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

func (t *Terminal) GetSelectedText() string

GetSelectedText extracts and returns the text content within the active selection. Empty cells are converted to spaces, and newlines separate rows.

func (*Terminal) GetSelection

func (t *Terminal) GetSelection() Selection

GetSelection returns the current selection state.

func (*Terminal) GetUserVar added in v1.0.8

func (t *Terminal) GetUserVar(name string) string

GetUserVar returns the value of a user variable, or empty string if not set.

func (*Terminal) GetUserVars added in v1.0.8

func (t *Terminal) GetUserVars() map[string]string

GetUserVars returns a copy of all user variables.

func (*Terminal) Goto

func (t *Terminal) Goto(row, col int)

Goto moves the cursor to (row, col), adjusting for origin mode if enabled.

func (*Terminal) GotoCol

func (t *Terminal) GotoCol(col int)

GotoCol moves the cursor to the specified column, keeping the current row.

func (*Terminal) GotoLine

func (t *Terminal) GotoLine(row int)

GotoLine moves the cursor to the specified row, adjusting for origin mode if enabled.

func (*Terminal) HasDirty

func (t *Terminal) HasDirty() bool

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

func (t *Terminal) HasSelection() bool

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

func (t *Terminal) IdentifyTerminal(b byte)

IdentifyTerminal sends a terminal identification response (default: VT220).

func (*Terminal) Image added in v1.0.1

func (t *Terminal) Image(id uint32) *ImageData

Image returns the image data for the given ID, or nil if not found.

func (*Terminal) ImageCount added in v1.0.1

func (t *Terminal) ImageCount() int

ImageCount returns the number of stored images.

func (*Terminal) ImagePlacementCount added in v1.0.1

func (t *Terminal) ImagePlacementCount() int

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

func (t *Terminal) ImageUsedMemory() int64

ImageUsedMemory returns the current image memory usage in bytes.

func (*Terminal) Input

func (t *Terminal) Input(r rune)

Input writes a character to the buffer at the cursor position. Handles wide characters, line wrapping, insert mode, and charset translation.

func (*Terminal) InsertBlank

func (t *Terminal) InsertBlank(n int)

InsertBlank inserts n blank cells at the cursor, shifting existing characters right.

func (*Terminal) InsertBlankLines

func (t *Terminal) InsertBlankLines(n int)

InsertBlankLines inserts n blank lines at the cursor within the scroll region, shifting remaining lines down.

func (*Terminal) IsAlternateScreen

func (t *Terminal) IsAlternateScreen() bool

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

func (t *Terminal) IsSelected(row, col int) bool

IsSelected returns true if the cell at (row, col) is within the active selection.

func (*Terminal) IsWrapped

func (t *Terminal) IsWrapped(row int) bool

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

func (t *Terminal) KittyEnabled() bool

KittyEnabled returns true if Kitty graphics protocol is enabled.

func (*Terminal) LineContent

func (t *Terminal) LineContent(row int) string

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

func (t *Terminal) MaxScrollback() int

MaxScrollback returns the current maximum scrollback capacity.

func (*Terminal) Middleware

func (t *Terminal) Middleware() *Middleware

Middleware returns the current middleware.

func (*Terminal) MoveBackward

func (t *Terminal) MoveBackward(n int)

MoveBackward moves the cursor left n columns, stopping at column 0.

func (*Terminal) MoveBackwardTabs

func (t *Terminal) MoveBackwardTabs(n int)

MoveBackwardTabs moves the cursor left to the previous n tab stops.

func (*Terminal) MoveDown

func (t *Terminal) MoveDown(n int)

MoveDown moves the cursor down n rows, stopping at the last row.

func (*Terminal) MoveDownCr

func (t *Terminal) MoveDownCr(n int)

MoveDownCr moves the cursor down n rows and to column 0.

func (*Terminal) MoveForward

func (t *Terminal) MoveForward(n int)

MoveForward moves the cursor right n columns, stopping at the last column.

func (*Terminal) MoveForwardTabs

func (t *Terminal) MoveForwardTabs(n int)

MoveForwardTabs moves the cursor right to the next n tab stops.

func (*Terminal) MoveUp

func (t *Terminal) MoveUp(n int)

MoveUp moves the cursor up n rows, stopping at row 0.

func (*Terminal) MoveUpCr

func (t *Terminal) MoveUpCr(n int)

MoveUpCr moves the cursor up n rows and to column 0.

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) PTYWriter added in v1.0.9

func (t *Terminal) PTYWriter() PTYWriter

PTYWriter returns the current PTY writer.

func (*Terminal) PopKeyboardMode

func (t *Terminal) PopKeyboardMode(n int)

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

func (t *Terminal) PrivacyMessageReceived(data []byte)

PrivacyMessageReceived processes a PM sequence and delegates to the configured provider.

func (*Terminal) PromptMarkCount added in v1.0.1

func (t *Terminal) PromptMarkCount() int

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

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

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

func (t *Terminal) ResetColor(i int)

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

func (t *Terminal) Resize(rows, cols int)

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) Rows

func (t *Terminal) Rows() int

Rows returns the terminal height in character rows.

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

func (t *Terminal) ScrollDown(n int)

ScrollDown shifts lines down within the scroll region, clearing top lines.

func (*Terminal) ScrollRegion

func (t *Terminal) ScrollRegion() (top, bottom int)

ScrollRegion returns the current scrolling boundaries (0-based, exclusive bottom). When origin mode is enabled, cursor positioning is relative to scrollTop.

func (*Terminal) ScrollUp

func (t *Terminal) ScrollUp(n int)

ScrollUp shifts lines up within the scroll region, pushing top lines to scrollback if enabled.

func (*Terminal) ScrollbackLen

func (t *Terminal) ScrollbackLen() int

ScrollbackLen returns the number of lines stored in scrollback (primary buffer only).

func (*Terminal) ScrollbackLine

func (t *Terminal) ScrollbackLine(index int) []Cell

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

func (t *Terminal) Search(pattern string) []Position

Search finds all occurrences of pattern in the visible screen content. Returns positions of the first character of each match.

func (*Terminal) SearchScrollback

func (t *Terminal) SearchScrollback(pattern string) []Position

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

func (t *Terminal) SetActiveCharset(n int)

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

func (t *Terminal) SetColor(index int, c color.Color)

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

func (t *Terminal) SetDynamicColor(prefix string, index int, terminator string)

SetDynamicColor responds to a dynamic color query (OSC 10/11/12) with the current color value.

func (t *Terminal) SetHyperlink(hyperlink *ansicode.Hyperlink)

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

func (t *Terminal) SetImageMaxMemory(bytes int64)

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

func (t *Terminal) SetMaxScrollback(max int)

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

func (t *Terminal) SetPTYWriter(p PTYWriter)

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

func (t *Terminal) SetScrollingRegion(top, bottom int)

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

func (t *Terminal) SetSelection(start, end Position)

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) SetTitle

func (t *Terminal) SetTitle(title string)

SetTitle updates the window title and notifies the title provider.

func (*Terminal) SetTitleProvider

func (t *Terminal) SetTitleProvider(p TitleProvider)

SetTitleProvider sets the title provider at runtime.

func (*Terminal) SetUserVar added in v1.0.8

func (t *Terminal) SetUserVar(name, value string)

SetUserVar stores a user variable (OSC 1337 SetUserVar).

func (*Terminal) SetWorkingDirectory added in v1.0.1

func (t *Terminal) SetWorkingDirectory(uri string)

SetWorkingDirectory stores the current working directory (OSC 7).

func (*Terminal) SetWrapped

func (t *Terminal) SetWrapped(row int, wrapped bool)

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

func (t *Terminal) SixelEnabled() bool

SixelEnabled returns true if Sixel graphics protocol is enabled.

func (*Terminal) SixelReceived added in v1.0.1

func (t *Terminal) SixelReceived(params [][]uint16, data []byte)

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

func (t *Terminal) StartOfStringReceived(data []byte)

StartOfStringReceived processes a SOS sequence and delegates to the configured provider.

func (*Terminal) String

func (t *Terminal) String() 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) Tab

func (t *Terminal) Tab(n int)

Tab moves the cursor right to the next n tab stops.

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) Title

func (t *Terminal) Title() string

Title returns the current window title string.

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

func (t *Terminal) ViewportRowToAbsolute(viewportRow int) int

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

func (t *Terminal) WorkingDirectory() string

WorkingDirectory returns the current working directory URI (OSC 7).

func (*Terminal) WorkingDirectoryPath added in v1.0.1

func (t *Terminal) WorkingDirectoryPath() string

WorkingDirectoryPath extracts the path from the working directory URI.

func (*Terminal) Write

func (t *Terminal) Write(data []byte) (int, error)

Write processes raw bytes, parsing ANSI escape sequences and updating the terminal state. Implements io.Writer.

func (*Terminal) WriteString

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

WriteString is a convenience method that converts the string to bytes and calls Write.

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).

Directories

Path Synopsis
examples
basic command

Jump to

Keyboard shortcuts

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