vt

package
v0.0.0-...-8d2bbff Latest Latest
Warning

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

Go to latest
Published: Aug 23, 2026 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

Package vt implements the terminal emulation core of xterm.js 6.0.0 (https://github.com/xtermjs/xterm.js, MIT) as pure Go: the VT500 escape-sequence parser, the terminal buffer and the input handler. It has no browser dependencies and is fully testable with go test.

Index

Examples

Constants

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

	NullCellChar  = 0
	NullCellWidth = 1
	NullCellCode  = 0

	WhitespaceCellChar  = ' '
	WhitespaceCellWidth = 1
	WhitespaceCellCode  = 32
)

Buffer cell constants (port of buffer/Constants.ts).

View Source
const (
	ContentCodepointMask  uint32 = 0x1FFFFF
	ContentIsCombinedMask uint32 = 0x200000
	ContentHasContentMask uint32 = 0x3FFFFF
	ContentWidthMask      uint32 = 0xC00000
	ContentWidthShift            = 22
)

Content bit masks: bit 1..21 codepoint, bit 22 combined flag, bit 23..24 wcwidth.

View Source
const (
	AttrBlueMask   uint32 = 0xFF
	AttrBlueShift         = 0
	AttrPColorMask uint32 = 0xFF
	AttrGreenMask  uint32 = 0xFF00
	AttrGreenShift        = 8
	AttrRedMask    uint32 = 0xFF0000
	AttrRedShift          = 16

	// color mode: DEFAULT (0) | P16 (1) | P256 (2) | RGB (3)
	AttrCMMask    uint32 = 0x3000000
	AttrCMDefault uint32 = 0
	AttrCMP16     uint32 = 0x1000000
	AttrCMP256    uint32 = 0x2000000
	AttrCMRGB     uint32 = 0x3000000

	AttrRGBMask uint32 = 0xFFFFFF
)

Attribute color bits.

View Source
const (
	FgInverse       uint32 = 0x4000000
	FgBold          uint32 = 0x8000000
	FgUnderline     uint32 = 0x10000000
	FgBlink         uint32 = 0x20000000
	FgInvisible     uint32 = 0x40000000
	FgStrikethrough uint32 = 0x80000000
)

FG flag bits (bit 27..32).

View Source
const (
	BgItalic      uint32 = 0x4000000
	BgDim         uint32 = 0x8000000
	BgHasExtended uint32 = 0x10000000
	BgProtected   uint32 = 0x20000000
	BgOverline    uint32 = 0x40000000
)

BG flag bits (bit 27..32, upper 2 unused).

View Source
const (
	ExtUnderlineStyle uint32 = 0x1C000000
	ExtVariantOffset  uint32 = 0xE0000000
)

Extended attribute bits.

View Source
const (
	UnderlineNone   = 0
	UnderlineSingle = 1
	UnderlineDouble = 2
	UnderlineCurly  = 3
	UnderlineDotted = 4
	UnderlineDashed = 5
)

Underline styles.

View Source
const (
	ReportWinSizePixels  = 0
	ReportCellSizePixels = 1
)

Window options report types (WindowsOptionsReportType).

View Source
const (
	SpecialColorForeground = 256
	SpecialColorBackground = 257
	SpecialColorCursor     = 258
)

Special color indexes for OSC 10/11/12 events.

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

Mouse event types (CoreMouseEventType bit flags).

View Source
const (
	MouseButtonLeft   = 0
	MouseButtonMiddle = 1
	MouseButtonRight  = 2
	MouseButtonNone   = 3
	MouseButtonWheel  = 4
	// additional buttons 8..11 are unsupported by the encodings
	MouseButtonAux1 = 8
)

Mouse buttons (CoreMouseButton).

View Source
const (
	MouseActionUp    = 0 // NOTE: this matches wheel up
	MouseActionDown  = 1 // NOTE: this matches wheel down
	MouseActionLeft  = 2
	MouseActionRight = 3
	MouseActionMove  = 32
)

Mouse actions (CoreMouseAction).

View Source
const (
	MinimumCols = 2
	MinimumRows = 1
)

Minimum dimensions (less than 2 cols can mess with wide chars).

Variables

View Source
var Charsets = map[byte]Charset{

	'0': {
		'`': '◆',
		'a': '▒',
		'b': '␉',
		'c': '␌',
		'd': '␍',
		'e': '␊',
		'f': '°',
		'g': '±',
		'h': '␤',
		'i': '␋',
		'j': '┘',
		'k': '┐',
		'l': '┌',
		'm': '└',
		'n': '┼',
		'o': '⎺',
		'p': '⎻',
		'q': '─',
		'r': '⎼',
		's': '⎽',
		't': '├',
		'u': '┤',
		'v': '┴',
		'w': '┬',
		'x': '│',
		'y': '≤',
		'z': '≥',
		'{': 'π',
		'|': '≠',
		'}': '£',
		'~': '·',
	},

	'A': {
		'#': '£',
	},

	'B': nil,

	'4': {
		'#': '£',
		'@': '¾',

		'[':  'ij',
		'\\': '½',
		']':  '|',
		'{':  '¨',
		'|':  'f',
		'}':  '¼',
		'~':  '´',
	},

	'C': charsetFinnish,
	'5': charsetFinnish,

	'R': {
		'#':  '£',
		'@':  'à',
		'[':  '°',
		'\\': 'ç',
		']':  '§',
		'{':  'é',
		'|':  'ù',
		'}':  'è',
		'~':  '¨',
	},

	'Q': {
		'@':  'à',
		'[':  'â',
		'\\': 'ç',
		']':  'ê',
		'^':  'î',
		'`':  'ô',
		'{':  'é',
		'|':  'ù',
		'}':  'è',
		'~':  'û',
	},

	'K': {
		'@':  '§',
		'[':  'Ä',
		'\\': 'Ö',
		']':  'Ü',
		'{':  'ä',
		'|':  'ö',
		'}':  'ü',
		'~':  'ß',
	},

	'Y': {
		'#':  '£',
		'@':  '§',
		'[':  '°',
		'\\': 'ç',
		']':  'é',
		'`':  'ù',
		'{':  'à',
		'|':  'ò',
		'}':  'è',
		'~':  'ì',
	},

	'E': charsetNorwegian,
	'6': charsetNorwegian,

	'Z': {
		'#':  '£',
		'@':  '§',
		'[':  '¡',
		'\\': 'Ñ',
		']':  '¿',
		'{':  '°',
		'|':  'ñ',
		'}':  'ç',
	},

	'H': charsetSwedish,
	'7': charsetSwedish,

	'=': {
		'#':  'ù',
		'@':  'à',
		'[':  'é',
		'\\': 'ç',
		']':  'ê',
		'^':  'î',
		'_':  'è',
		'`':  'ô',
		'{':  'ä',
		'|':  'ö',
		'}':  'ü',
		'~':  'û',
	},
}

