Help us shape the future of Go! Take the 2026 Go Developer Survey

xterm

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2026 License: MIT Imports: 8 Imported by: 0

README

xterm-go

A pure-Go headless terminal emulator ported from xterm.js.

It processes VT/ANSI escape sequences and maintains terminal buffer state without requiring a browser, DOM, or any rendering. This enables server-side terminal state tracking, screen content extraction, and headless terminal testing.

The implementation follows the VT500 specification and is a direct port of the headless subset of xterm.js (MIT license).

This is a maintained fork of gitpod-io/xterm-go used by ttt. It adds a fix for a reflow panic when narrowing a full buffer and removes allocations from scrolling, cell loading, and SGR handling. Fixes are reported upstream as well.

Install

go get github.com/eugenioenko/xterm-go

Usage

package main

import (
	"fmt"

	xterm "github.com/eugenioenko/xterm-go"
)

func main() {
	term := xterm.New(xterm.WithCols(80), xterm.WithRows(24))
	defer term.Dispose()

	term.WriteString("Hello, world!\r\n")
	term.WriteString("\x1b[1;31mRed bold text\x1b[0m\r\n")

	fmt.Println(term.String())
	fmt.Printf("Cursor: (%d, %d)\n", term.CursorX(), term.CursorY())
}

Features

  • Full VT500 escape sequence parsing (CSI, OSC, DCS, APC)
  • Normal and alternate screen buffers with scrollback
  • Text attributes: bold, italic, underline, strikethrough, blink, inverse, dim, overline
  • 16-color, 256-color, and 24-bit RGB color support
  • Terminal resize with reflow
  • Serialize addon for terminal state snapshots
  • Conformance tests against xterm.js golden data

API

Terminal
// Create a terminal with options.
term := xterm.New(
    xterm.WithCols(80),
    xterm.WithRows(24),
    xterm.WithScrollback(1000),
)

// Write data (implements io.Writer).
term.Write([]byte("\x1b[2J"))
term.WriteString("text")

// Read state.
term.Cols()              // terminal width
term.Rows()              // terminal height
term.CursorX()           // cursor column
term.CursorY()           // cursor row
term.GetLine(y)          // text content of line y
term.String()            // full screen content
term.Buffer()            // active buffer
term.NormalBuffer()      // normal screen buffer
term.AltBuffer()         // alternate screen buffer
term.IsAltBufferActive() // whether alt buffer is active

// Resize.
term.Resize(cols, rows)

// Events.
term.OnData(func(s string) { })       // terminal response data (DA, DSR)
term.OnBell(func() { })               // BEL character
term.OnTitleChange(func(s string) { }) // OSC title change
term.OnLineFeed(func() { })            // line feed

// Cleanup.
term.Dispose()
SerializeAddon

Produces compact escape-sequence snapshots of terminal state for reconnection:

addon := xterm.NewSerializeAddon(term)
snapshot := addon.Serialize(nil) // []byte of escape sequences

Conformance

Cross-implementation tests verify the Go port produces identical behavior to xterm.js. See conformance/README.md.

go test -run TestConformance -v

Benchmarks

Pull requests get a benchstat comparison against the base commit, posted as a PR comment. To run the same comparison locally against another checkout (requires golang.org/x/perf/cmd/benchstat):

BASE_DIR=../xterm-go-base HEAD_DIR=. REPORT_FILE=benchstat.md scripts/bench-compare.sh

COUNT (default 6) and BENCH_TIME (default 500ms) control the runs.

License

MIT — see LICENSE.

The original xterm.js is also MIT licensed: https://github.com/xtermjs/xterm.js/blob/master/LICENSE

Documentation

Overview

Package xterm is a pure-Go headless terminal emulator ported from xterm.js.

It processes VT/ANSI escape sequences and maintains terminal buffer state without requiring a browser, DOM, or any rendering. This enables server-side terminal state tracking, screen content extraction, and headless terminal testing.

The implementation follows the VT500 specification and is a direct port of the headless subset of https://github.com/xtermjs/xterm.js (MIT license).

Index

Constants

View Source
const (
	// MinimumCols is the minimum number of columns. Less than 2 can break wide chars.
	MinimumCols = 2
	// MinimumRows is the minimum number of rows.
	MinimumRows = 1
)
View Source
const (
	ContentCodepointMask  uint32 = 0x1FFFFF
	ContentIsCombinedMask uint32 = 0x200000 // 1 << 21
	ContentHasContentMask uint32 = 0x3FFFFF // codepoint | isCombined
	ContentWidthMask      uint32 = 0xC00000 // 3 << 22
	ContentWidthShift     uint32 = 22
)

Content bitmasks for the cell content uint32.

bits 0-20:  codepoint (max 0x10FFFF)
bit  21:    IS_COMBINED flag
bits 22-23: wcwidth (0-2)
View Source
const (
	AttrBlueMask   uint32 = 0xFF
	AttrBlueShift  uint32 = 0
	AttrPColorMask uint32 = 0xFF
	AttrGreenMask  uint32 = 0xFF00
	AttrGreenShift uint32 = 8
	AttrRedMask    uint32 = 0xFF0000
	AttrRedShift   uint32 = 16
	AttrCMMask     uint32 = 0x3000000
	AttrCMDefault  uint32 = 0
	AttrCMP16      uint32 = 0x1000000
	AttrCMP256     uint32 = 0x2000000
	AttrCMRGB      uint32 = 0x3000000
	AttrRGBMask    uint32 = 0xFFFFFF
)

Attributes bitmasks for fg/bg uint32 color fields.

bits 0-7:   blue (RGB) or palette index
bits 8-15:  green (RGB)
bits 16-23: red (RGB)
bits 24-25: color mode
View Source
const (
	FgFlagInverse       uint32 = 0x4000000
	FgFlagBold          uint32 = 0x8000000
	FgFlagUnderline     uint32 = 0x10000000
	FgFlagBlink         uint32 = 0x20000000
	FgFlagInvisible     uint32 = 0x40000000
	FgFlagStrikethrough uint32 = 0x80000000
)

FgFlags are attribute flags stored in the upper bits of the fg uint32.

bits 26-31
View Source
const (
	BgFlagItalic      uint32 = 0x4000000
	BgFlagDim         uint32 = 0x8000000
	BgFlagHasExtended uint32 = 0x10000000
	BgFlagProtected   uint32 = 0x20000000
	BgFlagOverline    uint32 = 0x40000000
)

BgFlags are attribute flags stored in the upper bits of the bg uint32.

bits 26-30
View Source
const (
	ExtFlagUnderlineStyle uint32 = 0x1C000000 // bits 26-28
	ExtFlagVariantOffset  uint32 = 0xE0000000 // bits 29-31
)

ExtFlags are flags in the extended attributes uint32.

View Source
const (
	NullCellChar  = ""
	NullCellWidth = 1
	NullCellCode  = 0
)

Null cell constants.

View Source
const (
	WhitespaceCellChar  = " "
	WhitespaceCellWidth = 1
	WhitespaceCellCode  = 32
)

Whitespace cell constants.

View Source
const (
	DefaultColor uint32 = 0
	DefaultAttr  uint32 = (0 << 18) | (0 << 9) | (256 << 0)
	DefaultExt   uint32 = 0
)

Default attribute values.

View Source
const MaxBufferSize = min(4294967295, math.MaxInt)

MaxBufferSize is the maximum number of lines a buffer can hold: 2^32 - 1, capped at math.MaxInt so the package builds on 32-bit platforms.

View Source
const ParserPayloadLimit = 10000000

ParserPayloadLimit is the maximum payload size for OSC and DCS sequences.

Variables

View Source
var CHARSETS = map[byte]Charset{
	'B': nil,
}

CHARSETS maps charset designator characters to their Charset tables. nil means the default (US ASCII) charset.

View Source
var CharsetBritish = Charset{
	'#': '\u00a3',
}