Charsets maps the designation byte (final char of ESC ( x etc.) to its translation table.

Functions

func CharProperties

func CharProperties(codepoint uint32, preceding uint32) uint32

CharProperties packs width/join info for a codepoint given the packed properties of the preceding char (UnicodeService.charProperties via the V6 provider).

func CreatePropertyValue

func CreatePropertyValue(state, width int, shouldJoin bool) uint32

CreatePropertyValue packs cluster state, width and join flag.

func ExtractCharKind

func ExtractCharKind(value uint32) int

ExtractCharKind unpacks the grapheme cluster state.

func ExtractShouldJoin

func ExtractShouldJoin(value uint32) bool

ExtractShouldJoin reports whether a packed property value has the join bit set.

func ExtractWidth

func ExtractWidth(value uint32) int

ExtractWidth unpacks the char width from a packed property value.

func FromColorRGB

func FromColorRGB(value [3]int) uint32

FromColorRGB packs [r, g, b] into a color value.

func GetStringCellWidth

func GetStringCellWidth(s string) int

GetStringCellWidth returns the number of terminal cells a string occupies (UnicodeService.getStringCellWidth, walking UTF-16 units to keep charCodeAt semantics).

func IdentToString

func IdentToString(ident int) string

IdentToString renders a packed identifier back to its byte string.

func ParseColor

func ParseColor(data string) (rgb [3]int, ok bool)

ParseColor parses a color spec to 8-bit-per-channel RGB. ok is false for unsupported specs (rgbi:, named colors).

func ToColorRGB

func ToColorRGB(value uint32) [3]int

ToColorRGB unpacks a color value to [r, g, b].

func ToRgbString

func ToRgbString(color [3]int, bits int) string

ToRgbString converts a color to an rgb:../../.. string of bits depth (default use: 16).

func Utf16ToString

func Utf16ToString(units []uint16) string

Utf16ToString converts UTF-16 code units back to a string.

func Utf16Units

func Utf16Units(s string) []uint16

Utf16Units converts a string to UTF-16 code units (JS string semantics — used by the browser layer for textarea value math).

func Wcwidth

func Wcwidth(num uint32) int

Wcwidth returns the terminal cell width (0, 1 or 2) of a codepoint per the UnicodeV6 provider.

Types

type AttributeData

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

AttributeData is the port of AttributeData: packed fg/bg attributes plus extended attributes.

func NewAttributeData

func NewAttributeData() *AttributeData

NewAttributeData creates empty attributes.

func (*AttributeData) Clone

func (a *AttributeData) Clone() *AttributeData

Clone returns a deep copy.

func (*AttributeData) GetBgColor

func (a *AttributeData) GetBgColor() int

GetBgColor returns the bg color value (-1 for default).

func (*AttributeData) GetBgColorMode

func (a *AttributeData) GetBgColorMode() uint32

func (*AttributeData) GetFgColor

func (a *AttributeData) GetFgColor() int

GetFgColor returns the fg color value (-1 for default).

func (*AttributeData) GetFgColorMode

func (a *AttributeData) GetFgColorMode() uint32

Color mode accessors.

func (*AttributeData) GetUnderlineColor

func (a *AttributeData) GetUnderlineColor() int

GetUnderlineColor returns the underline color (falls back to fg).

func (*AttributeData) GetUnderlineStyle

func (a *AttributeData) GetUnderlineStyle() int

GetUnderlineStyle returns the effective underline style.

func (*AttributeData) HasExtendedAttrs

func (a *AttributeData) HasExtendedAttrs() bool

HasExtendedAttrs reports whether extended attrs are present.

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

func (*AttributeData) IsBold

func (a *AttributeData) IsBold() bool

func (*AttributeData) IsDim

func (a *AttributeData) IsDim() bool

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

Flag accessors.

func (*AttributeData) IsInvisible

func (a *AttributeData) IsInvisible() bool

func (*AttributeData) IsItalic

func (a *AttributeData) IsItalic() bool

func (*AttributeData) IsOverline

func (a *AttributeData) IsOverline() bool

func (*AttributeData) IsProtected

func (a *AttributeData) IsProtected() bool

func (*AttributeData) IsStrikethrough

func (a *AttributeData) IsStrikethrough() bool

func (*AttributeData) IsUnderline

func (a *AttributeData) IsUnderline() bool

func (*AttributeData) UpdateExtended

func (a *AttributeData) UpdateExtended()

UpdateExtended syncs the HAS_EXTENDED flag with the extended content.

type Buffer

type Buffer struct {
	Lines            *CircularList[*BufferLine]
	YDisp            int
	YBase            int
	Y                int
	X                int
	ScrollBottom     int
	ScrollTop        int
	Tabs             map[int]bool
	SavedY           int
	SavedX           int
	SavedCurAttrData *AttributeData
	SavedCharset     Charset
	Markers          []*Marker
	// contains filtered or unexported fields
}

Buffer represents a terminal buffer: text content, cursor position and scroll state (port of Buffer).

func NewBuffer

func NewBuffer(hasScrollback bool, opts *Options, cols, rows int) *Buffer

NewBuffer creates a buffer.

func (*Buffer) AddMarker

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

AddMarker adds a line marker.

func (*Buffer) Clear

func (b *Buffer) Clear()

Clear resets the buffer to its initial state.

func (*Buffer) ClearAllMarkers

func (b *Buffer) ClearAllMarkers()

ClearAllMarkers clears all markers.

func (*Buffer) ClearMarkers

func (b *Buffer) ClearMarkers(y int)

ClearMarkers clears markers on a single line.

func (*Buffer) FillViewportRows

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

FillViewportRows fills the viewport with blank lines.

func (*Buffer) GetBlankLine

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

GetBlankLine returns a fresh blank line filled with attr.

func (*Buffer) GetNullCell

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

GetNullCell returns the shared null cell carrying attr.

func (*Buffer) GetWhitespaceCell

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

GetWhitespaceCell returns the shared whitespace cell carrying attr.

func (*Buffer) GetWrappedRangeForLine

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

GetWrappedRangeForLine returns the first and last row of the wrapped line group containing y.

func (*Buffer) HasScrollback

func (b *Buffer) HasScrollback() bool

HasScrollback reports whether the buffer has scrollback capacity.

func (*Buffer) IsCursorInViewport

func (b *Buffer) IsCursorInViewport() bool

IsCursorInViewport reports whether the cursor is visible.

func (*Buffer) NextStop

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

NextStop returns the next tab stop from x (or the cursor with -1).

func (*Buffer) PrevStop

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

PrevStop returns the previous tab stop from x (or the cursor with -1).

func (*Buffer) Resize

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

Resize the buffer, adjusting its data accordingly.

func (*Buffer) SetupTabStops

func (b *Buffer) SetupTabStops(i int)

SetupTabStops sets up the tab stops (i < 0 = from scratch).

func (*Buffer) TranslateBufferLineToString

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

TranslateBufferLineToString renders a buffer line as a string.

type BufferLine

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

BufferLine is the typed-array based buffer line implementation.

func NewBufferLine

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

NewBufferLine creates a line with cols cells filled with fillCellData (nil = null cells).

func (*BufferLine) AddCodepointToCell

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

AddCodepointToCell combines a zero-width codepoint onto the cell.

func (*BufferLine) Clone

func (l *BufferLine) Clone() *BufferLine

Clone returns a copy of the line.

func (*BufferLine) CopyCellsFrom

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

CopyCellsFrom copies length cells from src starting at srcCol into this line at destCol.

func (*BufferLine) CopyFrom

func (l *BufferLine) CopyFrom(line *BufferLine)

CopyFrom makes this line a full copy of line.

func (*BufferLine) DeleteCells

func (l *BufferLine) DeleteCells(pos, n int, fillCellData *CellData)

DeleteCells deletes n cells at pos, filling from the right.

func (*BufferLine) Fill

func (l *BufferLine) Fill(fillCellData *CellData, respectProtect bool)

Fill fills the whole line with fillCellData.

func (*BufferLine) GetBg

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

GetBg returns the BG component.

func (*BufferLine) GetCodePoint

func (l *BufferLine) GetCodePoint(index int) int

GetCodePoint returns the codepoint (or last UTF-16 unit of combined content).

func (*BufferLine) GetFg

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

GetFg returns the FG component.

func (*BufferLine) GetNoBgTrimmedLength

func (l *BufferLine) GetNoBgTrimmedLength() int

GetNoBgTrimmedLength is like GetTrimmedLength but keeps cells with a non-default background.

func (*BufferLine) GetString

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

GetString returns the string content of the cell.

func (*BufferLine) GetTrimmedLength

func (l *BufferLine) GetTrimmedLength() int

GetTrimmedLength returns the line length without trailing empty cells.

func (*BufferLine) GetWidth

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

GetWidth returns the width of the cell at index.

func (*BufferLine) HasContent

func (l *BufferLine) HasContent(index int) bool

HasContent reports whether the cell contains any chars.

func (*BufferLine) HasWidth

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

HasWidth reports whether the cell has width.

func (*BufferLine) InsertCells

func (l *BufferLine) InsertCells(pos, n int, fillCellData *CellData)

InsertCells inserts n fill cells at pos, shifting the rest right.

func (*BufferLine) IsCombined

func (l *BufferLine) IsCombined(index int) bool

IsCombined reports whether the cell contains a combined string.

func (*BufferLine) IsProtected

func (l *BufferLine) IsProtected(index int) bool

IsProtected reports the protected flag of the cell.

func (*BufferLine) LoadCell

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

LoadCell loads the cell at index into cell (GC friendly accessor).

func (*BufferLine) ReplaceCells

func (l *BufferLine) ReplaceCells(start, end int, fillCellData *CellData, respectProtect bool)

ReplaceCells fills cells from start (inclusive) to end (exclusive).

func (*BufferLine) Resize

func (l *BufferLine) Resize(cols int, fillCellData *CellData)

Resize the line to cols, filling new cells with fillCellData.

func (*BufferLine) SetCell

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

SetCell stores cell data at index.

func (*BufferLine) SetCellFromCodepoint

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

SetCellFromCodepoint sets cell data from the input handler fast path.

func (*BufferLine) TranslateToString

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

TranslateToString renders the line as a string.

type BufferService

type BufferService struct {
	Cols    int
	Rows    int
	Buffers *BufferSet
	// IsUserScrolling locks the scroll position while the user is
	// scrolled up.
	IsUserScrolling bool

	// OnResize fires after a resize with the new dimensions.
	OnResize func(cols, rows int)
	// OnScroll fires with the new YDisp whenever the viewport moves.
	OnScroll func(ydisp int)
	// contains filtered or unexported fields
}

BufferService owns the buffer set and the terminal dimensions, and implements scrolling.

func NewBufferService

func NewBufferService(options *Options) *BufferService

NewBufferService creates the buffer service with dimensions from the options.

func (*BufferService) Buffer

func (s *BufferService) Buffer() *Buffer

Buffer returns the active buffer.

func (*BufferService) Reset

func (s *BufferService) Reset()

Reset resets the buffers.

func (*BufferService) Resize

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

Resize changes the terminal dimensions.

func (*BufferService) Scroll

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

Scroll scrolls the terminal down 1 row, creating a blank line at the bottom. eraseAttr is the attribute data for the blank line.

func (*BufferService) ScrollLines

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

ScrollLines scrolls the display by disp lines (negative = up).

type BufferSet

type BufferSet struct {

	// OnBufferActivate fires when the active buffer switches.
	OnBufferActivate func(active, inactive *Buffer)
	// contains filtered or unexported fields
}

BufferSet represents the normal and alt buffers used by xterm terminals.

func NewBufferSet

func NewBufferSet(options *Options, cols, rows int) *BufferSet

NewBufferSet creates the normal/alt buffer pair.

func (*BufferSet) ActivateAltBuffer

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

ActivateAltBuffer switches to the alt buffer, filling it with blank rows using fillAttr.

func (*BufferSet) ActivateNormalBuffer

func (s *BufferSet) ActivateNormalBuffer()

ActivateNormalBuffer switches to the normal buffer, clearing the alt buffer.

func (*BufferSet) Active

func (s *BufferSet) Active() *Buffer

Active returns the currently active buffer.

func (*BufferSet) Alt

func (s *BufferSet) Alt() *Buffer

Alt returns the alt buffer.

func (*BufferSet) Normal

func (s *BufferSet) Normal() *Buffer

Normal returns the normal buffer.

func (*BufferSet) Reset

func (s *BufferSet) Reset()

Reset recreates both buffers and activates the normal one.

func (*BufferSet) Resize

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

Resize resizes both buffers.

func (*BufferSet) SetupTabStops

func (s *BufferSet) SetupTabStops(i int)

SetupTabStops sets up tab stops on both buffers from index i (i < 0 = full re-init).

type CellData

type CellData struct {
	AttributeData
	Content      uint32
	CombinedData string
}

CellData represents a single cell in the terminal buffer (port of CellData; embeds AttributeData).

func CellDataFromCharData

func CellDataFromCharData(value CharData) *CellData

CellDataFromCharData creates a CellData from CharData.

func NewCellData

func NewCellData() *CellData

NewCellData creates an empty cell.

func (*CellData) GetAsCharData

func (c *CellData) GetAsCharData() CharData

GetAsCharData returns the cell as CharData.

func (*CellData) GetChars

func (c *CellData) GetChars() string

GetChars returns the string content of the cell.

func (*CellData) GetCode

func (c *CellData) GetCode() int

GetCode returns the UTF32 codepoint (for combined content the last UTF-16 unit, matching the original).

func (*CellData) GetWidth

func (c *CellData) GetWidth() int

GetWidth returns the cell width.

func (*CellData) IsCombined

func (c *CellData) IsCombined() bool

IsCombined reports whether the cell contains a combined string.

func (*CellData) SetFromCharData

func (c *CellData) SetFromCharData(value CharData)

SetFromCharData fills the cell from CharData.

type CharData

type CharData struct {
	Attr  uint32
	Chars string
	Width int
	Code  int
}

CharData mirrors the legacy [attr, chars, width, code] tuple.

type Charset

type Charset map[byte]rune

Charset maps input glyphs to replacement strings (port of ICharset).

var DefaultCharset Charset // nil = pass-through

DefaultCharset is the default (US) character set.

type CharsetService

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

CharsetService tracks the active charset and the G0-G3 slots.

func (*CharsetService) Reset

func (s *CharsetService) Reset()

Reset clears all designated charsets.

func (*CharsetService) SetgCharset

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

SetgCharset designates a charset into a G slot.

func (*CharsetService) SetgLevel

func (s *CharsetService) SetgLevel(g int)

SetgLevel selects which G slot is active (shift in/out, LS2, LS3).

type CircularList

type CircularList[T any] struct {

	// OnTrim is called with the number of trimmed items.
	OnTrim func(amount int)
	// OnInsert is called after an insertion at index with amount items.
	OnInsert func(index, amount int)
	// OnDelete is called after a deletion at index of amount items.
	OnDelete func(index, amount int)
	// contains filtered or unexported fields
}

CircularList is a list with a maximum size that wraps around, overriding values at the start when full (port of CircularList). Event emitters are replaced by optional callback fields.

func NewCircularList

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

NewCircularList creates a circular list with the given max length.

func (*CircularList[T]) Get

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

Get returns the value at index (no bounds checking, cyclic).

func (*CircularList[T]) IsFull

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

IsFull reports whether the ring buffer is at max length.

func (*CircularList[T]) Length

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

Length returns the current length.

func (*CircularList[T]) MaxLength

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

MaxLength returns the maximum length.

func (*CircularList[T]) Pop

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

Pop removes and returns the last value.

func (*CircularList[T]) Push

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

Push appends a value, overriding index 0 when full.

func (*CircularList[T]) Recycle

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

Recycle advances the ring buffer and returns the element for reuse. The buffer must be full.

func (*CircularList[T]) Set

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

Set sets the value at index (no bounds checking, cyclic).

func (*CircularList[T]) SetLength

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

SetLength sets the length, zero-filling on growth.

func (*CircularList[T]) SetMaxLength

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

SetMaxLength resizes the maximum length, compacting the list.

func (*CircularList[T]) ShiftElements

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

ShiftElements moves count elements at start by offset.

func (*CircularList[T]) Splice

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

Splice deletes deleteCount items at start, then inserts items there.

func (*CircularList[T]) TrimStart

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

TrimStart removes count items from the start.

type ColorEvent

type ColorEvent struct {
	Type  ColorRequestType
	Index int
	Color [3]int
}

ColorEvent is one entry of an OSC 4/10/11/12/104/110/111/112 color request. Index is -1 for "all colors" (OSC 104 without params).

type ColorRequestType

type ColorRequestType int

ColorRequestType describes what an OSC color event asks for.

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

Color request types (ColorRequestType).

type CoreMouseService

type CoreMouseService struct {
	// OnProtocolChange fires with the event-type bitmask needed by the
	// new protocol (browser layer uses it to attach DOM listeners).
	OnProtocolChange func(events int)
	// contains filtered or unexported fields
}

CoreMouseService decides whether/how to send mouse tracking reports.

func NewCoreMouseService

func NewCoreMouseService(bufferService *BufferService, coreService *CoreService, options *Options) *CoreMouseService

NewCoreMouseService creates the mouse service with protocol NONE and encoding DEFAULT.

func (*CoreMouseService) ActiveEncoding

func (s *CoreMouseService) ActiveEncoding() string

ActiveEncoding returns the current encoding name.

func (*CoreMouseService) ActiveProtocol

func (s *CoreMouseService) ActiveProtocol() string

ActiveProtocol returns the current protocol name.

func (*CoreMouseService) AreMouseEventsActive

func (s *CoreMouseService) AreMouseEventsActive() bool

AreMouseEventsActive reports whether any events are being tracked.

func (*CoreMouseService) ConsumeWheelEvent

func (s *CoreMouseService) ConsumeWheelEvent(deltaY float64, deltaMode int, shift, alt, ctrl bool, cellHeight, dpr float64) int

ConsumeWheelEvent converts a wheel delta into a line scroll amount, accounting for partial trackpad scrolls (port of consumeWheelEvent; the DOM event fields are passed in by the browser layer). deltaMode: 0 = pixel, 1 = line, 2 = page.

func (*CoreMouseService) Reset

func (s *CoreMouseService) Reset()

Reset restores protocol NONE / encoding DEFAULT.

func (*CoreMouseService) SetActiveEncoding

func (s *CoreMouseService) SetActiveEncoding(name string)

SetActiveEncoding switches the encoding.

func (*CoreMouseService) SetActiveProtocol

func (s *CoreMouseService) SetActiveProtocol(name string)

SetActiveProtocol switches the protocol (panics on unknown name, like the JS throw).

func (*CoreMouseService) TriggerMouseEvent

func (s *CoreMouseService) TriggerMouseEvent(e *MouseEvent) bool

TriggerMouseEvent sends a mouse report if the active protocol and encoding allow it. Returns true if a report was sent (the browser layer uses this to decide whether to suppress the default action). Note: the method mutates the event to fulfill protocol restrictions.

type CoreService

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

	// OnData receives data headed for the pty (user input and
	// terminal query responses).
	OnData func(data string)
	// OnUserInput fires on user-originated input (e.g. to clear the
	// selection).
	OnUserInput func()
	// OnBinary receives binary data headed for the pty.
	OnBinary func(data string)
	// OnRequestScrollToBottom fires when user input should snap the
	// viewport back to the bottom.
	OnRequestScrollToBottom func()
	// contains filtered or unexported fields
}

CoreService is the pty-facing output side of the terminal: data the terminal wants to send back (keystrokes, query responses) goes through TriggerDataEvent.

func NewCoreService

func NewCoreService(bufferService *BufferService, options *Options) *CoreService

NewCoreService creates a CoreService bound to a buffer service and options.

func (*CoreService) Reset

func (c *CoreService) Reset()

Reset restores default modes.

func (*CoreService) TriggerBinaryEvent

func (c *CoreService) TriggerBinaryEvent(data string)

TriggerBinaryEvent sends binary data to the pty unless stdin is disabled.

func (*CoreService) TriggerDataEvent

func (c *CoreService) TriggerDataEvent(data string, wasUserInput bool)

TriggerDataEvent sends data to the pty unless stdin is disabled.

type CsiHandler

type CsiHandler func(params *Params) bool

CsiHandler is invoked for CSI sequences. Returns handled (true stops bubbling to older handlers).

type DcsHandler

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

DcsHandler handles DCS sequences.

type DcsHandlerFunc

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

DcsHandlerFunc adapts a string-based callback into a DcsHandler.

func NewDcsHandler

func NewDcsHandler(fn func(data string, params *Params) bool) *DcsHandlerFunc

NewDcsHandler wraps fn as a DCS handler.

func (*DcsHandlerFunc) Hook

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