CharsetBritish is the British character set (ESC (A).

View Source
var CharsetDECSpecialGraphics = Charset{
	'`': '\u25c6',
	'a': '\u2592',
	'b': '\u2409',
	'c': '\u240c',
	'd': '\u240d',
	'e': '\u240a',
	'f': '\u00b0',
	'g': '\u00b1',
	'h': '\u2424',
	'i': '\u240b',
	'j': '\u2518',
	'k': '\u2510',
	'l': '\u250c',
	'm': '\u2514',
	'n': '\u253c',
	'o': '\u23ba',
	'p': '\u23bb',
	'q': '\u2500',
	'r': '\u23bc',
	's': '\u23bd',
	't': '\u251c',
	'u': '\u2524',
	'v': '\u2534',
	'w': '\u252c',
	'x': '\u2502',
	'y': '\u2264',
	'z': '\u2265',
	'{': '\u03c0',
	'|': '\u2260',
	'}': '\u00a3',
	'~': '\u00b7',
}

CharsetDECSpecialGraphics is the DEC Special Character and Line Drawing Set. Reference: http://vt100.net/docs/vt102-ug/table5-13.html

View Source
var CharsetDutch = Charset{
	'#':  '\u00a3',
	'@':  '\u00be',
	'[':  'i',
	'\\': '\u00bd',
	']':  '|',
	'{':  '\u00a8',
	'|':  'f',
	'}':  '\u00bc',
	'~':  '\u00b4',
}

CharsetDutch is the Dutch character set (ESC (4).

View Source
var CharsetFinnish = Charset{
	'[':  '\u00c4',
	'\\': '\u00d6',
	']':  '\u00c5',
	'^':  '\u00dc',
	'`':  '\u00e9',
	'{':  '\u00e4',
	'|':  '\u00f6',
	'}':  '\u00e5',
	'~':  '\u00fc',
}

CharsetFinnish is the Finnish character set (ESC (C or ESC (5).

View Source
var CharsetFrench = Charset{
	'#':  '\u00a3',
	'@':  '\u00e0',
	'[':  '\u00b0',
	'\\': '\u00e7',
	']':  '\u00a7',
	'{':  '\u00e9',
	'|':  '\u00f9',
	'}':  '\u00e8',
	'~':  '\u00a8',
}

CharsetFrench is the French character set (ESC (R).

View Source
var CharsetFrenchCanadian = Charset{
	'@':  '\u00e0',
	'[':  '\u00e2',
	'\\': '\u00e7',
	']':  '\u00ea',
	'^':  '\u00ee',
	'`':  '\u00f4',
	'{':  '\u00e9',
	'|':  '\u00f9',
	'}':  '\u00e8',
	'~':  '\u00fb',
}

CharsetFrenchCanadian is the French Canadian character set (ESC (Q).

View Source
var CharsetGerman = Charset{
	'@':  '\u00a7',
	'[':  '\u00c4',
	'\\': '\u00d6',
	']':  '\u00dc',
	'{':  '\u00e4',
	'|':  '\u00f6',
	'}':  '\u00fc',
	'~':  '\u00df',
}

CharsetGerman is the German character set (ESC (K).

View Source
var CharsetItalian = Charset{
	'#':  '\u00a3',
	'@':  '\u00a7',
	'[':  '\u00b0',
	'\\': '\u00e7',
	']':  '\u00e9',
	'`':  '\u00f9',
	'{':  '\u00e0',
	'|':  '\u00f2',
	'}':  '\u00e8',
	'~':  '\u00ec',
}

CharsetItalian is the Italian character set (ESC (Y).

View Source
var CharsetNorwegianDanish = Charset{
	'@':  '\u00c4',
	'[':  '\u00c6',
	'\\': '\u00d8',
	']':  '\u00c5',
	'^':  '\u00dc',
	'`':  '\u00e4',
	'{':  '\u00e6',
	'|':  '\u00f8',
	'}':  '\u00e5',
	'~':  '\u00fc',
}

CharsetNorwegianDanish is the Norwegian/Danish character set (ESC (E or ESC (6).

View Source
var CharsetSpanish = Charset{
	'#':  '\u00a3',
	'@':  '\u00a7',
	'[':  '\u00a1',
	'\\': '\u00d1',
	']':  '\u00bf',
	'{':  '\u00b0',
	'|':  '\u00f1',
	'}':  '\u00e7',
}

CharsetSpanish is the Spanish character set (ESC (Z).

View Source
var CharsetSwedish = Charset{
	'@':  '\u00c9',
	'[':  '\u00c4',
	'\\': '\u00d6',
	']':  '\u00c5',
	'^':  '\u00dc',
	'`':  '\u00e9',
	'{':  '\u00e4',
	'|':  '\u00f6',
	'}':  '\u00e5',
	'~':  '\u00fc',
}

CharsetSwedish is the Swedish character set (ESC (H or ESC (7).

View Source
var CharsetSwiss = Charset{
	'#':  '\u00f9',
	'@':  '\u00e0',
	'[':  '\u00e9',
	'\\': '\u00e7',
	']':  '\u00ea',
	'^':  '\u00ee',
	'_':  '\u00e8',
	'`':  '\u00f4',
	'{':  '\u00e4',
	'|':  '\u00f6',
	'}':  '\u00fc',
	'~':  '\u00fb',
}

CharsetSwiss is the Swiss character set (ESC (=).

View Source
var VT500TransitionTable = buildVT500TransitionTable()

VT500TransitionTable is the package-level VT500 parser transition table.

Functions

func CharDataAttr

func CharDataAttr(cd CharData) uint32

CharDataAttr returns the attribute (fg) from CharData.

func CharDataChar

func CharDataChar(cd CharData) string

CharDataChar returns the character string from CharData.

func CharDataCode

func CharDataCode(cd CharData) uint32

CharDataCode returns the codepoint from CharData.

func CharDataWidth

func CharDataWidth(cd CharData) int

CharDataWidth returns the display width from CharData.

func CreatePropertyValue

func CreatePropertyValue(charKind, width int, shouldJoin bool) int

CreatePropertyValue packs width and shouldJoin into a UnicodeCharProperties value.

func ExtractCharPropsWidth

func ExtractCharPropsWidth(value int) int

ExtractCharPropsWidth returns the character width from a UnicodeCharProperties value.

func ExtractShouldJoin

func ExtractShouldJoin(value int) bool

ExtractShouldJoin returns the shouldJoin flag from a UnicodeCharProperties value.

func FromColorRGB

func FromColorRGB(c ColorRGB) uint32

FromColorRGB packs an RGB triple into a uint32.

func IdentToString

func IdentToString(ident int) string

IdentToString converts a numeric identifier back to a human-readable string.

func StringToUtf32

func StringToUtf32(s string, target []uint32) int

StringToUtf32 decodes a Go string (UTF-8) into UTF-32 codepoints. This is simpler than the JS version since Go strings are UTF-8, not UTF-16.

func Utf32ToString

func Utf32ToString(data []uint32, start, end int) string

Utf32ToString converts UTF-32 codepoints back to a Go string.

Types

type ApcFallbackHandler

type ApcFallbackHandler func(ident int, action string, payload ...interface{})

ApcFallbackHandler is called when no registered handler matches the APC identifier.

type ApcHandler

type ApcHandler interface {
	Start()
	Put(data []uint32, start, end int)
	End(success bool) bool
}

ApcHandler is the interface for handlers that process APC sequences. Intentionally separate from OscHandler to mirror xterm.js type structure.

type ApcParser

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

ApcParser parses APC sequences and dispatches to registered handlers.

func NewApcParser

func NewApcParser() *ApcParser

NewApcParser creates a new ApcParser.

func (*ApcParser) ClearHandler

func (p *ApcParser) ClearHandler(ident int)

ClearHandler removes all handlers for the given identifier.

func (*ApcParser) Dispose

func (p *ApcParser) Dispose()

Dispose removes all handlers and resets state.

func (*ApcParser) End

func (p *ApcParser) End(success bool)

End signals the end of an APC sequence. success indicates whether the sequence terminated normally or was aborted.

func (*ApcParser) Put

func (p *ApcParser) Put(data []uint32, start, end int)

Put feeds payload data to the active APC handlers.

func (*ApcParser) RegisterHandler

func (p *ApcParser) RegisterHandler(ident int, handler ApcHandler) Disposable

RegisterHandler registers a handler for the given APC identifier. Returns a Disposable that removes the handler when disposed.

func (*ApcParser) Reset

func (p *ApcParser) Reset()

Reset forces cleanup of active handlers and resets parser state.

func (*ApcParser) SetHandlerFallback

func (p *ApcParser) SetHandlerFallback(handler ApcFallbackHandler)

SetHandlerFallback sets the fallback handler called when no handler matches.

func (*ApcParser) Start

func (p *ApcParser) Start(ident int)

Start begins a new APC sequence with the given identifier. The identifier is computed by the main parser from collect bytes and the final character (collect<<8 | code), matching the DCS pattern.

type ApcStringHandler

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

ApcStringHandler is a convenience wrapper that collects APC payload as a string and calls a callback function on End.

func NewApcStringHandler

func NewApcStringHandler(handler func(data string) bool) *ApcStringHandler

NewApcStringHandler creates an ApcStringHandler from a callback.

func (*ApcStringHandler) End

func (h *ApcStringHandler) End(success bool) bool

End calls the handler callback if the sequence ended successfully.

func (*ApcStringHandler) Put

func (h *ApcStringHandler) Put(data []uint32, start, end int)

Put appends payload data as a string.

func (*ApcStringHandler) Start

func (h *ApcStringHandler) Start()

Start resets the string accumulator.

type AttributeData

type AttributeData struct {
	Fg       uint32
	Bg       uint32
	Extended *ExtendedAttrs
}

AttributeData holds the fg, bg, and extended attributes for a cell.

func DefaultAttrData

func DefaultAttrData() AttributeData

DefaultAttrData returns an AttributeData with default (zero) values.

func (*AttributeData) Clone

func (a *AttributeData) Clone() AttributeData

Clone returns a deep copy.

func (*AttributeData) GetBgColor

func (a *AttributeData) GetBgColor() int

GetBgColor returns the background color value. Returns -1 for default color mode.

func (*AttributeData) GetBgColorMode

func (a *AttributeData) GetBgColorMode() uint32

func (*AttributeData) GetFgColor

func (a *AttributeData) GetFgColor() int

GetFgColor returns the foreground color value. Returns -1 for default color mode.

func (*AttributeData) GetFgColorMode

func (a *AttributeData) GetFgColorMode() uint32

func (*AttributeData) GetUnderlineColor

func (a *AttributeData) GetUnderlineColor() int

GetUnderlineColor returns the underline color value, falling back to fg color.

func (*AttributeData) GetUnderlineColorMode

func (a *AttributeData) GetUnderlineColorMode() uint32

GetUnderlineColorMode returns the color mode of the underline color, falling back to fg.

func (*AttributeData) GetUnderlineStyle

func (a *AttributeData) GetUnderlineStyle() UnderlineStyle

GetUnderlineStyle returns the effective underline style.

func (*AttributeData) GetUnderlineVariantOffset

func (a *AttributeData) GetUnderlineVariantOffset() int

GetUnderlineVariantOffset returns the underline variant offset from extended attrs.

func (*AttributeData) HasExtendedAttrs

func (a *AttributeData) HasExtendedAttrs() uint32

func (*AttributeData) IsAttributeDefault

func (a *AttributeData) IsAttributeDefault() bool

func (*AttributeData) IsBgDefault

func (a *AttributeData) IsBgDefault() bool

func (*AttributeData) IsBgPalette

func (a *AttributeData) IsBgPalette() bool

func (*AttributeData) IsBgRGB

func (a *AttributeData) IsBgRGB() bool
func (a *AttributeData) IsBlink() uint32

func (*AttributeData) IsBold

func (a *AttributeData) IsBold() uint32

func (*AttributeData) IsDim

func (a *AttributeData) IsDim() uint32

func (*AttributeData) IsFgDefault

func (a *AttributeData) IsFgDefault() bool

func (*AttributeData) IsFgPalette

func (a *AttributeData) IsFgPalette() bool

func (*AttributeData) IsFgRGB

func (a *AttributeData) IsFgRGB() bool

func (*AttributeData) IsInverse

func (a *AttributeData) IsInverse() uint32

func (*AttributeData) IsInvisible

func (a *AttributeData) IsInvisible() uint32

func (*AttributeData) IsItalic

func (a *AttributeData) IsItalic() uint32

func (*AttributeData) IsOverline

func (a *AttributeData) IsOverline() uint32

func (*AttributeData) IsProtected

func (a *AttributeData) IsProtected() uint32

func (*AttributeData) IsStrikethrough

func (a *AttributeData) IsStrikethrough() uint32

func (*AttributeData) IsUnderline

func (a *AttributeData) IsUnderline() uint32

IsUnderline checks both the fg underline flag and extended underline style.

func (*AttributeData) IsUnderlineColorDefault

func (a *AttributeData) IsUnderlineColorDefault() bool

IsUnderlineColorDefault returns whether the underline color is the default.

func (*AttributeData) IsUnderlineColorPalette

func (a *AttributeData) IsUnderlineColorPalette() bool

IsUnderlineColorPalette returns whether the underline color is a palette color.

func (*AttributeData) IsUnderlineColorRGB

func (a *AttributeData) IsUnderlineColorRGB() bool

IsUnderlineColorRGB returns whether the underline color is RGB.

func (*AttributeData) UpdateExtended

func (a *AttributeData) UpdateExtended()

UpdateExtended sets or clears the HAS_EXTENDED flag based on whether extended attrs are empty.

type Buffer

type Buffer struct {
	Lines *CircularList[*BufferLine]

	YDisp int // viewport scroll position
	YBase int // scroll offset (lines above viewport)
	Y     int // cursor row (relative to viewport)
	X     int // cursor column

	ScrollTop    int
	ScrollBottom int

	Tabs map[int]bool

	SavedState SavedCursorState

	Markers []*Marker
	// contains filtered or unexported fields
}

Buffer represents a terminal buffer (normal or alt).

func NewBuffer

func NewBuffer(opts BufferOptions) *Buffer

NewBuffer creates a new Buffer with the given options.

func (*Buffer) AddMarker

func (b *Buffer) AddMarker(y int) *Marker

AddMarker creates a marker at the given line and registers it for automatic adjustment on trim/insert/delete events.

func (*Buffer) Clear

func (b *Buffer) Clear()

Clear resets the buffer to its initial state.

func (*Buffer) ClearAllMarkers

func (b *Buffer) ClearAllMarkers()

ClearAllMarkers disposes and removes all markers.

func (*Buffer) ClearMarkers

func (b *Buffer) ClearMarkers(y int)

ClearMarkers disposes and removes all markers on the given line.

func (*Buffer) Cols

func (b *Buffer) Cols() int

Cols returns the current column count.

func (*Buffer) Dispose

func (b *Buffer) Dispose()

Dispose cleans up the buffer by disposing all markers and their event listeners.

func (*Buffer) FillViewportRows

func (b *Buffer) FillViewportRows(fillAttr *AttributeData)

FillViewportRows fills the buffer with blank lines up to the viewport size.

func (*Buffer) GetBlankLine

func (b *Buffer) GetBlankLine(attr *AttributeData, isWrapped bool) *BufferLine

GetBlankLine creates a new blank BufferLine with the given attributes.

func (*Buffer) GetNullCell

func (b *Buffer) GetNullCell(attr *AttributeData) *CellData

GetNullCell returns a null cell, optionally with the given attributes.

func (*Buffer) GetWhitespaceCell

func (b *Buffer) GetWhitespaceCell(attr *AttributeData) *CellData

GetWhitespaceCell returns a whitespace cell, optionally with the given attributes.

func (*Buffer) GetWrappedRangeForLine

func (b *Buffer) GetWrappedRangeForLine(y int) (first, last int)

GetWrappedRangeForLine returns the first and last line indices of the wrapped line group.

func (*Buffer) HasScrollback

func (b *Buffer) HasScrollback() bool

HasScrollback returns true if the buffer has scrollback enabled and capacity.

func (*Buffer) IsCursorInViewport

func (b *Buffer) IsCursorInViewport() bool

IsCursorInViewport returns true if the cursor is within the visible viewport.

func (*Buffer) NextStop

func (b *Buffer) NextStop(x int) int

NextStop returns the next tab stop position after x.

func (*Buffer) PrevStop

func (b *Buffer) PrevStop(x int) int

PrevStop returns the previous tab stop position before x.

func (*Buffer) Resize

func (b *Buffer) Resize(newCols, newRows int)

Resize adjusts the buffer dimensions. Handles row/column changes and reflow.

func (*Buffer) Rows

func (b *Buffer) Rows() int

Rows returns the current row count.

func (*Buffer) SetupTabStops

func (b *Buffer) SetupTabStops(startCol int)

SetupTabStops initializes tab stops. If startCol >= 0, extends from that position; otherwise resets all tab stops.

func (*Buffer) TranslateBufferLineToString

func (b *Buffer) TranslateBufferLineToString(lineIndex int, trimRight bool, startCol, endCol int) string

TranslateBufferLineToString converts a buffer line to a string.

type BufferActivateEvent

type BufferActivateEvent struct {
	ActiveBuffer   *Buffer
	InactiveBuffer *Buffer
}

BufferActivateEvent is fired when the active buffer changes.

type BufferIndex

type BufferIndex [2]int

BufferIndex denotes a position in the buffer: [rowIndex, colIndex].

type BufferLine

type BufferLine struct {
	Len       int
	IsWrapped bool
	// contains filtered or unexported fields
}

BufferLine stores a single terminal line as a flat []uint32 with 3 values per cell.

func NewBufferLine

func NewBufferLine(cols int, fillCell *CellData, isWrapped bool) *BufferLine

NewBufferLine creates a BufferLine with cols cells, filled with fillCell. If fillCell is nil, cells are filled with null cell defaults.

func (*BufferLine) AddCodepointToCell

func (bl *BufferLine) AddCodepointToCell(index int, codePoint uint32, width int)

AddCodepointToCell adds a combining codepoint to the cell at index.

func (*BufferLine) CleanupMemory

func (bl *BufferLine) CleanupMemory() int

CleanupMemory reallocates the backing array if it exceeds the threshold. Returns 1 if cleanup happened, 0 otherwise.

func (*BufferLine) Clone

func (bl *BufferLine) Clone() *BufferLine

Clone returns a deep copy of the BufferLine.

func (*BufferLine) CopyCellsFrom

func (bl *BufferLine) CopyCellsFrom(src *BufferLine, srcCol, destCol, length int, applyInReverse bool)

CopyCellsFrom copies length cells from src starting at srcCol to bl starting at destCol.

func (*BufferLine) CopyFrom

func (bl *BufferLine) CopyFrom(line *BufferLine)

CopyFrom copies all data from another BufferLine.

func (*BufferLine) DeleteCells

func (bl *BufferLine) DeleteCells(pos, n int, fillCell *CellData)

DeleteCells deletes n cells at pos, shifting remaining cells left. Vacated cells at the end are filled with fillCell.

func (*BufferLine) Fill

func (bl *BufferLine) Fill(fillCell *CellData, respectProtect bool)

Fill fills all cells with fillCell.

func (*BufferLine) Get

func (bl *BufferLine) Get(index int) CharData

Get returns the cell at index as a legacy CharData tuple.

func (*BufferLine) GetBg

func (bl *BufferLine) GetBg(index int) uint32

GetBg returns the bg attribute of the cell at index.

func (*BufferLine) GetCodePoint

func (bl *BufferLine) GetCodePoint(index int) uint32

GetCodePoint returns the codepoint of the cell at index. For combined cells, returns the last char code of the combined string.

func (*BufferLine) GetExtended

func (bl *BufferLine) GetExtended(index int) *ExtendedAttrs

GetExtended returns the extended attributes of the cell at index.

func (*BufferLine) GetFg

func (bl *BufferLine) GetFg(index int) uint32

GetFg returns the fg attribute of the cell at index.

func (*BufferLine) GetNoBgTrimmedLength

func (bl *BufferLine) GetNoBgTrimmedLength() int

GetNoBgTrimmedLength returns the trimmed length considering both content and bg color.

func (*BufferLine) GetString

func (bl *BufferLine) GetString(index int) string

GetString returns the string content of the cell at index.

func (*BufferLine) GetTrimmedLength

func (bl *BufferLine) GetTrimmedLength() int

GetTrimmedLength returns the number of columns with content, accounting for wide chars.

func (*BufferLine) GetWidth

func (bl *BufferLine) GetWidth(index int) int

GetWidth returns the display width of the cell at index.

func (*BufferLine) HasContent

func (bl *BufferLine) HasContent(index int) uint32

HasContent returns non-zero if the cell at index has content.

func (*BufferLine) HasWidth

func (bl *BufferLine) HasWidth(index int) uint32

HasWidth returns non-zero if the cell at index has a width set.

func (*BufferLine) InsertCells

func (bl *BufferLine) InsertCells(pos, n int, fillCell *CellData)

InsertCells inserts n cells at pos, shifting existing cells right. Cells that fall off the end are lost. New cells are filled with fillCell.

func (*BufferLine) IsCombined

func (bl *BufferLine) IsCombined(index int) uint32

IsCombined returns non-zero if the cell at index has combined content.

func (*BufferLine) IsProtected

func (bl *BufferLine) IsProtected(index int) uint32

IsProtected returns non-zero if the cell at index has the PROTECTED flag.

func (*BufferLine) LoadCell

func (bl *BufferLine) LoadCell(index int, cell *CellData) *CellData

LoadCell loads the cell at index into the provided CellData, returning it.

func (*BufferLine) ReplaceCells

func (bl *BufferLine) ReplaceCells(start, end int, fillCell *CellData, respectProtect bool)

ReplaceCells replaces cells in [start, end) with fillCell.

func (*BufferLine) Resize

func (bl *BufferLine) Resize(cols int, fillCell *CellData) bool

Resize resizes the line to cols cells, filling new cells with fillCell. Returns true if a CleanupMemory call would free excess memory.

func (*BufferLine) Set

func (bl *BufferLine) Set(index int, value CharData)

Set sets the cell at index from a legacy CharData tuple.

func (*BufferLine) SetCell

func (bl *BufferLine) SetCell(index int, cell *CellData)

SetCell sets the cell at index from a CellData.

func (*BufferLine) SetCellFromCodepoint

func (bl *BufferLine) SetCellFromCodepoint(index int, codePoint uint32, width int, attrs *AttributeData)

SetCellFromCodepoint sets a cell from a codepoint, width, and attribute data.

func (*BufferLine) TranslateToString

func (bl *BufferLine) TranslateToString(trimRight bool, startCol, endCol int) string

TranslateToString converts the line to a string. If trimRight is true, trailing empty cells are excluded. startCol and endCol define the range (endCol is exclusive, -1 means bl.Len).

type BufferOptions

type BufferOptions struct {
	Cols           int
	Rows           int
	Scrollback     int
	TabStopWidth   int
	HasScrollback  bool
	WindowsPtyMode bool // simplified: true if windowsPty backend is set
}

BufferOptions configures a Buffer. In xterm.js these come from OptionsService/BufferService; here they are passed directly to avoid DI.

type BufferResizeEvent

type BufferResizeEvent struct {
	Cols        int
	Rows        int
	ColsChanged bool
	RowsChanged bool
}

BufferResizeEvent is fired when the terminal dimensions change.

type BufferService

type BufferService struct {
	Cols    int
	Rows    int
	Buffers *BufferSet

	// IsUserScrolling is true when the user has scrolled up from the bottom.
	IsUserScrolling bool

	OnResizeEmitter EventEmitter[BufferResizeEvent]
	OnScrollEmitter EventEmitter[int]
	// contains filtered or unexported fields
}

BufferService wraps a BufferSet with scroll management and resize events.

func NewBufferService

func NewBufferService(opts *OptionsService) *BufferService

NewBufferService creates a BufferService from the given options.

func (*BufferService) Buffer

func (bs *BufferService) Buffer() *Buffer

Buffer returns the currently active buffer.

func (*BufferService) Dispose

func (bs *BufferService) Dispose()

Dispose cleans up event emitters.

func (*BufferService) Reset

func (bs *BufferService) Reset()

Reset recreates both buffers and resets scroll state.

func (*BufferService) Resize

func (bs *BufferService) Resize(cols, rows int)

Resize changes the terminal dimensions and fires the resize event.

func (*BufferService) Scroll

func (bs *BufferService) Scroll(eraseAttr *AttributeData, isWrapped bool)

Scroll scrolls the terminal down one line, creating a blank line at the bottom of the scroll region.

func (*BufferService) ScrollLines

func (bs *BufferService) ScrollLines(disp int, suppressScrollEvent bool)

ScrollLines scrolls the viewport by disp lines (negative = up, positive = down).

type BufferSet

type BufferSet struct {
	OnBufferActivateEmitter EventEmitter[BufferActivateEvent]
	// contains filtered or unexported fields
}

BufferSet manages the normal and alt screen buffers.

func NewBufferSet

func NewBufferSet(cols, rows, scrollback, tabStopWidth int) *BufferSet

NewBufferSet creates a BufferSet with normal and alt buffers.

func (*BufferSet) ActivateAltBuffer

func (bs *BufferSet) ActivateAltBuffer(fillAttr *AttributeData)

ActivateAltBuffer switches to the alt buffer. Fills the alt buffer viewport and copies cursor position from normal.

func (*BufferSet) ActivateNormalBuffer

func (bs *BufferSet) ActivateNormalBuffer()

ActivateNormalBuffer switches to the normal buffer. Copies cursor position from alt and clears the alt buffer.

func (*BufferSet) Active

func (bs *BufferSet) Active() *Buffer

Active returns the currently active buffer.

func (*BufferSet) Alt

func (bs *BufferSet) Alt() *Buffer

Alt returns the alt buffer.

func (*BufferSet) Dispose

func (bs *BufferSet) Dispose()

Dispose cleans up buffers and event emitters.

func (*BufferSet) Normal

func (bs *BufferSet) Normal() *Buffer

Normal returns the normal buffer.

func (*BufferSet) Reset

func (bs *BufferSet) Reset()

Reset recreates both buffers and activates the normal buffer. Old buffers are disposed to clean up markers and event listeners.

func (*BufferSet) Resize

func (bs *BufferSet) Resize(newCols, newRows int)

Resize resizes both buffers.

func (*BufferSet) SetWindowsPtyMode

func (bs *BufferSet) SetWindowsPtyMode(windowsPty bool)

func (*BufferSet) SetupTabStops

func (bs *BufferSet) SetupTabStops(startCol int)

SetupTabStops sets up tab stops on both buffers.

type CellData

type CellData struct {
	AttributeData
	Content      uint32
	CombinedData string
}

CellData represents a single cell in the terminal buffer. It embeds AttributeData for fg/bg/extended and adds content + combined data.

func CellDataFromCharData

func CellDataFromCharData(cd CharData) *CellData

CellDataFromCharData creates a CellData from a legacy CharData tuple.

func NewCellData

func NewCellData() *CellData

NewCellData creates a zero-valued CellData with initialized extended attrs.

func (*CellData) AttributesEqual

func (c *CellData) AttributesEqual(other *CellData) bool

AttributesEqual returns true if this cell has the same visual attributes as other. Compares fg/bg color and mode, all text decoration flags, and underline style/color.

func (*CellData) GetAsCharData

func (c *CellData) GetAsCharData() CharData

GetAsCharData returns the cell as a legacy CharData tuple.

func (*CellData) GetChars

func (c *CellData) GetChars() string

GetChars returns the string representation of the cell content.

func (*CellData) GetCode

func (c *CellData) GetCode() uint32

GetCode returns the codepoint of the cell. For combined strings, returns the codepoint of the last character (matching xterm.js behavior).

func (*CellData) GetWidth

func (c *CellData) GetWidth() int

GetWidth returns the display width of the cell (0, 1, or 2).

func (*CellData) IsCombined

func (c *CellData) IsCombined() uint32

IsCombined returns non-zero if the cell contains combined/multi-codepoint content.

func (*CellData) SetFromCharData

func (c *CellData) SetFromCharData(cd CharData)

SetFromCharData populates the cell from a legacy CharData tuple.

type CharData

type CharData [4]interface{}

CharData is the legacy cell representation: [attr, char, width, code].

func NewCharData

func NewCharData(attr uint32, ch string, width int, code uint32) CharData

NewCharData creates a CharData tuple.

type Charset

type Charset map[byte]rune

Charset maps single-byte characters to replacement strings (e.g., DEC special graphics).

type CharsetService

type CharsetService struct {
	Charset Charset
	GLevel  int
	// contains filtered or unexported fields
}

CharsetService manages the active charset state (G0-G3, GL level).

func NewCharsetService

func NewCharsetService() *CharsetService

NewCharsetService creates a CharsetService in the default state.

func (*CharsetService) Charsets

func (cs *CharsetService) Charsets() []Charset

Charsets returns the G0-G3 charset slots.

func (*CharsetService) Reset

func (cs *CharsetService) Reset()

Reset clears all charset state to defaults.

func (*CharsetService) SetgCharset

func (cs *CharsetService) SetgCharset(g int, charset Charset)

SetgCharset assigns a charset to a G-set slot. If the slot is the active GL level, the active charset is updated.

func (*CharsetService) SetgLevel

func (cs *CharsetService) SetgLevel(g int)

SetgLevel sets the active GL level and updates the active charset.

type CircularList

type CircularList[T any] struct {
	OnDeleteEmitter EventEmitter[DeleteEvent]
	OnInsertEmitter EventEmitter[InsertEvent]
	OnTrimEmitter   EventEmitter[int]
	// contains filtered or unexported fields
}

CircularList is a generic circular buffer with a fixed maximum size. When Push is called on a full list, the oldest element is overwritten and the OnTrim event fires.

func NewCircularList

func NewCircularList[T any](maxLength int) *CircularList[T]

NewCircularList creates a CircularList with the given maximum length.

func (*CircularList[T]) Dispose

func (cl *CircularList[T]) Dispose()

Dispose cleans up event emitters.

func (*CircularList[T]) Get

func (cl *CircularList[T]) Get(index int) T

Get returns the element at the given logical index. No bounds checking for performance (matches xterm.js).

func (*CircularList[T]) IsFull

func (cl *CircularList[T]) IsFull() bool

IsFull returns true if the list is at maximum capacity.

func (*CircularList[T]) Length

func (cl *CircularList[T]) Length() int

Length returns the number of elements in the list.

func (*CircularList[T]) MaxLength

func (cl *CircularList[T]) MaxLength() int

MaxLength returns the maximum capacity.

func (*CircularList[T]) Pop

func (cl *CircularList[T]) Pop() T

Pop removes and returns the last element.

func (*CircularList[T]) Push

func (cl *CircularList[T]) Push(value T)

Push appends a value. If the list is full, the oldest element is overwritten and OnTrim fires with count=1.

func (*CircularList[T]) Recycle

func (cl *CircularList[T]) Recycle() T

Recycle advances the ring buffer and returns the current tail element for reuse. The buffer must be full or this panics.

func (*CircularList[T]) Set

func (cl *CircularList[T]) Set(index int, value T)

Set sets the element at the given logical index.

func (*CircularList[T]) SetLength

func (cl *CircularList[T]) SetLength(newLength int)

SetLength sets the logical length. If growing, new slots contain zero values.

func (*CircularList[T]) SetMaxLength

func (cl *CircularList[T]) SetMaxLength(newMaxLength int)

SetMaxLength resizes the backing array, preserving existing elements.

func (*CircularList[T]) ShiftElements

func (cl *CircularList[T]) ShiftElements(start, count, offset int)

ShiftElements shifts count elements starting at start by offset positions.

func (*CircularList[T]) Splice

func (cl *CircularList[T]) Splice(start, deleteCount int, items ...T)

Splice deletes deleteCount elements starting at start, then inserts items at that position.

func (*CircularList[T]) TrimStart

func (cl *CircularList[T]) TrimStart(count int)

TrimStart removes count elements from the beginning of the list.

type Color

type Color struct {
	CSS  string
	RGBA uint32
}

Color represents a color with a CSS string and a 32-bit RGBA value.

type ColorEvent

type ColorEvent struct {
	Type  ColorRequestType
	Index int // ColorIndex (0-255) or SpecialColorIndex
	Color *ColorRGB
}

ColorEvent is a single color request entry (set, report, or restore).

type ColorRGB

type ColorRGB [3]uint8

ColorRGB is an [R, G, B] color triple, each component 0-255.

func ToColorRGB

func ToColorRGB(v uint32) ColorRGB

ToColorRGB extracts an RGB triple from a packed color value.

type ColorRequestType

type ColorRequestType int

ColorRequestType identifies the kind of color request (OSC 4/10/11/12).

const (
	ColorRequestReport  ColorRequestType = 0
	ColorRequestSet     ColorRequestType = 1
	ColorRequestRestore ColorRequestType = 2
)

type CoreMouseAction

type CoreMouseAction int

CoreMouseAction identifies a mouse action.

const (
	MouseActionUp    CoreMouseAction = 0
	MouseActionDown  CoreMouseAction = 1
	MouseActionLeft  CoreMouseAction = 2
	MouseActionRight CoreMouseAction = 3
	MouseActionMove  CoreMouseAction = 32
)

type CoreMouseButton

type CoreMouseButton int

CoreMouseButton identifies a mouse button.

const (
	MouseButtonLeft   CoreMouseButton = 0
	MouseButtonMiddle CoreMouseButton = 1
	MouseButtonRight  CoreMouseButton = 2
	MouseButtonNone   CoreMouseButton = 3
	MouseButtonWheel  CoreMouseButton = 4
	MouseButtonAux1   CoreMouseButton = 8
	MouseButtonAux2   CoreMouseButton = 9
	MouseButtonAux3   CoreMouseButton = 10
	MouseButtonAux4   CoreMouseButton = 11
	MouseButtonAux5   CoreMouseButton = 12
	MouseButtonAux6   CoreMouseButton = 13
	MouseButtonAux7   CoreMouseButton = 14
	MouseButtonAux8   CoreMouseButton = 15
)

type CoreMouseEncoding

type CoreMouseEncoding func(e *CoreMouseEvent) string

CoreMouseEncoding is a function that encodes a CoreMouseEvent into an escape sequence.

type CoreMouseEvent

type CoreMouseEvent struct {
	Col    int
	Row    int
	X      int
	Y      int
	Button CoreMouseButton
	Action CoreMouseAction
	Ctrl   bool
	Alt    bool
	Shift  bool
}

CoreMouseEvent represents a mouse event in the terminal core.

type CoreMouseEventType

type CoreMouseEventType int

CoreMouseEventType is a bitmask of mouse event categories a protocol wants to receive.

const (
	MouseEventNone  CoreMouseEventType = 0
	MouseEventDown  CoreMouseEventType = 1
	MouseEventUp    CoreMouseEventType = 2
	MouseEventDrag  CoreMouseEventType = 4
	MouseEventMove  CoreMouseEventType = 8
	MouseEventWheel CoreMouseEventType = 16
)

type CoreService

type CoreService struct {
	IsCursorInitialized bool
	IsCursorHidden      bool
	Modes               Modes
	DecPrivateModes     DecPrivateModes
	KittyKeyboard       KittyKeyboardState

	OnDataEmitter                  EventEmitter[string]
	OnUserInputEmitter             EventEmitter[struct{}]
	OnBinaryEmitter                EventEmitter[string]
	OnRequestScrollToBottomEmitter EventEmitter[struct{}]
	// contains filtered or unexported fields
}

CoreService manages terminal modes and provides data/binary event plumbing.

func NewCoreService

func NewCoreService(opts *OptionsService) *CoreService

NewCoreService creates a CoreService. The OptionsService is used to check disableStdin and scrollOnUserInput. bufferService is not stored; callers pass buffer state through TriggerDataEvent parameters.

func (*CoreService) Dispose

func (cs *CoreService) Dispose()

Dispose cleans up all event emitters.

func (*CoreService) Reset

func (cs *CoreService) Reset()

Reset restores modes and kitty keyboard state to defaults.

func (*CoreService) TriggerBinaryEvent

func (cs *CoreService) TriggerBinaryEvent(data string)

TriggerBinaryEvent fires the OnBinary event. Respects disableStdin.

func (*CoreService) TriggerDataEvent

func (cs *CoreService) TriggerDataEvent(data string, wasUserInput bool, shouldScroll bool)

TriggerDataEvent fires the OnData event. If wasUserInput is true and scrollOnUserInput is enabled, it also fires OnRequestScrollToBottom and OnUserInput. Respects disableStdin.

shouldScroll indicates whether the viewport is not at the bottom (ybase != ydisp). The caller is responsible for computing this from the active buffer.

type CsiFallbackHandler

type CsiFallbackHandler func(ident int, params *Params)

CsiFallbackHandler is called when no CSI handler matches.

type CsiHandler

type CsiHandler func(params *Params) bool

CsiHandler handles CSI sequences. Returns true to stop handler chain bubbling.

type CursorInactiveStyle

type CursorInactiveStyle string

CursorInactiveStyle is the shape of the cursor when the terminal is not focused.

const (
	CursorInactiveStyleOutline   CursorInactiveStyle = "outline"
	CursorInactiveStyleBlock     CursorInactiveStyle = "block"
	CursorInactiveStyleBar       CursorInactiveStyle = "bar"
	CursorInactiveStyleUnderline CursorInactiveStyle = "underline"
	CursorInactiveStyleNone      CursorInactiveStyle = "none"
)

type CursorStyle

type CursorStyle string

CursorStyle is the shape of the cursor.

const (
	CursorStyleBlock     CursorStyle = "block"
	CursorStyleUnderline CursorStyle = "underline"
	CursorStyleBar       CursorStyle = "bar"
)

type DcsFallbackHandler

type DcsFallbackHandler func(ident int, action string, payload ...interface{})

DcsFallbackHandler is called when no registered handler matches the DCS identifier.

type DcsHandler

type DcsHandler interface {
	Hook(params *Params)
	Put(data []uint32, start, end int)
	Unhook(success bool) bool
}

DcsHandler is the interface for handlers that process DCS sequences.

type DcsParser

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

DcsParser parses DCS sequences and dispatches to registered handlers.

func NewDcsParser

func NewDcsParser() *DcsParser

NewDcsParser creates a new DcsParser.

func (*DcsParser) ClearHandler

func (p *DcsParser) ClearHandler(ident int)

ClearHandler removes all handlers for the given identifier.

func (*DcsParser) Dispose

func (p *DcsParser) Dispose()

Dispose removes all handlers and resets state.

func (*DcsParser) Hook

func (p *DcsParser) Hook(ident int, params *Params)

Hook begins a new DCS sequence with the given identifier and parameters.

func (*DcsParser) Put

func (p *DcsParser) Put(data []uint32, start, end int)

Put feeds payload data to the active DCS handlers.

func (*DcsParser) RegisterHandler

func (p *DcsParser) RegisterHandler(ident int, handler DcsHandler) Disposable

RegisterHandler registers a handler for the given DCS identifier. Returns a Disposable that removes the handler when disposed.

func (*DcsParser) Reset

func (p *DcsParser) Reset()

Reset forces cleanup of active handlers and resets parser state.

func (*DcsParser) SetHandlerFallback

func (p *DcsParser) SetHandlerFallback(handler DcsFallbackHandler)

SetHandlerFallback sets the fallback handler called when no handler matches.

func (*DcsParser) Unhook

func (p *DcsParser) Unhook(success bool)

Unhook signals the end of a DCS sequence. success indicates whether the sequence terminated normally or was aborted.

type DcsStringHandler

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

DcsStringHandler is a convenience wrapper that collects DCS payload as a string and calls a callback function on Unhook.

func NewDcsStringHandler

func NewDcsStringHandler(handler func(data string, params *Params) bool) *DcsStringHandler

NewDcsStringHandler creates a DcsStringHandler from a callback.

func (*DcsStringHandler) Hook

func (h *DcsStringHandler) Hook(params *Params)

Hook stores the params (cloned if non-trivial) and resets the accumulator.

func (*DcsStringHandler) Put

func (h *DcsStringHandler) Put(data []uint32, start, end int)

Put appends payload data as a string.

func (*DcsStringHandler) Unhook

func (h *DcsStringHandler) Unhook(success bool) bool

Unhook calls the handler callback if the sequence ended successfully.

type DecPrivateModes

type DecPrivateModes struct {
	ApplicationCursorKeys bool
	ApplicationKeypad     bool
	BracketedPasteMode    bool
	ColorSchemeUpdates    bool
	CursorBlink           *bool        // nil = not set by DECSET/DECRST
	CursorBlinkOverride   *bool        // nil = not set by DECSCUSR
	CursorStyle           *CursorStyle // nil = not set
	MouseEncoding         string       // "DEFAULT", "SGR", "SGR_PIXELS"
	MouseTrackingMode     string       // "NONE", "X10", "VT200", "DRAG", "ANY"
	Origin                bool
	ReverseWraparound     bool
	SendFocus             bool
	SynchronizedOutput    bool
	Win32InputMode        bool
	Wraparound            bool
}

DecPrivateModes tracks DEC private mode settings.

type DeleteEvent

type DeleteEvent struct {
	Index  int
	Amount int
}

DeleteEvent is fired when items are deleted from a CircularList.

type DirtyRowTracker

type DirtyRowTracker struct {
	Start int
	End   int
	// contains filtered or unexported fields
}

DirtyRowTracker tracks which rows were modified during a parse cycle.

func (*DirtyRowTracker) ClearRange

func (d *DirtyRowTracker) ClearRange()

func (*DirtyRowTracker) MarkAllDirty

func (d *DirtyRowTracker) MarkAllDirty()

func (*DirtyRowTracker) MarkDirty

func (d *DirtyRowTracker) MarkDirty(y int)

func (*DirtyRowTracker) MarkRangeDirty

func (d *DirtyRowTracker) MarkRangeDirty(y1, y2 int)

type Disposable

type Disposable interface {
	Dispose()
}

Disposable represents a resource that can be disposed to free associated resources.

func CombinedDisposable

func CombinedDisposable(disposables ...Disposable) Disposable

CombinedDisposable creates a Disposable that disposes all given disposables.

type DisposableStore

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

DisposableStore collects disposables and disposes them all at once.

func (*DisposableStore) Add

func (s *DisposableStore) Add(d Disposable)

Add registers a disposable. If the store is already disposed, the disposable is disposed immediately.

func (*DisposableStore) Clear

func (s *DisposableStore) Clear()

Clear disposes all registered disposables but keeps the store usable.

func (*DisposableStore) Dispose

func (s *DisposableStore) Dispose()

Dispose disposes all registered disposables and marks the store as disposed.

func (*DisposableStore) IsDisposed

func (s *DisposableStore) IsDisposed() bool

IsDisposed returns whether the store has been disposed.

type ErrorHandler

type ErrorHandler func(state ParsingState) ParsingState

ErrorHandler processes parsing errors. Returns a (possibly modified) ParsingState. Set abort=true in the returned state to stop parsing.

type EscFallbackHandler

type EscFallbackHandler func(ident int)

EscFallbackHandler is called when no ESC handler matches.

type EscHandler

type EscHandler func() bool

EscHandler handles ESC sequences. Returns true to stop handler chain bubbling.

type EscapeSequenceParser

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

EscapeSequenceParser is a synchronous VT500-compatible escape sequence parser.

func NewEscapeSequenceParser

func NewEscapeSequenceParser() *EscapeSequenceParser

NewEscapeSequenceParser creates a new parser with the VT500 transition table.

func NewEscapeSequenceParserWithTable

func NewEscapeSequenceParserWithTable(table *TransitionTable) *EscapeSequenceParser

NewEscapeSequenceParserWithTable creates a new parser with a custom transition table.

func (*EscapeSequenceParser) ClearApcHandler

func (p *EscapeSequenceParser) ClearApcHandler(id FunctionIdentifier)

ClearApcHandler removes all APC handlers for the identifier.

func (*EscapeSequenceParser) ClearCsiHandler

func (p *EscapeSequenceParser) ClearCsiHandler(id FunctionIdentifier)

ClearCsiHandler removes all handlers for a CSI function identifier.

func (*EscapeSequenceParser) ClearDcsHandler

func (p *EscapeSequenceParser) ClearDcsHandler(id FunctionIdentifier)

ClearDcsHandler removes all DCS handlers for the identifier.

func (*EscapeSequenceParser) ClearErrorHandler

func (p *EscapeSequenceParser) ClearErrorHandler()

ClearErrorHandler resets the error handler to the default.

func (*EscapeSequenceParser) ClearEscHandler

func (p *EscapeSequenceParser) ClearEscHandler(id FunctionIdentifier)

ClearEscHandler removes all handlers for an ESC function identifier.

func (*EscapeSequenceParser) ClearExecuteHandler

func (p *EscapeSequenceParser) ClearExecuteHandler(code byte)

ClearExecuteHandler removes the handler for a specific control code.

func (*EscapeSequenceParser) ClearOscHandler

func (p *EscapeSequenceParser) ClearOscHandler(ident int)

ClearOscHandler removes all OSC handlers for the identifier.

func (*EscapeSequenceParser) ClearPrintHandler

func (p *EscapeSequenceParser) ClearPrintHandler()

ClearPrintHandler resets the print handler to the fallback.

func (*EscapeSequenceParser) CurrentState

func (p *EscapeSequenceParser) CurrentState() ParserState

CurrentState returns the current parser state.

func (*EscapeSequenceParser) Dispose

func (p *EscapeSequenceParser) Dispose()

Dispose cleans up all parser resources.

func (*EscapeSequenceParser) Parse

func (p *EscapeSequenceParser) Parse(data []uint32, length int)

Parse processes UTF-32 codepoints in data[0:length]. This is the main parse loop, fully synchronous (no async/promise support).

func (*EscapeSequenceParser) PrecedingJoinState

func (p *EscapeSequenceParser) PrecedingJoinState() int

PrecedingJoinState returns the preceding grapheme join state.

func (*EscapeSequenceParser) RegisterApcHandler

func (p *EscapeSequenceParser) RegisterApcHandler(id FunctionIdentifier, handler ApcHandler) Disposable

RegisterApcHandler registers an APC handler.

func (*EscapeSequenceParser) RegisterCsiHandler

func (p *EscapeSequenceParser) RegisterCsiHandler(id FunctionIdentifier, handler CsiHandler) Disposable

RegisterCsiHandler registers a handler for a CSI function identifier. Returns a Disposable that removes the handler.

func (*EscapeSequenceParser) RegisterDcsHandler

func (p *EscapeSequenceParser) RegisterDcsHandler(id FunctionIdentifier, handler DcsHandler) Disposable

RegisterDcsHandler registers a DCS handler.

func (*EscapeSequenceParser) RegisterEscHandler

func (p *EscapeSequenceParser) RegisterEscHandler(id FunctionIdentifier, handler EscHandler) Disposable

RegisterEscHandler registers a handler for an ESC function identifier. Returns a Disposable that removes the handler.

func (*EscapeSequenceParser) RegisterExecuteHandler

func (p *EscapeSequenceParser) RegisterExecuteHandler(code byte, handler ExecuteHandler) Disposable

RegisterExecuteHandler registers a handler for a specific control code. Returns a Disposable that removes the handler.

func (*EscapeSequenceParser) RegisterOscHandler

func (p *EscapeSequenceParser) RegisterOscHandler(ident int, handler OscHandler) Disposable

RegisterOscHandler registers an OSC handler.

func (*EscapeSequenceParser) Reset

func (p *EscapeSequenceParser) Reset()

Reset resets the parser to its initial state.

func (*EscapeSequenceParser) SetApcHandlerFallback

func (p *EscapeSequenceParser) SetApcHandlerFallback(handler ApcFallbackHandler)

SetApcHandlerFallback sets the APC fallback handler.

func (*EscapeSequenceParser) SetCsiHandlerFallback

func (p *EscapeSequenceParser) SetCsiHandlerFallback(handler CsiFallbackHandler)

SetCsiHandlerFallback sets the fallback CSI handler.

func (*EscapeSequenceParser) SetDcsHandlerFallback

func (p *EscapeSequenceParser) SetDcsHandlerFallback(handler DcsFallbackHandler)

SetDcsHandlerFallback sets the DCS fallback handler.

func (*EscapeSequenceParser) SetErrorHandler

func (p *EscapeSequenceParser) SetErrorHandler(handler ErrorHandler)

SetErrorHandler sets the error handler.

func (*EscapeSequenceParser) SetEscHandlerFallback

func (p *EscapeSequenceParser) SetEscHandlerFallback(handler EscFallbackHandler)

SetEscHandlerFallback sets the fallback ESC handler.

func (*EscapeSequenceParser) SetExecuteHandlerFallback

func (p *EscapeSequenceParser) SetExecuteHandlerFallback(handler ExecuteFallbackHandler)

SetExecuteHandlerFallback sets the fallback execute handler.

func (*EscapeSequenceParser) SetOscHandlerFallback

func (p *EscapeSequenceParser) SetOscHandlerFallback(handler OscFallbackHandler)

SetOscHandlerFallback sets the OSC fallback handler.

func (*EscapeSequenceParser) SetPrecedingJoinState

func (p *EscapeSequenceParser) SetPrecedingJoinState(state int)

SetPrecedingJoinState sets the preceding grapheme join state.

func (*EscapeSequenceParser) SetPrintHandler

func (p *EscapeSequenceParser) SetPrintHandler(handler PrintHandler)

SetPrintHandler sets the handler for printable character ranges.

func (*EscapeSequenceParser) SetPrintHandlerFallback

func (p *EscapeSequenceParser) SetPrintHandlerFallback(handler PrintFallbackHandler)

SetPrintHandlerFallback sets the fallback print handler.

type EventEmitter

type EventEmitter[T any] struct {
	// contains filtered or unexported fields
}

EventEmitter is a synchronous event emitter. Listeners are called in registration order when Fire is called.

func (*EventEmitter[T]) Dispose

func (e *EventEmitter[T]) Dispose()

Dispose removes all listeners and prevents future subscriptions.

func (*EventEmitter[T]) Event

func (e *EventEmitter[T]) Event(listener func(T)) Disposable

Event registers a listener and returns a Disposable that removes it.

func (*EventEmitter[T]) Fire

func (e *EventEmitter[T]) Fire(value T)

Fire invokes all registered listeners synchronously with the given value. Listeners that unsubscribe during iteration are handled safely via snapshot.

func (*EventEmitter[T]) HasListeners

func (e *EventEmitter[T]) HasListeners() bool

HasListeners returns true if there are any active listeners.

type ExecuteFallbackHandler

type ExecuteFallbackHandler func(code uint32)

ExecuteFallbackHandler is called when no execute handler matches.

type ExecuteHandler

type ExecuteHandler func()

ExecuteHandler handles C0/C1 control codes.

type ExtendedAttrs

type ExtendedAttrs struct {
	Payload any
	// contains filtered or unexported fields
}

ExtendedAttrs holds extended cell attributes (underline style, underline color, URL ID, and an arbitrary payload).

func NewExtendedAttrs

func NewExtendedAttrs(ext uint32, urlID int) *ExtendedAttrs

NewExtendedAttrs creates an ExtendedAttrs with the given raw ext value and URL ID.

func (*ExtendedAttrs) Clone

func (e *ExtendedAttrs) Clone() *ExtendedAttrs

Clone returns a copy.

func (*ExtendedAttrs) Ext

func (e *ExtendedAttrs) Ext() uint32

Ext returns the raw extended attributes value. If a URL is set, the underline style bits are overridden to DASHED.

func (*ExtendedAttrs) IsEmpty

func (e *ExtendedAttrs) IsEmpty() bool

IsEmpty returns true if the extended attrs carry no meaningful data.

func (*ExtendedAttrs) SetExt

func (e *ExtendedAttrs) SetExt(v uint32)

SetExt sets the raw extended attributes value.

func (*ExtendedAttrs) SetURLID

func (e *ExtendedAttrs) SetURLID(v int)

SetURLID sets the OSC hyperlink ID.

func (*ExtendedAttrs) SetUnderlineColor

func (e *ExtendedAttrs) SetUnderlineColor(v uint32)

SetUnderlineColor sets the underline color bits.

func (*ExtendedAttrs) SetUnderlineStyle

func (e *ExtendedAttrs) SetUnderlineStyle(v UnderlineStyle)

SetUnderlineStyle sets the underline style bits.

func (*ExtendedAttrs) SetUnderlineVariantOffset

func (e *ExtendedAttrs) SetUnderlineVariantOffset(v int)

SetUnderlineVariantOffset sets the variant offset bits.

func (*ExtendedAttrs) URLID

func (e *ExtendedAttrs) URLID() int

URLID returns the OSC hyperlink ID.

func (*ExtendedAttrs) UnderlineColor

func (e *ExtendedAttrs) UnderlineColor() uint32

UnderlineColor returns the underline color (color mode + RGB/palette bits).

func (*ExtendedAttrs) UnderlineStyle

func (e *ExtendedAttrs) UnderlineStyle() UnderlineStyle

UnderlineStyle returns the underline style. Returns DASHED if a URL is active.

func (*ExtendedAttrs) UnderlineVariantOffset

func (e *ExtendedAttrs) UnderlineVariantOffset() int

UnderlineVariantOffset returns the variant offset (3-bit unsigned from bits 29-31).

type FontWeight

type FontWeight string

FontWeight represents CSS font-weight values.

const (
	FontWeightNormal FontWeight = "normal"
	FontWeightBold   FontWeight = "bold"
	FontWeight100    FontWeight = "100"
	FontWeight200    FontWeight = "200"
	FontWeight300    FontWeight = "300"
	FontWeight400    FontWeight = "400"
	FontWeight500    FontWeight = "500"
	FontWeight600    FontWeight = "600"
	FontWeight700    FontWeight = "700"
	FontWeight800    FontWeight = "800"
	FontWeight900    FontWeight = "900"
)

type FunctionIdentifier

type FunctionIdentifier struct {
	Prefix        byte // 0 for none, or '<', '=', '>', '?'
	Intermediates string
	Final         byte
}

FunctionIdentifier identifies a parser function by its prefix, intermediates, and final character.

type InputHandler

type InputHandler struct {

	// Events
	OnCursorMoveEmitter                  EventEmitter[struct{}]
	OnTitleChangeEmitter                 EventEmitter[string]
	OnIconNameChangeEmitter              EventEmitter[string]
	OnLineFeedEmitter                    EventEmitter[struct{}]
	OnA11yCharEmitter                    EventEmitter[string]
	OnA11yTabEmitter                     EventEmitter[int]
	OnRequestBellEmitter                 EventEmitter[struct{}]
	OnRequestResetEmitter                EventEmitter[struct{}]
	OnRequestRefreshRowsEmitter          EventEmitter[RowRange]
	OnColorEmitter                       EventEmitter[[]ColorEvent]
	OnRequestSendFocusEmitter            EventEmitter[struct{}]
	OnRequestSyncScrollBarEmitter        EventEmitter[struct{}]
	OnRequestColorSchemeQueryEmitter     EventEmitter[struct{}]
	OnRequestWindowsOptionsReportEmitter EventEmitter[WindowsOptionsReportType]
	// contains filtered or unexported fields
}

InputHandler wires the EscapeSequenceParser to the terminal buffer.

func NewInputHandler

func NewInputHandler(
	bufferService *BufferService,
	charsetService *CharsetService,
	coreService *CoreService,
	optionsService *OptionsService,
	oscLinkService *OscLinkService,
	unicodeService *UnicodeService,
) *InputHandler

NewInputHandler creates an InputHandler and registers all parser handlers.

func (*InputHandler) Backspace

func (h *InputHandler) Backspace()

Backspace (BS, 0x08) — move cursor one position left. With reverse wraparound enabled, can undo soft line wraps.

func (*InputHandler) Bell

func (h *InputHandler) Bell()

Bell (BEL, 0x07) — ring the bell.

func (*InputHandler) CarriageReturn

func (h *InputHandler) CarriageReturn()

CarriageReturn (CR, 0x0D) — move cursor to column 0.

func (*InputHandler) Dispose

func (h *InputHandler) Dispose()

Dispose cleans up all event emitters.

func (*InputHandler) FullReset

func (h *InputHandler) FullReset() bool

FullReset (ESC c / RIS) — complete terminal reset.

func (*InputHandler) Index

func (h *InputHandler) Index() bool

Index (ESC D / IND) — move cursor down one line, scroll if at bottom of scroll region.

func (*InputHandler) KeypadApplicationMode

func (h *InputHandler) KeypadApplicationMode() bool

KeypadApplicationMode (ESC =) — enable application keypad mode.

func (*InputHandler) KeypadNumericMode

func (h *InputHandler) KeypadNumericMode() bool

KeypadNumericMode (ESC >) — enable numeric keypad mode.

func (*InputHandler) LineFeed

func (h *InputHandler) LineFeed()

LineFeed (LF, 0x0A / VT, 0x0B / FF, 0x0C) — move cursor down one row, scrolling if needed.

func (*InputHandler) NextLine

func (h *InputHandler) NextLine() bool

NextLine (ESC E / NEL) — CR + LF.

func (*InputHandler) Parse

func (h *InputHandler) Parse(data []byte)

Parse decodes input data and feeds it to the parser.

func (*InputHandler) ParseString

func (h *InputHandler) ParseString(data string)

ParseString is a convenience method that accepts a string.

func (*InputHandler) Parser

func (h *InputHandler) Parser() *EscapeSequenceParser

Parser returns the underlying escape sequence parser.

func (*InputHandler) Print

func (h *InputHandler) Print(data []uint32, start, end int)

Print handles printable characters — writes them to the buffer.

func (*InputHandler) Reset

func (h *InputHandler) Reset()

Reset resets the input handler state.

func (*InputHandler) RestoreBgColor

func (h *InputHandler) RestoreBgColor(_ string) bool

RestoreBgColor (OSC 111) — restore default background color.

func (*InputHandler) RestoreCursor

func (h *InputHandler) RestoreCursor() bool

RestoreCursor (ESC 8 / DECRC) — restore saved cursor state.

func (*InputHandler) RestoreCursorColor

func (h *InputHandler) RestoreCursorColor(_ string) bool

RestoreCursorColor (OSC 112) — restore default cursor color.

func (*InputHandler) RestoreFgColor

func (h *InputHandler) RestoreFgColor(_ string) bool

RestoreFgColor (OSC 110) — restore default foreground color.

func (*InputHandler) RestoreIndexedColor

func (h *InputHandler) RestoreIndexedColor(data string) bool

RestoreIndexedColor (OSC 104) — restore palette colors to theme defaults.

func (*InputHandler) ReverseIndex

func (h *InputHandler) ReverseIndex() bool

ReverseIndex (ESC M / RI) — move cursor up one line, scroll down if at top of scroll region.

func (*InputHandler) SaveCursor

func (h *InputHandler) SaveCursor() bool

SaveCursor (ESC 7 / DECSC) — save cursor position, attributes, charset state.

func (*InputHandler) ScreenAlignmentPattern

func (h *InputHandler) ScreenAlignmentPattern() bool

ScreenAlignmentPattern (ESC # 8 / DECALN) — fill screen with 'E'.

func (*InputHandler) SelectCharset

func (h *InputHandler) SelectCharset(collectAndFlag string) bool

SelectCharset designates a charset to a G-set (ESC ( ) * + - . / <flag>).

func (*InputHandler) SelectDefaultCharset

func (h *InputHandler) SelectDefaultCharset() bool

SelectDefaultCharset (ESC % @ / ESC % G) — select default (US ASCII) charset.

func (h *InputHandler) SetHyperlink(data string) bool

SetHyperlink (OSC 8) — create or finish a hyperlink.

func (*InputHandler) SetOrReportBgColor

func (h *InputHandler) SetOrReportBgColor(data string) bool

SetOrReportBgColor (OSC 11) — set or query default background color.

func (*InputHandler) SetOrReportCursorColor

func (h *InputHandler) SetOrReportCursorColor(data string) bool

SetOrReportCursorColor (OSC 12) — set or query default cursor color.

func (*InputHandler) SetOrReportFgColor

func (h *InputHandler) SetOrReportFgColor(data string) bool

SetOrReportFgColor (OSC 10) — set or query default foreground color.

func (*InputHandler) SetOrReportIndexedColor

func (h *InputHandler) SetOrReportIndexedColor(data string) bool

SetOrReportIndexedColor (OSC 4) — set or query palette colors.

func (*InputHandler) SetTitle

func (h *InputHandler) SetTitle(data string) bool

SetTitle (OSC 2) — set the terminal window title.

func (*InputHandler) SetgLevel

func (h *InputHandler) SetgLevel(level int) bool

SetgLevel sets the active GL level (ESC n/o/|/}/~).

func (*InputHandler) ShiftIn

func (h *InputHandler) ShiftIn()

ShiftIn (SI, 0x0F) — switch to G0 character set.

func (*InputHandler) ShiftOut

func (h *InputHandler) ShiftOut()

ShiftOut (SO, 0x0E) — switch to G1 character set.

func (*InputHandler) Tab

func (h *InputHandler) Tab()

Tab (HT, 0x09) — move cursor to next tab stop.

func (*InputHandler) TabSet

func (h *InputHandler) TabSet() bool

TabSet (ESC H / HTS) — set a tab stop at the current cursor column.

type InsertEvent

type InsertEvent struct {
	Index  int
	Amount int
}

InsertEvent is fired when items are inserted into a CircularList.

type KittyKeyboardState

type KittyKeyboardState struct {
	Flags     int
	MainFlags int
	AltFlags  int
	MainStack []int
	AltStack  []int
}

KittyKeyboardState tracks the kitty keyboard protocol state.

type LogLevel

type LogLevel string

LogLevel controls terminal logging verbosity.

const (
	LogLevelTrace   LogLevel = "trace"
	LogLevelDebug   LogLevel = "debug"
	LogLevelInfo    LogLevel = "info"
	LogLevelWarning LogLevel = "warning"
	LogLevelError   LogLevel = "error"
	LogLevelOff     LogLevel = "off"
)

type Marker

type Marker struct {
	Line       int
	IsDisposed bool
	// contains filtered or unexported fields
}

Marker represents a line position in the buffer that is tracked across scrollback trimming, insertions, and deletions.

func NewMarker

func NewMarker(line int) *Marker

NewMarker creates a marker at the given line.

func (*Marker) Dispose

func (m *Marker) Dispose()

Dispose disposes the marker, firing OnDispose and cleaning up all registered disposables.

func (*Marker) ID

func (m *Marker) ID() int64

ID returns the unique marker identifier.

func (*Marker) OnDispose

func (m *Marker) OnDispose(listener func(struct{})) Disposable

OnDispose registers a listener called when the marker is disposed.

func (*Marker) Register

func (m *Marker) Register(d Disposable) Disposable

Register adds a disposable to be cleaned up when the marker is disposed. Returns the disposable for chaining.

type Modes

type Modes struct {
	InsertMode bool
}

Modes tracks standard ANSI modes.

type MouseStateService

type MouseStateService struct {
	OnProtocolChangeEmitter EventEmitter[CoreMouseEventType]
	// contains filtered or unexported fields
}

MouseStateService manages mouse tracking protocols and encodings.

func NewMouseStateService

func NewMouseStateService() *MouseStateService

NewMouseStateService creates a MouseStateService with default protocols and encodings.

func (*MouseStateService) ActiveEncoding

func (m *MouseStateService) ActiveEncoding() string

ActiveEncoding returns the name of the active mouse encoding.

func (*MouseStateService) ActiveProtocol

func (m *MouseStateService) ActiveProtocol() string

ActiveProtocol returns the name of the active mouse tracking protocol.

func (*MouseStateService) AreMouseEventsActive

func (m *MouseStateService) AreMouseEventsActive() bool

AreMouseEventsActive returns true if the active protocol accepts any events.

func (*MouseStateService) Dispose

func (m *MouseStateService) Dispose()

Dispose cleans up event emitters.

func (*MouseStateService) Reset

func (m *MouseStateService) Reset()

Reset restores the default protocol (NONE) and encoding (DEFAULT).

func (*MouseStateService) SetActiveEncoding

func (m *MouseStateService) SetActiveEncoding(name string)

SetActiveEncoding sets the active mouse encoding by name.

func (*MouseStateService) SetActiveProtocol

func (m *MouseStateService) SetActiveProtocol(name string)

SetActiveProtocol sets the active mouse tracking protocol by name.

func (*MouseStateService) TriggerMouseEvent

func (m *MouseStateService) TriggerMouseEvent(e CoreMouseEvent) (string, bool)

TriggerMouseEvent applies the active protocol's filter and encoding to the event. Returns the encoded escape sequence and true if the event was accepted, or ("", false) if the protocol rejected it.

type MutableDisposable

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

MutableDisposable holds a single disposable value that can be replaced. Setting a new value disposes the previous one.

func (*MutableDisposable) Clear

func (m *MutableDisposable) Clear()

Clear disposes and removes the current value.

func (*MutableDisposable) Dispose

func (m *MutableDisposable) Dispose()

Dispose disposes the current value and marks the holder as disposed.

func (*MutableDisposable) SetValue

func (m *MutableDisposable) SetValue(d Disposable)

SetValue replaces the current disposable, disposing the old one.

func (*MutableDisposable) Value

func (m *MutableDisposable) Value() Disposable

Value returns the current disposable, or nil if disposed.

type NewLayoutResult

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

NewLayoutResult holds the result of reflowLargerCreateNewLayout.

type Option

type Option func(*TerminalOptions)

Option configures a Terminal.

func WithCols

func WithCols(cols int) Option

WithCols sets the number of columns.

func WithMouseEventsRequireAlt

func WithMouseEventsRequireAlt(on bool) Option

WithMouseEventsRequireAlt requires Alt for mouse event reporting.

func WithRows

func WithRows(rows int) Option

WithRows sets the number of rows.

func WithScreenReaderMode

func WithScreenReaderMode(on bool) Option

WithScreenReaderMode enables screen reader / accessibility mode.

func WithScrollback

func WithScrollback(n int) Option

WithScrollback sets the scrollback buffer size.

func WithVtExtensions

func WithVtExtensions(ext VtExtensions) Option

WithVtExtensions configures non-standard VT extensions.

func WithWindowOptions

func WithWindowOptions(wo WindowOptions) Option

WithWindowOptions configures which CSI t sub-commands are permitted.

func WithWindowsPty

func WithWindowsPty(wp WindowsPty) Option

WithWindowsPty configures Windows pseudo-terminal compatibility behavior.

type OptionsService

type OptionsService struct {
	Options TerminalOptions

	OnOptionChangeEmitter EventEmitter[string]
}

OptionsService wraps TerminalOptions with change notification.

func NewOptionsService

func NewOptionsService(opts *TerminalOptions) *OptionsService

NewOptionsService creates an OptionsService with defaults merged with the given overrides.

func (*OptionsService) Dispose

func (s *OptionsService) Dispose()

Dispose cleans up the options service.

func (*OptionsService) OnMultipleOptionChange

func (s *OptionsService) OnMultipleOptionChange(keys []string, listener func()) Disposable

OnMultipleOptionChange registers a listener that fires when any of the given options change.

func (*OptionsService) OnSpecificOptionChange

func (s *OptionsService) OnSpecificOptionChange(key string, listener func()) Disposable

OnSpecificOptionChange registers a listener for changes to a specific option.

func (*OptionsService) SetOption

func (s *OptionsService) SetOption(name string, value interface{})

SetOption sets a named option and fires the change event if the value changed.

type OscFallbackHandler

type OscFallbackHandler func(ident int, action string, payload ...interface{})

OscFallbackHandler is called when no registered handler matches the OSC identifier.

type OscHandler

type OscHandler interface {
	Start()
	Put(data []uint32, start, end int)
	End(success bool) bool
}

OscHandler is the interface for handlers that process OSC sequences. Intentionally separate from ApcHandler to mirror xterm.js type structure.

type OscLinkData

type OscLinkData struct {
	URI string
	ID  string // optional; links with the same ID+URI share an entry
}

OscLinkData holds the data for an OSC hyperlink.

type OscLinkService

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

OscLinkService tracks active hyperlinks in the terminal buffer.

func NewOscLinkService

func NewOscLinkService(bs *BufferService) *OscLinkService

NewOscLinkService creates an OscLinkService backed by the given BufferService.

func (s *OscLinkService) AddLineToLink(linkID, y int)

AddLineToLink adds a line reference to an existing link.

func (*OscLinkService) GetLinkData

func (s *OscLinkService) GetLinkData(linkID int) *OscLinkData

GetLinkData returns the link data for a given link ID, or nil if not found.

func (s *OscLinkService) RegisterLink(data OscLinkData) int

RegisterLink registers a hyperlink and returns its numeric link ID. Links without an ID are always created as new entries. Links with an ID reuse an existing entry if the key matches.

type OscParser

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

OscParser parses OSC sequences and dispatches to registered handlers.

func NewOscParser

func NewOscParser() *OscParser

NewOscParser creates a new OscParser.

func (*OscParser) ClearHandler

func (p *OscParser) ClearHandler(ident int)

ClearHandler removes all handlers for the given identifier.

func (*OscParser) Dispose

func (p *OscParser) Dispose()

Dispose removes all handlers and resets state.

func (*OscParser) End

func (p *OscParser) End(success bool)

End signals the end of an OSC sequence. success indicates whether the sequence terminated normally (ST/BEL) or was aborted.

func (*OscParser) Put

func (p *OscParser) Put(data []uint32, start, end int)

Put feeds data to the current OSC command. Parses the numeric identifier from the leading digits, then passes payload to handlers.

func (*OscParser) RegisterHandler

func (p *OscParser) RegisterHandler(ident int, handler OscHandler) Disposable

RegisterHandler registers a handler for the given OSC identifier. Returns a Disposable that removes the handler when disposed.

func (*OscParser) Reset

func (p *OscParser) Reset()

Reset forces cleanup of active handlers and resets parser state.

func (*OscParser) SetHandlerFallback

func (p *OscParser) SetHandlerFallback(handler OscFallbackHandler)

SetHandlerFallback sets the fallback handler called when no handler matches.

func (*OscParser) Start

func (p *OscParser) Start()

Start begins a new OSC sequence, resetting any leftover state.

type OscState

type OscState uint8

OscState enumerates the internal states of the OSC parser.

const (
	OscStateStart   OscState = 0
	OscStateID      OscState = 1
	OscStatePayload OscState = 2
	OscStateAbort   OscState = 3
)

type OscStringHandler

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

OscStringHandler is a convenience wrapper that collects OSC payload as a string and calls a callback function on End.

func NewOscStringHandler

func NewOscStringHandler(handler func(data string) bool) *OscStringHandler

NewOscStringHandler creates an OscStringHandler from a callback.

func (*OscStringHandler) End

func (h *OscStringHandler) End(success bool) bool

End calls the handler callback if the sequence ended successfully.

func (*OscStringHandler) Put

func (h *OscStringHandler) Put(data []uint32, start, end int)

Put appends payload data as a string.

func (*OscStringHandler) Start

func (h *OscStringHandler) Start()

Start resets the string accumulator.

type Params

type Params struct {
	// Params is the main parameter array. Only indices [0, Length) are valid.
	Params    []int32
	Length    int
	MaxLength int
	// contains filtered or unexported fields
}

Params stores CSI/DCS sequence parameters and their sub-parameters.

func DefaultParams

func DefaultParams() *Params

DefaultParams creates a Params with default limits (32 params, 32 sub-params).

func NewParams

func NewParams(maxLength, maxSubParamsLength int) *Params

NewParams creates a Params with the given capacity limits.

func ParamsFromArray

func ParamsFromArray(values []interface{}) *Params

ParamsFromArray creates a Params from a mixed array representation. Elements can be int32 (params) or []int32 (sub-params for the preceding param). Leading sub-param arrays (before any int32) are skipped.

func (*Params) AddDigit

func (p *Params) AddDigit(value int32)

AddDigit adds a single digit to the current parameter or sub-parameter. Used by the parser to accumulate digits character by character.

func (*Params) AddParam

func (p *Params) AddParam(value int32)

AddParam appends a parameter value. Values < -1 panic. Values beyond maxLength are silently ignored. Values exceeding maxParamValue are clamped.

func (*Params) AddSubParam

func (p *Params) AddSubParam(value int32)

AddSubParam appends a sub-parameter associated with the last parameter. Ignored if no parameter has been added yet or limits are exceeded.

func (*Params) Clone

func (p *Params) Clone() *Params

Clone returns a deep copy of the Params.

func (*Params) GetSubParams

func (p *Params) GetSubParams(idx int) []int32

GetSubParams returns the sub-parameters for the parameter at idx. Returns nil if there are no sub-parameters. The returned slice is borrowed.

func (*Params) GetSubParamsAll

func (p *Params) GetSubParamsAll() map[int][]int32

GetSubParamsAll returns a map of param index to cloned sub-parameter slices.

func (*Params) HasSubParams

func (p *Params) HasSubParams(idx int) bool

HasSubParams returns whether the parameter at idx has sub-parameters.

func (*Params) Reset

func (p *Params) Reset()

Reset clears all parameters to the initial empty state.

func (*Params) ResetZdm

func (p *Params) ResetZdm()

ResetZdm resets the params and seeds a single zero-default param (ZDM). Equivalent to Reset() followed by AddParam(0); kept as a single call to mirror the upstream xterm.js Params.resetZdm helper.

func (*Params) ToArray

func (p *Params) ToArray() []interface{}

ToArray returns a mixed representation: each param as int32, followed by its sub-params as []int32 (if any).

type ParserAction

type ParserAction uint8

ParserAction enumerates the internal actions of the escape sequence parser.

const (
	ParserActionIgnore      ParserAction = 0
	ParserActionError       ParserAction = 1
	ParserActionPrint       ParserAction = 2
	ParserActionExecute     ParserAction = 3
	ParserActionOSCStart    ParserAction = 4
	ParserActionOSCPut      ParserAction = 5
	ParserActionOSCEnd      ParserAction = 6
	ParserActionCSIDispatch ParserAction = 7
	ParserActionParam       ParserAction = 8
	ParserActionCollect     ParserAction = 9
	ParserActionESCDispatch ParserAction = 10
	ParserActionClear       ParserAction = 11
	ParserActionDCSHook     ParserAction = 12
	ParserActionDCSPut      ParserAction = 13
	ParserActionDCSUnhook   ParserAction = 14
	ParserActionAPCStart    ParserAction = 15
	ParserActionAPCPut      ParserAction = 16
	ParserActionAPCEnd      ParserAction = 17
)

type ParserState

type ParserState uint8

ParserState enumerates the internal states of the VT500 escape sequence parser.

const (
	ParserStateGround             ParserState = 0
	ParserStateEscape             ParserState = 1
	ParserStateEscapeIntermediate ParserState = 2
	ParserStateCSIEntry           ParserState = 3
	ParserStateCSIParam           ParserState = 4
	ParserStateCSIIntermediate    ParserState = 5
	ParserStateCSIIgnore          ParserState = 6
	ParserStateSOSPMString        ParserState = 7
	ParserStateOSCString          ParserState = 8
	ParserStateDCSEntry           ParserState = 9
	ParserStateDCSParam           ParserState = 10
	ParserStateDCSIgnore          ParserState = 11
	ParserStateDCSIntermediate    ParserState = 12
	ParserStateDCSPassthrough     ParserState = 13
	ParserStateAPCEntry           ParserState = 14
	ParserStateAPCIntermediate    ParserState = 15
	ParserStateAPCPassthrough     ParserState = 16
	ParserStateLength             ParserState = 17 // number of states
)

type ParsingState

type ParsingState struct {
	Position     int
	Code         uint32
	CurrentState ParserState
	Collect      int
	Params       *Params
	Abort        bool
}

ParsingState describes the parser state at the point of an error.

type PrintFallbackHandler

type PrintFallbackHandler = PrintHandler

PrintFallbackHandler is called when no print handler is set. Same signature as PrintHandler.

type PrintHandler

type PrintHandler func(data []uint32, start, end int)

PrintHandler handles printable character ranges.

type RowRange

type RowRange struct {
	Start int
	End   int
}

RowRange represents a range of rows [Start, End).

type SavedCursorState

type SavedCursorState struct {
	X              int
	Y              int
	CurAttrData    AttributeData
	Charset        Charset
	Charsets       []Charset
	GLevel         int
	OriginMode     bool
	WraparoundMode bool
}

SavedCursorState holds cursor state saved by DECSC.

type ScrollEvent

type ScrollEvent struct {
	Position int
}

ScrollEvent carries a scroll position.

type ScrollbarOptions

type ScrollbarOptions struct {
	ShowScrollbar bool `json:"showScrollbar"`
}

ScrollbarOptions configures the scrollbar.

type SerializeAddon

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

SerializeAddon serializes terminal buffer state as escape sequences.

func NewSerializeAddon

func NewSerializeAddon(t *Terminal) *SerializeAddon

NewSerializeAddon creates a new SerializeAddon attached to the given terminal.

func (*SerializeAddon) Serialize

func (sa *SerializeAddon) Serialize(opts *SerializeOptions) []byte

Serialize returns the terminal buffer content as escape sequences.

type SerializeOptions

type SerializeOptions struct {
	// Scrollback limits how many scrollback lines to include.
	// If nil, all scrollback is included.
	Scrollback *int

	// Range serializes only the specified line range instead of the full buffer.
	Range *SerializeRange

	// ExcludeAltBuffer skips alternate buffer serialization.
	ExcludeAltBuffer bool

	// ExcludeModes skips mode and scroll region serialization.
	ExcludeModes bool
}

SerializeOptions controls what gets serialized.

type SerializeRange

type SerializeRange struct {
	Start int
	End   int
}

SerializeRange specifies a row range for serialization.

type SpecialColorIndex

type SpecialColorIndex int

SpecialColorIndex identifies special color slots beyond the 256-color palette.

const (
	SpecialColorForeground SpecialColorIndex = 256
	SpecialColorBackground SpecialColorIndex = 257
	SpecialColorCursor     SpecialColorIndex = 258
)

type Terminal

type Terminal struct {

	// Public event emitters (forwarded from sub-components).
	OnBellEmitter                        EventEmitter[struct{}]
	OnTitleChangeEmitter                 EventEmitter[string]
	OnIconNameChangeEmitter              EventEmitter[string]
	OnLineFeedEmitter                    EventEmitter[struct{}]
	OnCursorMoveEmitter                  EventEmitter[struct{}]
	OnResizeEmitter                      EventEmitter[BufferResizeEvent]
	OnScrollEmitter                      EventEmitter[int]
	OnRenderEmitter                      EventEmitter[RowRange]
	OnWriteParsedEmitter                 EventEmitter[struct{}]
	OnRequestSendFocusEmitter            EventEmitter[struct{}]
	OnRequestColorSchemeQueryEmitter     EventEmitter[struct{}]
	OnRequestWindowsOptionsReportEmitter EventEmitter[WindowsOptionsReportType]
	// contains filtered or unexported fields
}

Terminal is a headless terminal emulator.

func New

func New(opts ...Option) *Terminal

New creates a new Terminal with the given options.

func (*Terminal) AddMarker

func (t *Terminal) AddMarker(cursorYOffset int) *Marker

AddMarker creates a marker at the cursor position plus the given offset.

func (*Terminal) AltBuffer

func (t *Terminal) AltBuffer() *Buffer

AltBuffer returns the alternate buffer.

func (*Terminal) Buffer

func (t *Terminal) Buffer() *Buffer

Buffer returns the active buffer (for advanced access).

func (*Terminal) Clear

func (t *Terminal) Clear()

Clear clears the viewport and scrollback buffer, preserving the line the cursor is on. Ported from xterm.js src/headless/Terminal.ts clear().

func (*Terminal) Cols

func (t *Terminal) Cols() int

Cols returns the number of columns.

func (*Terminal) CurAttrData

func (t *Terminal) CurAttrData() AttributeData

CurAttrData returns the current cursor attribute data from the input handler.

func (*Terminal) CursorX

func (t *Terminal) CursorX() int

CursorX returns the cursor column (0-based).

func (*Terminal) CursorY

func (t *Terminal) CursorY() int

CursorY returns the cursor row (0-based, relative to viewport).

func (*Terminal) DecPrivateModes

func (t *Terminal) DecPrivateModes() DecPrivateModes

DecPrivateModes returns the current DEC private modes.

func (*Terminal) Dispose

func (t *Terminal) Dispose()

Dispose cleans up all resources.

func (*Terminal) GetLine

func (t *Terminal) GetLine(y int) string

GetLine returns the content of a viewport line as a string. Returns "" if y is out of range.

func (*Terminal) IconName

func (t *Terminal) IconName() string

IconName returns the current icon name set via OSC 1 or OSC 0.

func (*Terminal) IsAltBufferActive

func (t *Terminal) IsAltBufferActive() bool

IsAltBufferActive returns true if the alternate buffer is active.

func (*Terminal) IsCursorHidden

func (t *Terminal) IsCursorHidden() bool

IsCursorHidden returns whether the cursor is hidden (DECTCEM).

func (*Terminal) Modes

func (t *Terminal) Modes() Modes

Modes returns the current ANSI modes.

func (*Terminal) NormalBuffer

func (t *Terminal) NormalBuffer() *Buffer

NormalBuffer returns the normal (primary) buffer.

func (*Terminal) OnA11yChar

func (t *Terminal) OnA11yChar(fn func(string)) Disposable

OnA11yChar subscribes to accessibility character announcements.

func (*Terminal) OnA11yTab

func (t *Terminal) OnA11yTab(fn func(int)) Disposable

OnA11yTab subscribes to accessibility tab movement announcements.

func (*Terminal) OnBell

func (t *Terminal) OnBell(fn func()) Disposable

OnBell registers a callback for bell events.

func (*Terminal) OnBinary

func (t *Terminal) OnBinary(fn func(string)) Disposable

OnBinary subscribes to binary data events from the terminal.

func (*Terminal) OnColor

func (t *Terminal) OnColor(fn func([]ColorEvent)) Disposable

OnColor subscribes to color palette query/set/restore events (OSC 4/10/11/12).

func (*Terminal) OnCursorMove

func (t *Terminal) OnCursorMove(fn func()) Disposable

OnCursorMove registers a callback for cursor move events.

func (*Terminal) OnData

func (t *Terminal) OnData(fn func(string)) Disposable

OnData registers a callback for data sent from the terminal (e.g. DA responses).

func (*Terminal) OnIconNameChange

func (t *Terminal) OnIconNameChange(fn func(string)) Disposable

OnIconNameChange registers a callback for icon name change events.

func (*Terminal) OnLineFeed

func (t *Terminal) OnLineFeed(fn func()) Disposable

OnLineFeed registers a callback for line feed events.

func (*Terminal) OnRender

func (t *Terminal) OnRender(fn func(RowRange)) Disposable

OnRender registers a callback fired when terminal rows are dirty.

func (*Terminal) OnRequestColorSchemeQuery

func (t *Terminal) OnRequestColorSchemeQuery(fn func()) Disposable

OnRequestColorSchemeQuery subscribes to DSR 996 color scheme query events. Fired when the client sends CSI ? 996 n while color scheme updates (DECSET 2031) are enabled.

func (*Terminal) OnRequestSendFocus

func (t *Terminal) OnRequestSendFocus(fn func()) Disposable

OnRequestSendFocus subscribes to focus-reporting enable events (DECSET 1004). Fired when the application enables focus tracking so the host can immediately report the current focus state.

func (*Terminal) OnRequestWindowsOptionsReport

func (t *Terminal) OnRequestWindowsOptionsReport(fn func(WindowsOptionsReportType)) Disposable

OnRequestWindowsOptionsReport subscribes to window-options report requests (CSI 14 t, CSI 16 t).

func (*Terminal) OnResize

func (t *Terminal) OnResize(fn func(BufferResizeEvent)) Disposable

OnResize registers a callback for terminal resize events.

func (*Terminal) OnScroll

func (t *Terminal) OnScroll(fn func(int)) Disposable

OnScroll registers a callback for scroll events.

func (*Terminal) OnTitleChange

func (t *Terminal) OnTitleChange(fn func(string)) Disposable

OnTitleChange registers a callback for title change events.

func (*Terminal) OnWriteParsed

func (t *Terminal) OnWriteParsed(fn func()) Disposable

OnWriteParsed subscribes to write-parsed events. Fires after each Write/WriteString call completes parsing.

func (*Terminal) RegisterApcHandler

func (t *Terminal) RegisterApcHandler(id FunctionIdentifier, handler func(data string) bool) Disposable

RegisterApcHandler registers a handler for APC escape sequences. id identifies the APC function by its final character (e.g., Final: 'G' for Kitty graphics).

func (*Terminal) RegisterCsiHandler

func (t *Terminal) RegisterCsiHandler(id FunctionIdentifier, handler CsiHandler) Disposable

RegisterCsiHandler registers a custom handler for a CSI escape sequence. The handler returns true to stop the handler chain from bubbling further. For CSI t (window options), the handler is wrapped with a permission check against the terminal's WindowOptions configuration.

func (*Terminal) RegisterDcsHandler

func (t *Terminal) RegisterDcsHandler(id FunctionIdentifier, handler DcsHandler) Disposable

RegisterDcsHandler registers a custom handler for a DCS escape sequence.

func (*Terminal) RegisterEscHandler

func (t *Terminal) RegisterEscHandler(id FunctionIdentifier, handler EscHandler) Disposable

RegisterEscHandler registers a custom handler for an ESC escape sequence. The handler returns true to stop the handler chain from bubbling further.

func (*Terminal) RegisterMarker

func (t *Terminal) RegisterMarker(cursorYOffset int) *Marker

RegisterMarker creates a marker at the cursor position plus the given offset.

func (*Terminal) RegisterOscHandler

func (t *Terminal) RegisterOscHandler(ident int, handler OscHandler) Disposable

RegisterOscHandler registers a custom handler for an OSC escape sequence.

func (*Terminal) Reset

func (t *Terminal) Reset()

Reset performs a full terminal reset.

func (*Terminal) Resize

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

Resize changes the terminal dimensions.

func (*Terminal) Rows

func (t *Terminal) Rows() int

Rows returns the number of rows.

func (*Terminal) ScrollBottom

func (t *Terminal) ScrollBottom() int

ScrollBottom returns the bottom of the scroll region (0-based).

func (*Terminal) ScrollLines

func (t *Terminal) ScrollLines(disp int)

ScrollLines scrolls the viewport by disp lines (negative = up, positive = down).

func (*Terminal) ScrollPages

func (t *Terminal) ScrollPages(pageCount int)

ScrollPages scrolls the viewport by pageCount pages.

func (*Terminal) ScrollToBottom

func (t *Terminal) ScrollToBottom()

ScrollToBottom scrolls the viewport to the bottom (latest output).

func (*Terminal) ScrollToLine

func (t *Terminal) ScrollToLine(line int)

ScrollToLine scrolls the viewport so that the given line is at the top.

func (*Terminal) ScrollToTop

func (t *Terminal) ScrollToTop()

ScrollToTop scrolls the viewport to the top of the scrollback.

func (*Terminal) ScrollTop

func (t *Terminal) ScrollTop() int

ScrollTop returns the top of the scroll region (0-based).

func (*Terminal) Scrollback

func (t *Terminal) Scrollback() int

Scrollback returns the scrollback buffer size.

func (*Terminal) String

func (t *Terminal) String() string

String returns the entire visible viewport as a string. Trailing blank lines are trimmed. Each line has trailing whitespace trimmed.

func (*Terminal) TriggerMouseEvent

func (t *Terminal) TriggerMouseEvent(ev CoreMouseEvent) bool

TriggerMouseEvent dispatches a mouse event through the active tracking protocol and encoding. Returns true if the event was accepted and sent via the data event. The active protocol is determined by DecPrivateModes.MouseTrackingMode and the active encoding by DecPrivateModes.MouseEncoding.

func (*Terminal) Write

func (t *Terminal) Write(p []byte) (n int, err error)

Write writes data to the terminal, implementing io.Writer.

func (*Terminal) WriteString

func (t *Terminal) WriteString(s string)

WriteString writes a string to the terminal.

type TerminalOptions

type TerminalOptions struct {
	Cols                          int                 `json:"cols"`
	Rows                          int                 `json:"rows"`
	ShowCursorImmediately         bool                `json:"showCursorImmediately"`
	CursorBlink                   bool                `json:"cursorBlink"`
	BlinkIntervalDuration         int                 `json:"blinkIntervalDuration"`
	CursorStyle                   CursorStyle         `json:"cursorStyle"`
	CursorWidth                   int                 `json:"cursorWidth"`
	CursorInactiveStyle           CursorInactiveStyle `json:"cursorInactiveStyle"`
	DrawBoldTextInBrightColors    bool                `json:"drawBoldTextInBrightColors"`
	FastScrollSensitivity         float64             `json:"fastScrollSensitivity"`
	FontFamily                    string              `json:"fontFamily"`
	FontSize                      int                 `json:"fontSize"`
	FontWeight                    FontWeight          `json:"fontWeight"`
	FontWeightBold                FontWeight          `json:"fontWeightBold"`
	IgnoreBracketedPasteMode      bool                `json:"ignoreBracketedPasteMode"`
	LineHeight                    float64             `json:"lineHeight"`
	LetterSpacing                 float64             `json:"letterSpacing"`
	LogLevel                      LogLevel            `json:"logLevel"`
	Scrollback                    int                 `json:"scrollback"`
	Scrollbar                     ScrollbarOptions    `json:"scrollbar"`
	ScrollOnEraseInDisplay        bool                `json:"scrollOnEraseInDisplay"`
	ScrollOnUserInput             bool                `json:"scrollOnUserInput"`
	ScrollSensitivity             float64             `json:"scrollSensitivity"`
	ScreenReaderMode              bool                `json:"screenReaderMode"`
	SmoothScrollDuration          int                 `json:"smoothScrollDuration"`
	MacOptionIsMeta               bool                `json:"macOptionIsMeta"`
	MacOptionClickForcesSelection bool                `json:"macOptionClickForcesSelection"`
	MinimumContrastRatio          float64             `json:"minimumContrastRatio"`
	DisableStdin                  bool                `json:"disableStdin"`
	AllowProposedApi              bool                `json:"allowProposedApi"`
	AllowTransparency             bool                `json:"allowTransparency"`
	TabStopWidth                  int                 `json:"tabStopWidth"`
	ReflowCursorLine              bool                `json:"reflowCursorLine"`
	RescaleOverlappingGlyphs      bool                `json:"rescaleOverlappingGlyphs"`
	RightClickSelectsWord         bool                `json:"rightClickSelectsWord"`
	WordSeparator                 string              `json:"wordSeparator"`
	AltClickMovesCursor           bool                `json:"altClickMovesCursor"`
	MouseEventsRequireAlt         bool                `json:"mouseEventsRequireAlt"`
	ConvertEol                    bool                `json:"convertEol"`
	TermName                      string              `json:"termName"`
	WindowsPty                    WindowsPty          `json:"windowsPty"`
	WindowOptions                 WindowOptions       `json:"windowOptions"`
	VtExtensions                  VtExtensions        `json:"vtExtensions"`
}

TerminalOptions holds all terminal configuration fields.

func DefaultOptions

func DefaultOptions() TerminalOptions

DefaultOptions returns TerminalOptions with sensible defaults matching xterm.js.

type TransitionTable

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

TransitionTable maps (state, charCode) pairs to (action, nextState) transitions. Index: state << 8 | charCode. Value: action << 8 | nextState.

func NewTransitionTable

func NewTransitionTable(length int) *TransitionTable

NewTransitionTable creates a transition table with the given length.

func (*TransitionTable) Add

func (t *TransitionTable) Add(code int, state ParserState, action ParserAction, next ParserState)

Add sets the transition for a specific (code, state) pair.

func (*TransitionTable) AddMany

func (t *TransitionTable) AddMany(codes []int, state ParserState, action ParserAction, next ParserState)

AddMany sets the transition for multiple codes in a given state.

func (*TransitionTable) SetDefault

func (t *TransitionTable) SetDefault(action ParserAction, next ParserState)

SetDefault sets the default transition for all entries.

type UnderlineStyle

type UnderlineStyle uint32

UnderlineStyle values for extended attributes.

const (
	UnderlineStyleNone   UnderlineStyle = 0
	UnderlineStyleSingle UnderlineStyle = 1
	UnderlineStyleDouble UnderlineStyle = 2
	UnderlineStyleCurly  UnderlineStyle = 3
	UnderlineStyleDotted UnderlineStyle = 4
	UnderlineStyleDashed UnderlineStyle = 5
)

type UnicodeService

type UnicodeService struct{}

UnicodeService provides character width calculation for terminal rendering.

func NewUnicodeService

func NewUnicodeService() *UnicodeService

NewUnicodeService creates a UnicodeService.

func (*UnicodeService) CharProperties

func (u *UnicodeService) CharProperties(codepoint rune, preceding int) int

CharProperties determines character properties for terminal rendering, including whether a character should join with the preceding cell. Mirrors xterm.js UnicodeV6.charProperties().

func (*UnicodeService) GetStringCellWidth

func (u *UnicodeService) GetStringCellWidth(s string) int

GetStringCellWidth returns the total display width of a string.

func (*UnicodeService) Wcwidth

func (u *UnicodeService) Wcwidth(cp rune) int

Wcwidth returns the display width of a codepoint. Control chars and combining marks return 0, East Asian wide chars return 2, others return 1.

type Utf8ToUtf32

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

Utf8ToUtf32 is a streaming UTF-8 to UTF-32 decoder. It handles partial multi-byte sequences across chunk boundaries.

func (*Utf8ToUtf32) Clear

func (d *Utf8ToUtf32) Clear()

Clear resets the decoder state, discarding any partial sequence.

func (*Utf8ToUtf32) Decode

func (d *Utf8ToUtf32) Decode(input []byte, target []uint32) int

Decode decodes UTF-8 bytes from input into UTF-32 codepoints in target. Returns the number of codepoints written to target. Handles streaming: partial multi-byte sequences are buffered for the next call. Invalid sequences and surrogates are silently skipped. BOM (U+FEFF) is skipped.

type VtExtensions

type VtExtensions struct {
	KittyKeyboard            bool  `json:"kittyKeyboard"`
	ColorSchemeQuery         *bool `json:"colorSchemeQuery,omitempty"` // default true
	Win32InputMode           bool  `json:"win32InputMode"`
	KittySgrBoldFaintControl *bool `json:"kittySgrBoldFaintControl,omitempty"` // default true
}

VtExtensions gates non-standard terminal extensions. Mirrors upstream xterm.js vtExtensions option. Pointer fields default to true when nil.

type WindowOptions

type WindowOptions struct {
	RestoreWin          bool `json:"restoreWin,omitempty"`
	MinimizeWin         bool `json:"minimizeWin,omitempty"`
	SetWinPosition      bool `json:"setWinPosition,omitempty"`
	SetWinSizePixels    bool `json:"setWinSizePixels,omitempty"`
	RaiseWin            bool `json:"raiseWin,omitempty"`
	LowerWin            bool `json:"lowerWin,omitempty"`
	RefreshWin          bool `json:"refreshWin,omitempty"`
	SetWinSizeChars     bool `json:"setWinSizeChars,omitempty"`
	MaximizeWin         bool `json:"maximizeWin,omitempty"`
	FullscreenWin       bool `json:"fullscreenWin,omitempty"`
	GetWinState         bool `json:"getWinState,omitempty"`
	GetWinPosition      bool `json:"getWinPosition,omitempty"`
	GetWinSizePixels    bool `json:"getWinSizePixels,omitempty"`
	GetScreenSizePixels bool `json:"getScreenSizePixels,omitempty"`
	GetCellSizePixels   bool `json:"getCellSizePixels,omitempty"`
	GetWinSizeChars     bool `json:"getWinSizeChars,omitempty"`
	GetScreenSizeChars  bool `json:"getScreenSizeChars,omitempty"`
	GetIconTitle        bool `json:"getIconTitle,omitempty"`
	GetWinTitle         bool `json:"getWinTitle,omitempty"`
	PushTitle           bool `json:"pushTitle,omitempty"`
	PopTitle            bool `json:"popTitle,omitempty"`
	SetWinLines         bool `json:"setWinLines,omitempty"`
}

WindowOptions controls which CSI t (window manipulation) sub-commands are permitted. All fields default to false (denied). Mirrors upstream xterm.js IWindowOptions interface.

type WindowsOptionsReportType

type WindowsOptionsReportType int

WindowsOptionsReportType identifies a window-options report request (CSI t).

const (
	// GetWinSizePixels requests the window size in pixels (CSI 14 t).
	GetWinSizePixels WindowsOptionsReportType = 0
	// GetCellSizePixels requests the cell size in pixels (CSI 16 t).
	GetCellSizePixels WindowsOptionsReportType = 1
)

type WindowsPty

type WindowsPty struct {
	Backend string `json:"backend,omitempty"`
	BuildNo int    `json:"buildNumber,omitempty"`
}

WindowsPty holds Windows pseudo-terminal backend configuration.

Jump to

Keyboard shortcuts

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