Hook implements DcsHandler.

func (*DcsHandlerFunc) Put

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

Put implements DcsHandler.

func (*DcsHandlerFunc) Unhook

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

Unhook implements DcsHandler.

type DcsParser

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

DcsParser parses DCS sequences (hook/put/unhook).

func NewDcsParser

func NewDcsParser() *DcsParser

NewDcsParser creates a DCS sub parser.

func (*DcsParser) Hook

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

Hook starts a DCS sequence.

func (*DcsParser) Put

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

Put feeds payload data.

func (*DcsParser) RegisterHandler

func (d *DcsParser) RegisterHandler(ident int, handler DcsHandler)

RegisterHandler adds a handler for the given DCS identifier.

func (*DcsParser) Reset

func (d *DcsParser) Reset()

Reset aborts any pending sequence.

func (*DcsParser) SetHandlerFallback

func (d *DcsParser) SetHandlerFallback(fn func(ident int, action string, data interface{}))

SetHandlerFallback installs the fallback handler.

func (*DcsParser) Unhook

func (d *DcsParser) Unhook(success bool)

Unhook finishes the DCS sequence.

type DecPrivateModes

type DecPrivateModes struct {
	ApplicationCursorKeys bool
	ApplicationKeypad     bool
	BracketedPasteMode    bool
	// CursorBlink/CursorStyle: nil = not overridden by DECSCUSR.
	CursorBlink        *bool
	CursorStyle        *string
	Origin             bool
	ReverseWraparound  bool
	SendFocus          bool
	SynchronizedOutput bool
	Wraparound         bool // defaults: xterm - true, vt100 - false
}

DecPrivateModes holds the DEC private modes (IDecPrivateModes).

type EscHandler

type EscHandler func() bool

EscHandler is invoked for ESC sequences.

type ExecuteHandler

type ExecuteHandler func() bool

ExecuteHandler is invoked for C0/C1 control codes. Returns handled.

type ExtendedAttrs

type ExtendedAttrs struct {
	URLID int
	// contains filtered or unexported fields
}

ExtendedAttrs holds underline style/color and url id of a cell.

func NewExtendedAttrs

func NewExtendedAttrs() *ExtendedAttrs

NewExtendedAttrs creates empty extended attributes.

func (*ExtendedAttrs) Clone

func (e *ExtendedAttrs) Clone() *ExtendedAttrs

Clone returns a copy.

func (*ExtendedAttrs) Ext

func (e *ExtendedAttrs) Ext() uint32

Ext returns the packed extended attribute value.

func (*ExtendedAttrs) HasUnderlineColor

func (e *ExtendedAttrs) HasUnderlineColor() bool

HasUnderlineColor mirrors the JS `~underlineColor` truthiness check; since the getter masks to a non-negative value it can never be -1, making the check effectively always true (kept for faithfulness).

func (*ExtendedAttrs) IsEmpty

func (e *ExtendedAttrs) IsEmpty() bool

IsEmpty reports whether the attrs hold nothing persistent.

func (*ExtendedAttrs) SetExt

func (e *ExtendedAttrs) SetExt(value uint32)

SetExt sets the packed extended attribute value.

func (*ExtendedAttrs) SetUnderlineColor

func (e *ExtendedAttrs) SetUnderlineColor(value uint32)

SetUnderlineColor sets the packed underline color.

func (*ExtendedAttrs) SetUnderlineStyle

func (e *ExtendedAttrs) SetUnderlineStyle(value int)

SetUnderlineStyle sets the underline style.

func (*ExtendedAttrs) SetUnderlineVariantOffset

func (e *ExtendedAttrs) SetUnderlineVariantOffset(value int)

SetUnderlineVariantOffset sets the variant offset.

func (*ExtendedAttrs) UnderlineColor

func (e *ExtendedAttrs) UnderlineColor() uint32

UnderlineColor returns the packed underline color (mode+rgb).

func (*ExtendedAttrs) UnderlineStyle

func (e *ExtendedAttrs) UnderlineStyle() int

UnderlineStyle returns the underline style.

func (*ExtendedAttrs) UnderlineVariantOffset

func (e *ExtendedAttrs) UnderlineVariantOffset() int

UnderlineVariantOffset returns the variant offset.

type FunctionID

type FunctionID struct {
	Prefix        string
	Intermediates string
	Final         string
}

FunctionID identifies a CSI/ESC/DCS function: an optional prefix byte (0x3c..0x3f), up to two intermediates (0x20..0x2f) and the final byte.

type InputHandler

type InputHandler struct {

	// Event callbacks (Emitter fields of the original).
	OnRequestBell                 func()
	OnRequestRefreshRows          func(start, end int) // -1,-1 = full refresh
	OnRequestReset                func()
	OnRequestSendFocus            func()
	OnRequestSyncScrollBar        func()
	OnRequestWindowsOptionsReport func(reportType int)
	OnA11yChar                    func(char string)
	OnA11yTab                     func(spaces int)
	OnCursorMove                  func()
	OnLineFeed                    func()
	OnScroll                      func(ydisp int)
	OnTitleChange                 func(title string)
	OnColor                       func(events []ColorEvent)
	// contains filtered or unexported fields
}

InputHandler interprets all input from the parser.

func NewInputHandler

func NewInputHandler(bufferService *BufferService, charsetService *CharsetService, coreService *CoreService, mouseService *CoreMouseService, oscLinkService *OscLinkService, options *Options) *InputHandler

NewInputHandler creates the handler and registers all sequence handlers on the parser.

func (*InputHandler) Backspace

func (h *InputHandler) Backspace() bool

Backspace handles BS, honoring reverse wrap-around (CSI ? 45 h).

func (*InputHandler) Bell

func (h *InputHandler) Bell() bool

Bell rings the bell (BEL).

func (*InputHandler) CarriageReturn

func (h *InputHandler) CarriageReturn() bool

CarriageReturn handles CR.

func (*InputHandler) CharAttributes

func (h *InputHandler) CharAttributes(params *Params) bool

CharAttributes handles SGR.

func (*InputHandler) CharPosAbsolute

func (h *InputHandler) CharPosAbsolute(params *Params) bool

CharPosAbsolute handles HPA.

func (*InputHandler) CursorBackward

func (h *InputHandler) CursorBackward(params *Params) bool

CursorBackward handles CUB.

func (*InputHandler) CursorBackwardTab

func (h *InputHandler) CursorBackwardTab(params *Params) bool

CursorBackwardTab handles CBT.

func (*InputHandler) CursorCharAbsolute

func (h *InputHandler) CursorCharAbsolute(params *Params) bool

CursorCharAbsolute handles CHA.

func (*InputHandler) CursorDown

func (h *InputHandler) CursorDown(params *Params) bool

CursorDown handles CUD (stops at the bottom scroll margin).

func (*InputHandler) CursorForward

func (h *InputHandler) CursorForward(params *Params) bool

CursorForward handles CUF.

func (*InputHandler) CursorForwardTab

func (h *InputHandler) CursorForwardTab(params *Params) bool

CursorForwardTab handles CHT.

func (*InputHandler) CursorNextLine

func (h *InputHandler) CursorNextLine(params *Params) bool

CursorNextLine handles CNL.

func (*InputHandler) CursorPosition

func (h *InputHandler) CursorPosition(params *Params) bool

CursorPosition handles CUP.

func (*InputHandler) CursorPrecedingLine

func (h *InputHandler) CursorPrecedingLine(params *Params) bool

CursorPrecedingLine handles CPL.

func (*InputHandler) CursorUp

func (h *InputHandler) CursorUp(params *Params) bool

CursorUp handles CUU (stops at the top scroll margin).

func (*InputHandler) DeleteChars

func (h *InputHandler) DeleteChars(params *Params) bool

DeleteChars handles DCH.

func (*InputHandler) DeleteColumns

func (h *InputHandler) DeleteColumns(params *Params) bool

DeleteColumns handles DECDC.

func (*InputHandler) DeleteLines

func (h *InputHandler) DeleteLines(params *Params) bool

DeleteLines handles DL.

func (*InputHandler) DeviceStatus

func (h *InputHandler) DeviceStatus(params *Params) bool

DeviceStatus handles DSR.

func (*InputHandler) DeviceStatusPrivate

func (h *InputHandler) DeviceStatusPrivate(params *Params) bool

DeviceStatusPrivate handles DEC-specific DSR (only CPR).

func (*InputHandler) EraseChars

func (h *InputHandler) EraseChars(params *Params) bool

EraseChars handles ECH.

func (*InputHandler) EraseInDisplay

func (h *InputHandler) EraseInDisplay(params *Params, respectProtect bool) bool

EraseInDisplay handles ED and DECSED.

func (*InputHandler) EraseInLine

func (h *InputHandler) EraseInLine(params *Params, respectProtect bool) bool

EraseInLine handles EL and DECSEL.

func (*InputHandler) FullReset

func (h *InputHandler) FullReset() bool

FullReset handles RIS.

func (*InputHandler) GetAttrData

func (h *InputHandler) GetAttrData() *AttributeData

GetAttrData returns the current attribute data.

func (*InputHandler) HPositionRelative

func (h *InputHandler) HPositionRelative(params *Params) bool

HPositionRelative handles HPR.

func (*InputHandler) HVPosition

func (h *InputHandler) HVPosition(params *Params) bool

HVPosition handles HVP (same as CUP).

func (*InputHandler) Index

func (h *InputHandler) Index() bool

Index handles IND.

func (*InputHandler) InsertChars

func (h *InputHandler) InsertChars(params *Params) bool

InsertChars handles ICH.

func (*InputHandler) InsertColumns

func (h *InputHandler) InsertColumns(params *Params) bool

InsertColumns handles DECIC.

func (*InputHandler) InsertLines

func (h *InputHandler) InsertLines(params *Params) bool

InsertLines handles IL.

func (*InputHandler) KeypadApplicationMode

func (h *InputHandler) KeypadApplicationMode() bool

KeypadApplicationMode handles DECKPAM.

func (*InputHandler) KeypadNumericMode

func (h *InputHandler) KeypadNumericMode() bool

KeypadNumericMode handles DECKPNM.

func (*InputHandler) LineFeed

func (h *InputHandler) LineFeed() bool

LineFeed handles LF/VT/FF.

func (*InputHandler) LinePosAbsolute

func (h *InputHandler) LinePosAbsolute(params *Params) bool

LinePosAbsolute handles VPA.

func (*InputHandler) MarkRangeDirty

func (h *InputHandler) MarkRangeDirty(y1, y2 int)

MarkRangeDirty exposes dirty marking for the terminal (used on scroll events).

func (*InputHandler) NextLine

func (h *InputHandler) NextLine() bool

NextLine handles NEL.

func (*InputHandler) Parse

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

Parse decodes and parses a chunk of UTF-8 pty output.

func (*InputHandler) ParseString

func (h *InputHandler) ParseString(data string)

ParseString parses a chunk given as a Go string (decoded via UTF-16 like the JS string path to keep charCodeAt semantics for lone surrogates).

func (*InputHandler) Parser

func (h *InputHandler) Parser() *Parser

Parser exposes the parser for custom handler registration.

func (*InputHandler) Print

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

Print writes decoded codepoints to the buffer (the parser's print handler).

func (*InputHandler) RegisterCsiHandler

func (h *InputHandler) RegisterCsiHandler(id FunctionID, callback CsiHandler)

RegisterCsiHandler forwards custom CSI handlers to the parser, with the window-options security gate for plain CSI t.

func (*InputHandler) RegisterDcsHandler

func (h *InputHandler) RegisterDcsHandler(id FunctionID, callback func(data string, params *Params) bool)

RegisterDcsHandler forwards custom DCS handlers to the parser.

func (*InputHandler) RegisterEscHandler

func (h *InputHandler) RegisterEscHandler(id FunctionID, callback EscHandler)

RegisterEscHandler forwards custom ESC handlers to the parser.

func (*InputHandler) RegisterOscHandler

func (h *InputHandler) RegisterOscHandler(ident int, callback func(data string) bool)

RegisterOscHandler forwards custom OSC handlers to the parser.

func (*InputHandler) RepeatPrecedingCharacter

func (h *InputHandler) RepeatPrecedingCharacter(params *Params) bool

RepeatPrecedingCharacter handles REP; repeats entire grapheme clusters like the original's extension of xterm's behavior.

func (*InputHandler) RequestMode

func (h *InputHandler) RequestMode(params *Params, ansi bool) bool

RequestMode handles DECRQM (reports via DECRPM).

func (*InputHandler) RequestStatusString

func (h *InputHandler) RequestStatusString(data string, params *Params) bool

RequestStatusString handles DECRQSS.

func (*InputHandler) Reset

func (h *InputHandler) Reset()

Reset resets the handler attributes (called from the terminal reset).

func (*InputHandler) ResetMode

func (h *InputHandler) ResetMode(params *Params) bool

ResetMode handles RM.

func (*InputHandler) ResetModePrivate

func (h *InputHandler) ResetModePrivate(params *Params) bool

ResetModePrivate handles DECRST.

func (*InputHandler) RestoreBgColor

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

RestoreBgColor handles OSC 111.

func (*InputHandler) RestoreCursor

func (h *InputHandler) RestoreCursor() bool

RestoreCursor handles DECRC / CSI u.

func (*InputHandler) RestoreCursorColor

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

RestoreCursorColor handles OSC 112.

func (*InputHandler) RestoreFgColor

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

RestoreFgColor handles OSC 110.

func (*InputHandler) RestoreIndexedColor

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

RestoreIndexedColor handles OSC 104.

func (*InputHandler) ReverseIndex

func (h *InputHandler) ReverseIndex() bool

ReverseIndex handles RI.

func (*InputHandler) SaveCursor

func (h *InputHandler) SaveCursor() bool

SaveCursor handles DECSC / CSI s.

func (*InputHandler) ScreenAlignmentPattern

func (h *InputHandler) ScreenAlignmentPattern() bool

ScreenAlignmentPattern handles DECALN.

func (*InputHandler) ScrollDown

func (h *InputHandler) ScrollDown(params *Params) bool

ScrollDown handles SD.

func (*InputHandler) ScrollLeft

func (h *InputHandler) ScrollLeft(params *Params) bool

ScrollLeft handles SL (ECMA-48).

func (*InputHandler) ScrollRight

func (h *InputHandler) ScrollRight(params *Params) bool

ScrollRight handles SR (ECMA-48).

func (*InputHandler) ScrollUp

func (h *InputHandler) ScrollUp(params *Params) bool

ScrollUp handles SU.

func (*InputHandler) SelectCharset

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

SelectCharset designates a charset (ESC ( C etc.).

func (*InputHandler) SelectDefaultCharset

func (h *InputHandler) SelectDefaultCharset() bool

SelectDefaultCharset handles ESC % @ and ESC % G.

func (*InputHandler) SelectProtected

func (h *InputHandler) SelectProtected(params *Params) bool

SelectProtected handles DECSCA.

func (*InputHandler) SendDeviceAttributesPrimary

func (h *InputHandler) SendDeviceAttributesPrimary(params *Params) bool

SendDeviceAttributesPrimary handles DA1.

func (*InputHandler) SendDeviceAttributesSecondary

func (h *InputHandler) SendDeviceAttributesSecondary(params *Params) bool

SendDeviceAttributesSecondary handles DA2.

func (*InputHandler) SetCursorStyle

func (h *InputHandler) SetCursorStyle(params *Params) bool

SetCursorStyle handles DECSCUSR.

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

SetHyperlink handles OSC 8.

func (*InputHandler) SetIconName

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

SetIconName handles OSC 0/1 (icon name is not exposed).

func (*InputHandler) SetMode

func (h *InputHandler) SetMode(params *Params) bool

SetMode handles SM (only IRM and LNM are supported).

func (*InputHandler) SetModePrivate

func (h *InputHandler) SetModePrivate(params *Params) bool

SetModePrivate handles DECSET.

func (*InputHandler) SetOrReportBgColor

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

SetOrReportBgColor handles OSC 11.

func (*InputHandler) SetOrReportCursorColor

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

SetOrReportCursorColor handles OSC 12.

func (*InputHandler) SetOrReportFgColor

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

SetOrReportFgColor handles OSC 10.

func (*InputHandler) SetOrReportIndexedColor

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

SetOrReportIndexedColor handles OSC 4.

func (*InputHandler) SetScrollRegion

func (h *InputHandler) SetScrollRegion(params *Params) bool

SetScrollRegion handles DECSTBM.

func (*InputHandler) SetTitle

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

SetTitle handles OSC 0/2.

func (*InputHandler) SetgLevel

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

SetgLevel handles the locking shifts (ESC n/o/|/}/~).

func (*InputHandler) ShiftIn

func (h *InputHandler) ShiftIn() bool

ShiftIn handles SI (invoke G0).

func (*InputHandler) ShiftOut

func (h *InputHandler) ShiftOut() bool

ShiftOut handles SO (invoke G1).

func (*InputHandler) SoftReset

func (h *InputHandler) SoftReset(params *Params) bool

SoftReset handles DECSTR.

func (*InputHandler) Tab

func (h *InputHandler) Tab() bool

Tab handles HT.

func (*InputHandler) TabClear

func (h *InputHandler) TabClear(params *Params) bool

TabClear handles TBC.

func (*InputHandler) TabSet

func (h *InputHandler) TabSet() bool

TabSet handles HTS.

func (*InputHandler) VPositionRelative

func (h *InputHandler) VPositionRelative(params *Params) bool

VPositionRelative handles VPR.

func (*InputHandler) WindowOptionsHandler

func (h *InputHandler) WindowOptionsHandler(params *Params) bool

WindowOptionsHandler handles CSI t window manipulations (gated by Options.WindowOptions).

func (*InputHandler) WindowTitle

func (h *InputHandler) WindowTitle() string

WindowTitle returns the current window title.

type KeyboardEvent

type KeyboardEvent struct {
	AltKey   bool
	CtrlKey  bool
	ShiftKey bool
	MetaKey  bool
	KeyCode  int
	Key      string
	Code     string
}

KeyboardEvent is the subset of the DOM KeyboardEvent used for evaluation (IKeyboardEvent).

type KeyboardResult

type KeyboardResult struct {
	Type KeyboardResultType
	// Cancel reports whether to cancel event propagation.
	Cancel bool
	// Key is the data to send to the pty ("" = nothing).
	Key string
}

KeyboardResult is the evaluation outcome (IKeyboardResult).

func EvaluateKeyboardEvent

func EvaluateKeyboardEvent(ev *KeyboardEvent, applicationCursorMode, isMac, macOptionIsMeta bool) KeyboardResult

EvaluateKeyboardEvent translates a keydown event into the data to send to the pty.

type KeyboardResultType

type KeyboardResultType int

KeyboardResultType describes what should happen for a key event.

const (
	KeySendKey KeyboardResultType = iota
	KeySelectAll
	KeyPageUp
	KeyPageDown
)

Keyboard result types.

type Marker

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

Marker tracks a line position in the buffer across scrolling (simplified port of Marker).

func (*Marker) Dispose

func (m *Marker) Dispose()

Dispose invalidates the marker.

func (*Marker) IsDisposed

func (m *Marker) IsDisposed() bool

IsDisposed reports whether the marker was disposed.

type Modes

type Modes struct {
	InsertMode bool
}

Modes holds the ANSI-standardized modes (IModes).

type MouseEvent

type MouseEvent struct {
	Col, Row int
	X, Y     int
	Button   int
	Action   int
	Ctrl     bool
	Alt      bool
	Shift    bool
}

MouseEvent is the terminal-side mouse event (ICoreMouseEvent). Col/Row are 0-based grid coords; X/Y pixel coords (SGR_PIXELS).

type Options

type Options struct {
	// Cols/Rows of the terminal. Defaults: 80x24.
	Cols int
	Rows int
	// Scrollback line count. Default: 1000.
	Scrollback int
	// TabStopWidth. Default: 8.
	TabStopWidth int
	// CursorBlink toggles cursor blinking. Default: false.
	CursorBlink bool
	// ConvertEol treats LF as CRLF. Default: false.
	ConvertEol bool
	// DisableStdin ignores keyboard input. Default: false.
	DisableStdin bool
	// ScreenReaderMode. Default: false.
	ScreenReaderMode bool
	// WindowsMode disables reflow (conpty quirk mode). Default: false.
	WindowsMode bool
	// ReflowCursorLine reflows the cursor line on resize. Default: false.
	ReflowCursorLine bool
	// TermName reported by DA sequences. Default: "xterm".
	TermName string
	// CursorStyle: "block", "underline" or "bar". Default: "block".
	CursorStyle string
	// ScrollOnUserInput snaps the viewport to the bottom on input.
	// Default: true.
	ScrollOnUserInput bool
	// ScrollOnEraseInDisplay scrolls content into scrollback on ED 2
	// instead of clearing it. Default: false.
	ScrollOnEraseInDisplay bool
	// ScrollSensitivity scaling for wheel scroll. Default: 1.
	ScrollSensitivity float64
	// FastScrollSensitivity applied while the modifier is held. Default: 5.
	FastScrollSensitivity float64
	// WindowOptions enables individual CSI t window commands (all
	// default false, security).
	WindowOptions WindowOptions
	// FontFamily/FontSize used by the renderer.
	FontFamily string
	FontSize   float64
	// LineHeight multiplier. Default: 1.
	LineHeight float64

	// MirrorGlyph reports whether a glyph should be drawn flipped left-to-right.
	// nil, the default, draws everything the way round the font has it.
	//
	// This exists because some glyphs are only correct mirrored and no font
	// supplies them that way. The Matrix's code rain is the case it was added
	// for: its katakana are flipped horizontally, drawn as a custom typeface for
	// the film, and Unicode encodes no mirrored kana — so a terminal cannot ask
	// for them. The WebGL renderer rasterises each glyph onto a canvas before
	// packing it into its atlas, and a canvas can be told to draw mirrored, so
	// the flip costs one transform at the point the glyph is first drawn and
	// nothing per frame.
	//
	// It is a rendering transform and not a font: the cell still holds the
	// ordinary codepoint, so selecting, copying and reading the buffer are
	// unaffected, and a terminal that cannot do this shows the glyph unflipped
	// rather than showing nothing.
	//
	// Only the WebGL renderer honours it. The DOM renderer draws real text and
	// has no rasterisation step to hook.
	MirrorGlyph func(string) bool
	// LetterSpacing in px. Default: 0.
	LetterSpacing float64
	// Theme colors (CSS color strings; empty = defaults).
	Theme Theme
}

Options is the subset of the xterm.js options relevant to the core (port of the OptionsService raw options; browser-only options live in the wasm layer).

func NewOptions

func NewOptions() *Options

NewOptions returns options with xterm.js defaults.

type OscHandler

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

OscHandler adapts a string-based callback into an OscHandlerIface.

func NewOscHandler

func NewOscHandler(fn func(data string) bool) *OscHandler

NewOscHandler wraps fn as an OSC handler.

func (*OscHandler) End

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

End implements OscHandlerIface.

func (*OscHandler) Put

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

Put implements OscHandlerIface.

func (*OscHandler) Start

func (h *OscHandler) Start()

Start implements OscHandlerIface.

type OscHandlerIface

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

OscHandlerIface handles OSC commands.

type OscLink struct {
	ID  string
	URI string
}

OscLink is a hyperlink created via OSC 8.

type OscLinkService

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

OscLinkService stores OSC 8 hyperlinks by id.

func NewOscLinkService

func NewOscLinkService() *OscLinkService

NewOscLinkService creates an empty link registry.

func (*OscLinkService) GetLinkData

func (s *OscLinkService) GetLinkData(linkID int) (OscLink, bool)

GetLinkData returns the link for an id.

func (s *OscLinkService) RegisterLink(id, uri string) int

RegisterLink stores a link and returns its numeric id (stored in ExtendedAttrs.URLID).

type OscParser

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

OscParser parses "OSC id ; payload ST/BEL" commands.

func NewOscParser

func NewOscParser() *OscParser

NewOscParser creates an OSC sub parser.

func (*OscParser) End

func (o *OscParser) End(success bool)

End finishes the OSC command; success indicates normal termination.

func (*OscParser) Put

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

Put feeds data into the current OSC command.

func (*OscParser) RegisterHandler

func (o *OscParser) RegisterHandler(ident int, handler OscHandlerIface)

RegisterHandler adds a handler for the given OSC identifier.

func (*OscParser) Reset

func (o *OscParser) Reset()

Reset aborts any pending command.

func (*OscParser) SetHandlerFallback

func (o *OscParser) SetHandlerFallback(fn func(id int, action string, data interface{}))

SetHandlerFallback installs the fallback handler.

func (*OscParser) Start

func (o *OscParser) Start()

Start begins a new OSC command.

type Params

type Params struct {
	Params []int32
	Length int
	// contains filtered or unexported fields
}

Params is the parameter storage used by the parser to accumulate sequence parameters and sub parameters (the "1;2:3:4;5" part of CSI sequences).

Notes carried over from the original:

  • the params object passed to handlers is borrowed; use ToArray or Clone for a copy
  • never read beyond Length-1 (likely to contain arbitrary data)
  • max value for a single (sub) param is 2^31-1, greater values clamp
  • negative values other than -1 (default placeholder) are not allowed

About ZDM (Zero Default Mode): the parser adds 0 for empty params; empty subparams are always added as -1.

func NewParams

func NewParams() *Params

NewParams creates a Params store with default capacity (32/32).

func NewParamsWithLimits

func NewParamsWithLimits(maxLength, maxSubParamsLength int) *Params

NewParamsWithLimits creates a Params store with explicit limits.

func ParamsFromArray

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

ParamsFromArray builds Params from a slice where plain values are params and nested slices are sub params of the preceding param (mirroring Params.fromArray).

func (*Params) AddDigit

func (p *Params) AddDigit(value int32)

AddDigit adds a single digit to the current (sub) parameter; used by the parser to account digits char by char.

func (*Params) AddParam

func (p *Params) AddParam(value int32)

AddParam adds a parameter value. Only up to maxLength parameters are stored; later ones are ignored.

func (*Params) AddSubParam

func (p *Params) AddSubParam(value int32)

AddSubParam adds a sub parameter to the last parameter added.

func (*Params) Clone

func (p *Params) Clone() *Params

Clone returns a deep copy.

func (*Params) GetSubParams

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

GetSubParams returns the borrowed sub parameters of the parameter at idx (nil if none).

func (*Params) GetSubParamsAll

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

GetSubParamsAll returns all sub parameters as an idx → values map (values copied).

func (*Params) HasSubParams

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

HasSubParams reports whether the parameter at idx has sub parameters.

func (*Params) Reset

func (p *Params) Reset()

Reset returns the store to its initial empty state.

func (*Params) ToArray

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

ToArray returns a representation where plain params are int and sub params appear as []int after their param: "1;2:3:4;5" → [1, 2, [3,4], 5].

type Parser

type Parser struct {

	// PrecedingJoinState carries the unicode join state across print calls.
	PrecedingJoinState int
	// contains filtered or unexported fields
}

Parser is the port of EscapeSequenceParser: an ANSI/DEC compatible parser as described by Paul Williams (https://vt100.net/emu/dec_ansi_parser), operating in Zero Default Mode with sub parameter support.

Unlike the original, handlers are synchronous only.

Example
p := NewParser()
p.SetPrintHandler(func(data []uint32, start, end int) {
	fmt.Print(utf32ToString(data, start, end))
})
feed(p, "plain \x1b[31mcolored\x1b[0m text")
Output:
plain colored text

func NewParser

func NewParser() *Parser

NewParser creates a parser with the VT500 transition table.

func (*Parser) Parse

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

Parse processes UTF32 codepoints in data[:length].

func (*Parser) RegisterCsiHandler

func (p *Parser) RegisterCsiHandler(id FunctionID, handler CsiHandler)

RegisterCsiHandler adds a CSI sequence handler.

func (*Parser) RegisterDcsHandler

func (p *Parser) RegisterDcsHandler(id FunctionID, handler DcsHandler)

RegisterDcsHandler adds a DCS sequence handler.

func (*Parser) RegisterEscHandler

func (p *Parser) RegisterEscHandler(id FunctionID, handler EscHandler)

RegisterEscHandler adds an ESC sequence handler.

func (*Parser) RegisterOscHandler

func (p *Parser) RegisterOscHandler(ident int, handler OscHandlerIface)

RegisterOscHandler adds an OSC command handler.

func (*Parser) Reset

func (p *Parser) Reset()

Reset returns the parser to its initial state.

func (*Parser) SetCsiHandlerFallback

func (p *Parser) SetCsiHandlerFallback(fn func(ident int, params *Params))

SetCsiHandlerFallback installs the CSI fallback.

func (*Parser) SetEscHandlerFallback

func (p *Parser) SetEscHandlerFallback(fn func(ident int))

SetEscHandlerFallback installs the ESC fallback.

func (*Parser) SetExecuteHandler

func (p *Parser) SetExecuteHandler(flag byte, handler ExecuteHandler)

SetExecuteHandler installs a handler for a C0/C1 control code.

func (*Parser) SetExecuteHandlerFallback

func (p *Parser) SetExecuteHandlerFallback(fn func(code uint32))

SetExecuteHandlerFallback installs the execute fallback.

func (*Parser) SetPrintHandler

func (p *Parser) SetPrintHandler(handler PrintHandler)

SetPrintHandler installs the print handler.

type ParsingState

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

ParsingState is handed to the error handler.

type PrintHandler

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

PrintHandler receives printable codepoints data[start:end].

type StringToUtf32

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

StringToUtf32 decodes UTF16-oriented JS-style strings into UTF32 codepoints. For Go strings (UTF-8) use Utf8ToUtf32 or DecodeString.

func (*StringToUtf32) Clear

func (s *StringToUtf32) Clear()

Clear resets the decoder.

func (*StringToUtf32) Decode

func (s *StringToUtf32) Decode(input []uint16, target []uint32) int

Decode writes codepoints of input into target, returning the count.

type Terminal

type Terminal struct {
	Options *Options

	// OnData receives data the terminal sends to the pty (user input,
	// query responses).
	OnData func(data string)
	// OnBinary receives binary data for the pty (legacy mouse
	// encoding).
	OnBinary func(data string)
	// OnLineFeed fires on line feeds.
	OnLineFeed func()
	// OnResize fires after the dimensions changed.
	OnResize func(cols, rows int)
	// OnScroll fires with the new viewport offset.
	OnScroll func(ydisp int)
	// OnTitleChange fires when the window title changes.
	OnTitleChange func(title string)
	// OnRefreshRows asks the renderer to redraw viewport rows
	// start..end (inclusive); -1,-1 means everything.
	OnRefreshRows func(start, end int)
	// OnBell fires on BEL.
	OnBell func()
	// OnColor receives OSC color set/report/restore requests.
	OnColor func(events []ColorEvent)
	// OnCursorMove fires when the cursor moved during a write.
	OnCursorMove func()
	// OnA11yChar/OnA11yTab fire in screen reader mode.
	OnA11yChar func(char string)
	OnA11yTab  func(spaces int)
	// OnWindowsOptionsReport asks the browser layer to report pixel
	// sizes (CSI t 14/16).
	OnWindowsOptionsReport func(reportType int)
	// OnSyncScrollBar asks the viewport to sync (keypad/alt-buffer
	// changes).
	OnSyncScrollBar func()
	// OnSendFocus asks the browser layer to send a focus report.
	OnSendFocus func()
	// OnProtocolChange fires with the mouse event mask needed by the
	// active mouse protocol.
	OnProtocolChange func(events int)
	// contains filtered or unexported fields
}

Terminal is a headless VT terminal.

func NewTerminal

func NewTerminal(options *Options) *Terminal

NewTerminal creates a headless terminal. Pass nil for defaults.

func (*Terminal) Buffer

func (t *Terminal) Buffer() *Buffer

Buffer returns the active buffer.

func (*Terminal) Buffers

func (t *Terminal) Buffers() *BufferSet

Buffers returns the buffer set (normal and alt).

func (*Terminal) Cols

func (t *Terminal) Cols() int

Cols returns the current column count.

func (*Terminal) CoreService

func (t *Terminal) CoreService() *CoreService

CoreService exposes modes and the data event trigger.

func (*Terminal) Input

func (t *Terminal) Input(data string, wasUserInput bool)

Input sends data to the pty (keyboard input path).

func (*Terminal) InputHandler

func (t *Terminal) InputHandler() *InputHandler

InputHandler exposes the input handler (attr data, custom handler registration).

func (*Terminal) MouseService

func (t *Terminal) MouseService() *CoreMouseService

MouseService exposes the mouse tracking service.

func (*Terminal) OscLinkService

func (t *Terminal) OscLinkService() *OscLinkService

OscLinkService exposes registered OSC 8 hyperlinks.

func (*Terminal) Reset

func (t *Terminal) Reset()

Reset restores the terminal to its initial state.

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 current row count.

func (*Terminal) Scroll

func (t *Terminal) Scroll(eraseAttr *AttributeData, isWrapped bool)

Scroll scrolls down one row, creating a blank line (used by the input handler via the buffer service).

func (*Terminal) ScrollLines

func (t *Terminal) ScrollLines(disp int)

ScrollLines scrolls the display (negative = up).

func (*Terminal) ScrollPages

func (t *Terminal) ScrollPages(pageCount int)

ScrollPages scrolls by pages.

func (*Terminal) ScrollToBottom

func (t *Terminal) ScrollToBottom()

ScrollToBottom scrolls back to the prompt.

func (*Terminal) ScrollToLine

func (t *Terminal) ScrollToLine(line int)

ScrollToLine scrolls to an absolute line in the buffer.

func (*Terminal) ScrollToTop

func (t *Terminal) ScrollToTop()

ScrollToTop scrolls to the top of the scrollback.

func (*Terminal) Write

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

Write parses a chunk of UTF-8 encoded pty output.

func (*Terminal) WriteString

func (t *Terminal) WriteString(data string)

WriteString parses a chunk given as string.

type Theme

type Theme struct {
	Foreground          string
	Background          string
	Cursor              string
	CursorAccent        string
	SelectionBackground string
	// SelectionForeground recolors selected text. Empty leaves each cell its
	// own foreground, which is what xterm.js does by default and what keeps
	// syntax coloring readable through a selection.
	SelectionForeground string
	Black               string
	Red                 string
	Green               string
	Yellow              string
	Blue                string
	Magenta             string
	Cyan                string
	White               string
	BrightBlack         string
	BrightRed           string
	BrightGreen         string
	BrightYellow        string
	BrightBlue          string
	BrightMagenta       string
	BrightCyan          string
	BrightWhite         string
}

Theme holds the terminal colors (port of ITheme).

type Utf8ToUtf32

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

Utf8ToUtf32 decodes UTF8 byte streams into UTF32 codepoints with support for partly transmitted sequences across chunks (the port of Utf8ToUtf32).

func (*Utf8ToUtf32) Clear

func (d *Utf8ToUtf32) Clear()

Clear resets the decoder to a clean state.

func (*Utf8ToUtf32) Decode

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

Decode decodes UTF8 bytes in input to UTF32 codepoints in target, returning the number of written codepoints. target must be at least len(input) long.

type WindowOptions

type WindowOptions struct {
	RestoreWin          bool
	MinimizeWin         bool
	SetWinPosition      bool
	SetWinSizePixels    bool
	RaiseWin            bool
	LowerWin            bool
	RefreshWin          bool
	SetWinSizeChars     bool
	MaximizeWin         bool
	FullscreenWin       bool
	GetWinState         bool
	GetWinPosition      bool
	GetWinSizePixels    bool
	GetScreenSizePixels bool
	GetCellSizePixels   bool
	GetWinSizeChars     bool
	GetScreenSizeChars  bool
	GetIconTitle        bool
	GetWinTitle         bool
	PushTitle           bool
	PopTitle            bool
	SetWinLines         bool
}

WindowOptions gates the CSI t window manipulation commands (port of IWindowOptions; everything defaults to off like in xterm.js).

Jump to

Keyboard shortcuts

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