All 48 libraries

SugarVterm

In-memory virtual terminal emulator

vt500-parser cell-grid snapshot-tests no-pty

SugarVterm code coverage

Feed an ANSI byte stream in, query a cell grid, cursor and mode state out, without ever spawning a real terminal. sugar-vterm is the in-memory virtual terminal of the SugarCraft ecosystem. It is built on a Paul Williams VT500 state machine shared with sugar-ansi-parser, and it mirrors the design of charmbracelet/x/vt.

Install

composer require sugarcraft/sugar-vterm

Requires PHP ^8.3. The library has no runtime dependency on a real terminal, a PTY or an event loop for the synchronous API.

Quickstart

use SugarCraft\Vterm\Terminal\Terminal;

$term = Terminal::new(cols: 80, rows: 24);
$term->feed("\x1b[1;31mHello\x1b[0m world");

$screen = $term->screen();
$screen->cell(0, 0)->grapheme;       // 'H'
$screen->cell(0, 0)->sgr()->bold;     // true (sgr() never null; the $sgr property is ?Sgr — null on the renderer path)
$screen->cell(0, 0)->foreground();   // a Color (kind 1 = Indexed16, value 1 — 16-color red)

$term->feed("\x1b]2;Demo\x07");
$term->windowTitle();                 // 'Demo'

$term->feed("\x1b[?1049h");
$term->isAltScreen();                 // true

The stream is parsed incrementally, so a sequence split across two feed() calls is handled correctly. The runnable version of a feed-and-inspect flow is examples/feed-and-screenshot.php.

Concepts

A terminal program writes bytes. The emulator reads them the way a real terminal would and keeps the result as state: a grid of cells, a cursor, a set of modes (alternate screen, mouse reporting, bracketed paste, synchronized output, auto-wrap), a window title and a scrollback ring of rows that scrolled off the top. Querying that state is cheap and synchronous, and nothing is rendered until you ask for it.

Two classes share the name. SugarCraft\Vterm\Terminal\Terminal is the full emulator, with alternate screen, scrollback, OSC dispatch and the complete mode set. The root SugarCraft\Vterm\Terminal is a lightweight emulator that produces Snapshot value objects for candy-vcr's renderer. The examples in this page use the full emulator unless they say otherwise.

Common tasks

Assert on the rendered grid instead of raw bytes. Drive a TUI's view() through the emulator and check the cells it actually painted:

use SugarCraft\Vterm\Terminal\Terminal;

$term = Terminal::new(cols: 20, rows: 3);
$term->feed($app->view());

$cell = $term->screen()->cell(0, 0);
assert($cell->grapheme === 'S');
assert($term->cursor()->row === 0);

Read a row as plain text. lines() yields each row's text, and linesWithHistory() includes the scrollback above it:

$term = Terminal::new(cols: 40, rows: 8);
$term->feed("\x1b[1;1Hstatus: ok");

foreach ($term->screen()->lines() as $row => $line) {
    echo "$row: $line\n";
}

Keep a scrollback history. Scrolled-off rows are kept in a ring buffer, and withScrollbackSize() returns a terminal with a different capacity:

$term = Terminal::new(cols: 80, rows: 24)->withScrollbackSize(5000);
$term->feed(str_repeat("line\r\n", 300));
$history = $term->screen()->scrollback();

Feed captured output safely. Text captured from a pipe or a file has bare LF line endings, which the emulator treats as a cursor move without a carriage return. feedCaptured() normalizes them first:

$term = Terminal::new(cols: 80, rows: 24);
$term->feedCaptured(file_get_contents('session.log'));

Read the state a program set. Title, cursor, modes and palette are all bare accessors on the terminal:

$term->feed("\x1b]2;build #42\x07\x1b[?25l\x1b[?2004h");

$title = $term->windowTitleSanitized();   // 'build #42', control bytes stripped
$cursorShown = $term->mode()->cursorVisible;   // false
$pasteWrapped = $term->mode()->bracketedPaste; // true

What's in the box

VT500 parser15-state Paul Williams state machine, implemented upstream in sugar-ansi-parser and imported here. This library's src/Parser/ holds the handler bridges only. Handles partial input across feed() calls and CSI subparameters (: separator per VT500 spec).
Full SGR16-color, bright, 256-color, and truecolor for fg + bg. The emulator pen tracks bold / italic / underline / strikethrough / blink / reverse / dim / hidden toggles and SGR underline styles 4:0–4:5 (single / double / curly / dotted / dashed). The renderer paints the five cell-attribute bits (bold, italic, underline, reverse, strikethrough). Blink, dim and hidden are tracked but not painted. BCE is always on: erase fills inherit the current background, and there is no ?12 gate.
Cursor, erase and scrollCUU/CUD/CUF/CUB/CUP/CHA/VPA, DECSC/DECRC, EL/ED/ECH/DCH/ICH, SU/SD, IND/RI/NEL.
DEC modes1049 alt screen with cursor save, 25 cursor visibility, 1000/1002/1003/1006 mouse, 2004 bracketed paste, 2026 synchronized output (batch queue, flushed on disable), 7 auto-wrap (DECAWM).
OSC dispatch0/1/2 window title, 4 palette set, 8 hyperlinks (per-cell attribution), 52 clipboard write and read events. Every payload is attacker-supplied text kept verbatim, and consumers sanitize it before display or onward propagation.
Width-aware and combiningCJK and most emoji take 2 cells with a continuation marker. Zero-width runes (combining diacritics, variation selectors, joiners) attach to the preceding cell through Cell::$combining, so composed graphemes render in a single column.
Scrollback bufferA ring buffer (default 1000 rows) captures scrolled-off content. Read it with Screen::scrollback(), resize it with Terminal::withScrollbackSize(), and erase it with CSI 3 J.
Trust boundaryEngineered for hostile byte streams. Stored strings cap at 64 KiB, event logs at 1024 entries (drop-oldest rings), and the DEC 2026 queue replays past 16384 pending cells. Stored side-channels (window titles, OSC 8 hyperlinks, OSC 52 payloads) are kept verbatim, so consumers sanitize before display.

Use it for

  • Snapshot tests. Drive any TUI's view() through SugarVterm and assert on cell-grid state instead of raw byte strings.
  • Recording and replay. Capture feed() input and replay it deterministically.
  • Headless SSH sessions. sugar-ssh-server is pairable: it can route session bytes into feed() to run TUIs without a real PTY, but no integration ships in either package. The wiring is yours to write.

API reference

ClassMethodDescription
Terminalnew(cols, rows, scrollbackSize, buffer, cursor, mode, onFocusEvent)Create a virtual terminal. The Terminal::create() factory is deprecated: it accepts no scrollbackSize
Terminalfeed(bytes), feedCaptured(bytes)Feed ANSI bytes to the terminal. feedCaptured() normalizes bare LF to CRLF first
Terminalflush()Drains the parser's pending state
Terminalscreen(), cellAt(row, col), rowCells(row)The current cell grid, and cell or row access by position
Terminalcursor(), isWrapPending()Cursor position and the pending-wrap flag
Terminalmode()Terminal mode state (cursor visibility, mouse, bracketed paste, auto-wrap and more)
TerminalwindowTitle(), windowTitleSanitized()The OSC title, verbatim, or with control bytes stripped
Terminalpalette(), clipboardEvents(), focusEvents(), bells()Palette entries set by OSC 4, OSC 52 events, focus events and the bell count
Terminalreplies(), replyOverflowCount()Responses the emulator produced for queries, and how many were dropped at the cap
Terminalresize(cols, rows), cols(), rows()Change the grid size and read it back
TerminalwithScrollbackSize(int), withCellPixels(int $widthPx, int $heightPx)New terminal with a different scrollback capacity (at least 1), or with a cell pixel size
TerminalenableAltScreen(), disableAltScreen(), isAltScreen()Alternate-screen control. The lightweight root Terminal throws \LogicException for the first two
Screencell(row, col)The cell at a position. Out-of-bounds coordinates return the empty cell
Screenlines(), linesWithHistory()Each row's text, optionally with the scrollback above it
Screenscrollback(), diff(Screen $other)The scrollback ring, and a cell-level diff against another screen
Scrollbackpush(), all(), at(), count(), clear(), maxSize()The ring of scrolled-off rows
Cellgrapheme, sgr(), combining, foreground(), background()Cell content, style and combining marks. sgr() always returns an Sgr, while the raw $sgr property is ?Sgr
Cursorrow, col, withRow(), withCol(), at(), withVisible(), hidden()Cursor position and visibility, with immutable updates
ModecursorVisible, bracketedPaste, mouseSgr, isMouseReporting(), withAutoWrap(), withAltScreen(), withSyncUpdate()Public mode flags, with immutable with*() updates and mouse-encoding helpers
SgrunderlineStyle, withUnderlineStyle(UnderlineStyle)SGR underline style (None, Single, Double, Curly, Dotted, Dashed), mapped from CSI 4:0 to 4:5
SnapshotSnapshot::of(Terminal $t, float $time = 0.0), equals(), equalsWithTime()A frozen frame from the lightweight root Terminal, used by candy-vcr
ThemedefaultPalette(), tokyoNight(), dracula(), solarizedDark(), tokyoNightLight(), tokyoNightStorm()256-color palette with default foreground and background, and named factories
Themesall(), v1()The bundled theme catalog, and the first-release subset
HyperlinkHyperlink value objectOSC 8 target and id, recorded per cell

Only methods declared in sugar-vterm/src, or inherited from a parent declared there, are listed. A type that extends a class outside that tree, such as \RuntimeException, does not show the methods of that class.

SugarCraft\Vterm

Cell final readonly class

A single cell in the terminal grid — the one Cell for BOTH engines.

MethodSummary
__construct(string $char = ' ', public int $fg = 7, public int $bg = 0, public int $attrs = 0, public ?Sgr $sgr = null, public ?int $fgTruecolor = null, public ?int $bgTruecolor = null, public Rendition $rendition = Rendition::None, public bool $continuation = false, public ?Hyperlink $hyperlink = null, public string $combining = '', ?string $grapheme = null)
static empty(): selfThe shared empty cell — one memoised instance per process.
static continuation(self $prev): selfSecond cell of a wide character — carries no grapheme, marks continuation, and inherits the leading cell's full rendition so the phantom column paints with the same colours/attributes/line state.
withFg(int $c): self
withBg(int $c): self
withAttrs(int $flags): self
withFgTruecolor(?int $rgb): selfForeground as an exact 24-bit packed value (or null when not truecolour).
withBgTruecolor(?int $rgb): selfBackground as an exact 24-bit packed value (or null when not truecolour).
withRendition(Rendition $rendition): self
withCombining(string $combining): selfReturn a new Cell with additional combining marks appended, capped at MAX_COMBINING_PER_CELL marks per cell: once the ceiling is reached the overflow marks are silently dropped (the appended burst is truncated to whatever budget remains), so a hostile mark flood can never grow a cell unboundedly. The FIRST marks are always the retained ones. Mirrors charmbracelet/x/vt Cell::WithCombining plus the xterm per-cell combining-limit idea.
static codepoints(string $text): arrayThe Unicode codepoints of $text as an array (empty string = none). Shared counting primitive for the per-cell combining ceiling.
static codepointCount(string $text): intNumber of Unicode codepoints in $text — codepoints() sized.
sgr(): Sgr
foreground(): ?Color
background(): ?Color
fgRgb(): ?arrayExact 24-bit foreground as [r, g, b], from either the renderer's $fgTruecolor slot or an emulator SGR carrying a kind-3 Color. Null when the foreground is a palette/default colour — this is the representation-agnostic truecolour exposure the renderer path previously lacked.
bgRgb(): ?arrayExact 24-bit background as [r, g, b] — the fgRgb() twin for the background colour.
colorSgr(): stringRe-emit the cell's colours as an SGR sequence — the cell→SGR direction that makes a stored truecolour value recoverable as bytes (the round-trip the parity work pinned; image rasterizers may consume it in future). Emits 38;2;R;G;B/48;2;R;G;B for a truecolour slot and 38;5;n/ 48;5;n for a palette slot; a default (unset) colour contributes nothing. Returns '' when neither colour is set. The caller wraps this in no extra CSI m — the string is already a complete ESC [ … m.
equals(self $other): bool

Cursor final readonly class

Cursor state for the vcr renderer path.

MethodSummary
__construct(public int $row = 0, public int $col = 0, public int $shape = 0, public bool $visible = true)
at(int $row, int $col): self
withShape(int $shape): self
hidden(): self
shown(): self
equals(self $other): bool

CursorShape enum

DECSCUSR cursor shape values — CSI Ps SP q.

Cases: BlinkingBlock · SteadyBlock · BlinkingUnderline · SteadyUnderline · BlinkingBar · SteadyBar

PHP also provides cases(), from() and tryFrom().

MethodSummary
static fromInt(int $shape): self
toInt(): intReturn the raw int value for storage in Cursor::$shape.

Rendition enum

Per-line width/height rendition carried by a Cell.

Cases: None · DoubleTop · DoubleBottom · DoubleWidth

PHP also provides cases(), from() and tryFrom().

MethodSummary
isDoubleHeight(): boolTrue when the rendition draws the line taller than one row (either DECDHL half).

Snapshot final readonly class

Frozen frame from the terminal emulator.

MethodSummary
__construct(public Buffer $grid, public Cursor $cursor, public float $time, public int $revision = 0)
static of(Terminal $t, float $time = 0.0): selfCapture a frozen frame from a live terminal: the grid is deep-copied so the Snapshot cannot retro-mutate as the terminal keeps consuming.
equals(self $other): bool
equalsWithTime(self $other): boolCompare snapshots including time. Used when exact frame reproducibility at specific timestamps matters.

Terminal final class

Public terminal surface for the vcr renderer path.

MethodSummary
__construct(public readonly int $cols, public readonly int $rows, Buffer $grid, Cursor $cursor, Parser $parser, CsiHandlerImpl $csi, PenForwardingOscHandler $osc, ?Theme $theme = null)
static new(int $cols = 80, int $rows = 24, ?Theme $theme = null): self
theme(): Theme
feed(string $bytes): selfConsume bytes. MUTATES this terminal in place and returns $this for chaining — it does not produce a new instance (frames are frozen by self::snapshot(), which deep-copies the grid at capture).
feedCaptured(string $bytes): selfFeed captured program output: every newline is expanded to \r\n before the bytes reach self::feed(), applying the README's "Captured-stream gotcha (ONLCR)" normalisation for you. Existing \r\n pairs and lone \r are collapsed to one break first, so a capture with mixed terminators lands consistently. The transform is idempotent — already-CRLF bytes pass through untouched — which makes it safe over streams a producer may have pre-expanded.
flush(): voidForce any in-flight string sequence (OSC/DCS) to dispatch with its current payload and reset the parser to ground.
enableAltScreen(): neverAlt screen (DEC 1049) belongs to the full emulator path; the vcr renderer has no screen-swap machinery. These parity stubs exist so consumers written against both entry points fail loudly rather than discovering the asymmetry via a silent method-not-found.
disableAltScreen(): neverCounterpart of self::enableAltScreen() — parity stub only.
snapshot(float $time = 0.0): SnapshotFreeze the current frame: the grid is deep-copied (clone) so the Snapshot is unaffected by any later self::feed(), and the terminal's feed revision rides along for cheap change detection.
revision(): intMonotonic write counter: bumped once per self::feed() and self::flush() call. Two snapshots with equal revision and equal grid are provably the same frame without a deep compare — for feeds and flushes: a direct self::grid() mutation changes the frame without bumping this counter.
cursor(): Cursor
isWrapPending(): boolDeferred-wrap (phantom-cell) state — mirrors the emulator's \SugarCraft\Vterm\Terminal\Terminal::isWrapPending().
grid(): BufferThe LIVE mutable grid — a borrow, not a snapshot. It is the very Buffer the parser writes into: callers that mutate it directly (put()/fillRow()/shift ops) BYPASS the write bookkeeping — such a change is visible to every later grid()/cursor() read but does NOT bump self::revision() and does not move the cursor. Take a self::snapshot() for a frozen copy. (The name predates this contract; a rename to mutableGrid() would break every consumer, so the contract is documented here — Phase 5 may upgrade.)
windowTitle(): string
windowTitleSanitized(): stringThe last OSC title with control bytes neutralized — the safe form for display or onward propagation (OscHandler::sanitizeControl()). self::windowTitle() keeps the stored-verbatim contract.

Theme final class

Terminal theme with 256-color palette and default fg/bg.

MethodSummary
__construct(public readonly int $defaultFg = 7, public readonly int $defaultBg = 0, ?array $palette = null)
static defaultPalette(): arrayCanonical 0..255 xterm default palette (E742): the sixteen hand-tuned base colours followed by the shared 16..255 extension. The extension is keyed by ABSOLUTE index, so the + union lands every cube and grayscale slot at its true xterm position — a positional (0..215) cube would shift the whole region by −16 and shadow its first sixteen entries under the base block.
color(int $index): int
static tokyoNight(): self
static dracula(): self
static solarizedDark(): self
static tokyoNightLight(): selfTokyo Night Light theme variant.
static tokyoNightStorm(): selfTokyo Night Storm theme variant.
static fgIndex(int $slot): intGiven an ANSI slot 0-15, return the corresponding 256-color index for foreground.
static bgIndex(int $slot): intGiven an ANSI slot 0-15, return the corresponding 256-color index for background.
static rgb(int $index): arrayGiven a 256-color index, return [r, g, b].

Themes final class

Catalog of available terminal themes.

MethodSummary
static all(): arrayReturns the catalog of all available themes: name => Theme.
static v1(): arrayReturns the v1-ready themes (TokyoNight first).

SugarCraft\Vterm\Buffer

Buffer final class

The one 2D cell grid — shared by the emulator (\SugarCraft\Vterm\Handler\ScreenHandler) and the vcr renderer path (\SugarCraft\Vterm\Terminal).

MethodSummary
__construct(public readonly int $cols, public readonly int $rows)
dirtyRegion(): array
resize(int $cols, int $rows): selfResize the grid, preserving existing content. Columns/rows beyond the new bounds are DISCARDED — dropped rows are not fed to the scrollback ring (the emulator's resizeBuffers keeps the ring separately; a resize is a viewport change, not a scroll). The whole new grid is marked dirty so a delta renderer repaints every cell instead of trusting stale coordinates.
widenPairSpan(int $row, int $start, int $end): arrayWiden the closed column span [start, end] on $row so it never cuts a wide glyph in half: a span starting on a pair's continuation pulls left over its base; a span ending on a base whose tail sits one column right extends over the tail. This is THE erase-widening rule shared by both engines (vterm-13, ECMA-48/VT510 "double-width characters are treated as one unit" under ED/EL/ECH and the pair-atomic DCH/ICH shifts); the print path's outside-half clearing (ScreenHandler::eraseWidePartners) stays its own loop because it acts per written column rather than on a span.
clear(): selfA fresh empty grid of the same dimensions; this instance is untouched.
cell(int $row, int $col): Cell
put(int $row, int $col, Cell $cell): voidWrite a cell at the given position and extend the dirty bounding box. Out-of-bounds coordinates are ignored silently.
insertRows(int $count, int $from = 0, ?int $top = null, ?int $bottom = null): voidInsert $count blank rows at row $from, pushing the rows below it DOWN within the region [$top, $bottom]; nothing above $from moves and content overflowing $bottom is dropped (region-internal edit — the callers that model scrollback own ring feeding, not the grid).
deleteRows(int $count, int $from = 0, ?int $top = null, ?int $bottom = null): voidDelete $count rows at row $from, pulling the rows below it UP within the region [$top, $bottom] and leaving blanks at the region bottom.
each(): \GeneratorIterate all cells in row-major order.
equals(self $other): boolCell-for-cell equality over the whole grid (dimensions must match).
row(int $row): arrayRead a whole row by value.
copy(): arrayCopy the entire grid for snapshotting.

SugarCraft\Vterm\Charset

Charsets final class

Character-set designation tables (SCS) and the GL/GR translation.

MethodSummary
static translate(string $charset, string $rune): stringTranslate one rune through a designated charset.

SugarCraft\Vterm\Color

Color final readonly class

Terminal color value object.

MethodSummary
static default(): selfDefault terminal color (reset).
static indexed16(int $index): self16-color palette (0–15).
static indexed256(int $index): self256-color palette (0–255).
static truecolor(int $r, int $g, int $b): self24-bit RGB.
static fromInt(int $kind, int $value): self
red(): int
green(): int
blue(): int
equals(self $other): bool
static equalsOrBothNull(?self $a, ?self $b): boolNull-safe colour comparison: two colours match iff both are unset or both are set and equal. The single home for the pattern formerly copy-pasted across Sgr::equals() and Cell::sgrEquals(). Color is final readonly, so this static helper adds no inheritance surface.

SugarCraft\Vterm\Cursor

Cursor final readonly class

Cursor state snapshot.

MethodSummary
__construct(public int $row = 0, public int $col = 0, public bool $visible = true, public int $shape = 0, public ?int $savedRow = null, public ?int $savedCol = null)
withRow(int $row): self
withCol(int $col): self
at(int $row, int $col): selfPosition alias: row and column in one call. The canonical primitive pair is withRow()/withCol(); \SugarCraft\Vterm\Cursor::at() (the root renderer VO) carries the same verb so callers move between the two classes without renaming (vterm-09, additive-only — behaviour is identical to chaining the pair).
withVisible(bool $v): self
hidden(): selfVisibility alias for withVisible(false); mirrors \SugarCraft\Vterm\Cursor::hidden().
shown(): selfVisibility alias for withVisible(true); mirrors \SugarCraft\Vterm\Cursor::shown().
withShape(int $shape): self
save(): self
restore(): self
equals(self $other): bool

SugarCraft\Vterm\Handler

CursorHandler final class

Applies CSI cursor-movement sequences to a Cursor.

MethodSummary
apply(int $final, array $params, Cursor $cursor, Buffer $buffer, int $scrollTop = 0, int $scrollBottom = -1, bool $originMode = false): Cursor

EraseHandler final class

Erase / delete / insert handlers — EL, ED, ECH, DCH, ICH.

MethodSummary
apply(int $final, array $params, Buffer $buffer, Cursor $cursor, ?Sgr $sgr = null, ?array &$pending = null): void
blankCell(?Sgr $sgr): CellThe BCE blank: a space carrying ONLY the pen's background colour, foreground/attributes default; no background set → plain empty cell. Shared by ED/EL/ECH (fillRow), the DCH/ICH shift gaps, and the wide-partner orphan erase in ScreenHandler::eraseWidePartners(), matching xterm's application of the erase colour to those operations too.

ModeHandler final class

Applies DEC private mode set/reset (CSI ?N h / CSI ?N l) to a ScreenHandler.

MethodSummary
apply(array $params, bool $set, ScreenHandler $handler): void

OscHandler final class

Routes OSC dispatch payloads to the right ScreenHandler slot.

MethodSummary
apply(string $data, ScreenHandler $h): void
static sanitizeControl(string $raw): stringNeutralize control bytes in a stored OSC payload for display or onward propagation — the escape hatch referenced by the SECURITY NOTE above. The parser already swallows ESC, NUL, TAB and CR/LF while collecting OSC strings, but DEL (0x7F) and C1 codepoints (U+0080-U+009F — whose raw bytes include the 8-bit OSC introducer 0x9D) survive verbatim into titles and payloads, and a title can also arrive via \SugarCraft\Vterm\Terminal\Terminal::withWindowTitle() without passing through any parser at all. This strips U+0000-U+001F and U+007F-U+009F; everything else is kept, so the result is always no longer than the input. In byte mode (payload failed UTF-8 validation) bytes 0x80-0x9F are dropped whole — corrupt input is neutralized, not rescued, and lone continuation bytes there are indistinguishable from C1 controls.

ScreenHandler final class

Default Handler implementation: mutates a Buffer + Cursor + Sgr + Mode triple in response to parser actions.

MethodSummary
setSubparams(array $subparams): void
__construct(Buffer $buffer, ?Cursor $cursor = null, ?Sgr $sgr = null, ?Mode $mode = null, ?Scrollback $scrollback = null, ?\Closure $onFocusEvent = null)
printChar(string $rune): void
execute(int $byte): void
csiDispatch(int $final, array $params, int $prefix, int $intermediate): void
escDispatch(int $final, int $intermediate): void
oscDispatch(string $data): void
dcsDispatch(int $final, array $params, int $prefix, int $intermediate, string $data): void
sosPmApcDispatch(string $kind, string $data): void
replyOverflowCount(): intNumber of queued replies evicted by the ring ceilings — the overflow-detection seam for hosts that drain lazily (sugar-vterm-048).
recordClipboardEvent(array $event): voidPublic entry for OSC 52 to record a clipboard event without appending to the property directly (keeps the ring ceiling in one place).
hardReset(): voidRIS — ESC c, full reset to the power-on state.
softReset(): voidDECSTR — CSI ! p, soft reset.
displayAlignmentTest(): voidDECALN — ESC # 8, screen-alignment pattern.
resizeBuffers(int $cols, int $rows): voidResize the active Buffer and, when alt-screen state is saved, the saved main Buffer to the new dimensions, preserving content overlap.
setCursorVisible(bool $visible): voidDEC 25 (DECTCEM) cursor visibility — the ONLY write path for this bit.
enterAltScreen(): voidEnter the alt screen (DEC 1049 set). Saves the current Buffer + Cursor + Sgr + SCS designations + origin mode and swaps in a fresh blank Buffer of the same size. This is the AUX save slot — the DECSC/CSI s GENERAL slot is never consumed by it (xterm keeps the two independent; less saving with ESC 7 before entering alt must still find its rendition on the way back). The companions only PARK for the duration so the alt screen starts with its own empty slot, matching xterm's per-screen saved cursor. The DECSTBM scroll region rides the same save: the alt screen starts on full margins and a DECSTBM issued inside alt never leaks back to the main screen.
leaveAltScreen(): voidLeave the alt screen (DEC 1049 reset). Restores the saved Buffer + Cursor + Sgr + SCS + origin mode + DECSTBM region. No-op if not currently in the full-swap (or upgraded-to-full) alt mode.
enterAltScreenNoSave(): voidEnter the alt screen without saving cursor or SGR (DECSET 47, 1047). Only swaps the buffer — cursor visibility is preserved. Idempotent within the same variant.
leaveAltScreenNoSave(): voidLeave the alt screen (DECSET 47, 1047 reset). Restores the saved Buffer only. Cursor and SGR are NOT restored (they were not saved).
enterAltScreenCursorOnly(): voidEnter the alt screen with cursor save only (DECSET 1048). Saves cursor position but NOT buffer or SGR. The buffer is swapped to a fresh blank one and cursor is reset to origin, keeping its DECTCEM visibility and DECSCUSR shape. On exit, only the cursor is restored.
leaveAltScreenCursorOnly(): voidLeave the alt screen (DECSET 1048 reset). Restores cursor position only. Buffer and SGR are NOT restored (they were not saved).
__clone(): voidDeep-copy on clone: PHP's default semantics would leave the clone writing THROUGH into the original's grid and scrollback ring, so clone $terminal (the snapshot/rewind idiom every consumer reaches for) silently corrupted the state it was meant to preserve.

ScrollHandler final class

Vertical scrolling primitives — SU/SD plus IND/RI/NEL.

MethodSummary
applyCsi(int $final, array $params, Buffer $buffer, int $scrollTop, int $scrollBottom): voidApply a scroll CSI (SU = 'S', SD = 'T').
index(Buffer $buffer, Cursor $cursor, int $scrollTop, int $scrollBottom): CursorIND (index) — move down, scroll up if at the bottom of the region.
reverseIndex(Buffer $buffer, Cursor $cursor, int $scrollTop, int $scrollBottom): CursorRI (reverse index) — move up, scroll down if at the top of the region.
nextLine(Buffer $buffer, Cursor $cursor, int $scrollTop, int $scrollBottom): CursorNEL (next line) — CR + IND.
insertLines(Buffer $buffer, int $scrollTop, int $scrollBottom, int $from, int $count): voidIL — insert $count blank lines starting at row $from, shifting the rows below it down inside the DECSTBM region [top, bottom].
deleteLines(Buffer $buffer, int $scrollTop, int $scrollBottom, int $from, int $count): voidDL — delete $count lines starting at row $from, pulling rows below up inside the DECSTBM region; blanks land at the region bottom.
scrollUp(Buffer $buffer, int $scrollTop, int $scrollBottom, int $count): voidScroll the region up by $count rows (SU).
scrollDown(Buffer $buffer, int $scrollTop, int $scrollBottom, int $count): voidScroll the region down by $count rows (SD).

SgrHandler final class

Applies CSI m (Select Graphic Rendition) parameters to an Sgr value.

MethodSummary
apply(array $params, Sgr $current, ?array $subparams = null): SgrApply a CSI m parameter list to the current SGR state.

TabHandler final class

Horizontal tab-stop arithmetic.

MethodSummary
static defaults(int $cols): arrayBuild the default tab-stop set: every 8 columns starting at 8.
forward(int $col, array $stops, int $cols): intMove forward to the next tab stop after $col, clamping at the right edge if no stop is set.
backward(int $col, array $stops): intMove backward to the previous tab stop before $col, clamping at 0.
applyCsi(int $final, array $params, int $col, array $stops, int $cols): intApply CSI I (CHT) or CSI Z (CBT) — repeat forward/backward N times.
clear(int $mode, int $col, array $stops): arrayTBC (CSI g): clear tab stops.

OSC 8 hyperlink metadata attached to cells.

MethodSummary
__construct(public string $id = '', public string $uri = '')
static fromRaw(string $id, string $uri): self
equals(self $other): bool

SugarCraft\Vterm\Mode

Mode final readonly class

DEC mode flags snapshot.

MethodSummary
__construct(public bool $cursorVisible = true, public bool $bracketedPaste = false, public bool $mouseUtf8 = false, public bool $mouseSgr = false, public bool $mouseUrxvt = false, public bool $mouseAny = false, public bool $mouseHighlights = false, public bool $mouseCellMotion = false, public bool $syncUpdate = false, public bool $mouseExtended = false, public int $altScreenVariant = self::ALT_NONE, public bool $autoWrap = true, public bool $originMode = false, public int $cursorShape = 0, public bool $reportFocusEvents = false)
withAltScreen(bool $v): self
withAltScreenVariant(int $variant): selfSet the alt screen variant directly (modes 47, 1047, 1048, 1049).
isAltScreen(): boolReturns true if any alt screen variant is active (variant != ALT_NONE).
withCursorVisible(bool $v): self
withMouseUtf8(bool $v): selfDEC 1005 — UTF-8 coordinate form flag (independent, vterm-12).
withMouseSgr(bool $v): selfDEC 1006 — SGR coordinate form flag (independent, vterm-12).
withMouseUrxvt(bool $v): selfDEC 1015 — urxvt coordinate form flag (independent, vterm-12).
effectiveMouseEncoding(): MouseEncodingThe encoder a report emitted NOW would use (DEC 1005/1006/1015).
withMouseHighlights(bool $v): self
withMouseAny(bool $v): self
withMouseCellMotion(bool $v): self
withMouseExtended(bool $v): self
isMouseReporting(): boolTrue while ANY mouse tracking mode is armed (DEC 1000/1001/1002/1003).
withBracketedPaste(bool $v): self
withSyncUpdate(bool $v): self
withAutoWrap(bool $v): selfSet DECAWM auto-wrap mode.
withOriginMode(bool $v): selfSet DECOM origin mode.
withCursorShape(int $v): selfSet DECSCUSR cursor shape.
withReportFocusEvents(bool $v): selfSet focus event reporting mode.
equals(self $other): bool

MouseEncoding enum

Mouse report coordinate encoding selected by the DEC 100x/101x family.

Cases: Default · Utf8 · Sgr · Urxvt

PHP also provides cases(), from() and tryFrom().

SugarCraft\Vterm\Msg

FocusInMsg final readonly class

Focus-in event — terminal received focus (CSI I).

FocusOutMsg final readonly class

Focus-out event — terminal lost focus (CSI O).

SugarCraft\Vterm\Parser

CsiHandlerImpl final class

CSI handler for the vcr renderer path.

MethodSummary
__construct(private Buffer $grid, private Cursor $cursor, private Theme $theme)
grid(): Buffer
cursor(): Cursor
wrapPending(): boolDeferred-wrap (phantom-cell) state — mirrors the emulator's Terminal\Terminal::isWrapPending().
setHyperlink(?Hyperlink $hyperlink): voidSet the pen's active OSC 8 link ($hyperlink); null closes it. Called by PenForwardingOscHandler on every OSC 8 dispatch.
hyperlink(): ?HyperlinkThe pen's currently active OSC 8 link, or null when none is open.
setSubparams(array $subparams): voidReceive the ECMA-48 sub-parameter continuation flags for the parameter list about to be dispatched. RendererHandler — the renderer path's push-reachable \SugarCraft\AnsiParser\Parser\SubparamsAwareHandler sink — forwards the parser's push here so SGR can tell CSI 4 : 3 m (curly underline) from CSI 4 ; 3 m (underline + italic). Never pushed (direct construction, or the raw sugar-ansi-parser HandlerAdapter) leaves $subparams null and SGR keeps the flat-list behaviour.
printable(string $grapheme): void
cuu(int $count = 1): void
cud(int $count = 1): void
cuf(int $count = 1): void
cub(int $count = 1): void
cup(int $row, int $col): void
hvp(int $row, int $col): void
sgr(array $params): void
gridRows(): int
gridCols(): int
ed(int $mode = 0): void
el(int $mode = 0): void
decset(int $mode, int $prefix = 0): void
decrst(int $mode, int $prefix = 0): void
decstbm(int $top, int $bottom): void
tbc(int $mode = 0): void
cbt(int $count = 1): void
cht(int $count = 1): void
cr(): voidCR — carriage return: move cursor to column 0 (row unchanged). Column motion disarms the deferred wrap (xterm carriage_return).
lf(): voidLF — line feed: advance cursor down one row, scrolling the scroll region if the cursor is at scrollBottom. Handles VT (0x0B) and FF (0x0C) the same way. Vertical motion consumes the phantom cell (emulator index()).
su(int $count = 1): voidSU — Scroll Up (CSI S). Scroll the scroll region up $count lines, introducing blank lines at the bottom. Cursor position unchanged.
sd(int $count = 1): voidSD — Scroll Down (CSI T). Scroll the scroll region down $count lines, introducing blank lines at the top. Cursor position unchanged.
il(int $count = 1): voidIL — Insert Line (CSI L). Insert $count blank lines at the cursor row, shifting existing lines down within the scroll region. No-op when the cursor sits outside the scroll region. On success the cursor homes to column 0 on its row — matching the emulator's insertLines() (VT500 §IL "cursor to home position"; charm keeps the phantom armed against the OLD margin, so column-home disarms it — see ScreenHandler::insertLines).
dl(int $count = 1): voidDL — Delete Line (CSI M). Delete $count lines at the cursor row, shifting lines below up within the scroll region. No-op when the cursor sits outside the scroll region. Cursor homes to column 0 like il(). (The emulator additionally pushes deleted rows into its scrollback when the region spans the screen; the renderer has no scrollback, so its visible-grid edit is identical.)
ich(int $count = 1): voidICH — Insert Character (CSI @). Insert $count blank cells at the cursor, shifting the rest of the line right; cells pushed past the right edge are dropped. Cursor position unchanged.
dch(int $count = 1): voidDCH — Delete Character (CSI P). Delete $count cells at the cursor, shifting the rest of the line left and blanking the vacated right edge. Cursor position unchanged.
rep(int $count = 1): voidREP — Repeat (CSI b). Replay the last printed graphic grapheme $count times, bounded to one screen-full: a REPeat never legitimately writes more than Buffer capacity ($cols * $rows) printables, so CSI 65535 b on an 80x24 grid costs at most 1920 writes. The ceiling bounds hostile work; an unbounded replay would keep scrolling the same screen rewrite after rewrite. No-op when nothing printable has been emitted yet.
scosc(): voidSCOSC — SCO Save Cursor (CSI s). Remembers the cursor position AND the active pen: the emulator's GENERAL DECSC slot restores position + rendition + designations (w4-vt), and the renderer's expressive range for that snapshot is the fg/bg/attrs triple.
scorc(): voidSCORC — SCO Restore Cursor (CSI u). Restore the cursor (and pen) saved by SCOSC; no-op when nothing was saved. A position change on the way back disarms the phantom cell (emulator parity: ScreenHandler routes CSI s/CSI u to saveCursor()/restoreCursor() directly, DECRC clearing the wrap flag the same way graphic-position moves do). When the slot is empty (no prior SCOSC) the cursor STAYS PUT here — the emulator's Cursor::restore() does the same (savedRow ?? row); xterm homes to 0,0 instead, a deliberate and parity-safe divergence on both engines.
escIndex(): voidESC D — IND (index): the vertical twin of LF. Route to lf(), which shares the emulator's index() behaviour (consume the phantom cell, scroll the region at its bottom edge).
escNextLine(): voidESC E — NEL (next line): carriage return + index. Mirrors the emulator's \SugarCraft\Vterm\Handler\ScreenHandler::nextLine().
escReverseIndex(): voidESC M — RI (reverse index): up one line, scrolling the region down when already at the top. Vertical-only motion: like the emulator, the phantom cell is deliberately left armed here.
escSetTabStop(): voidESC H — HTS (hard tab stop). Sets a stop at the cursor column, gated to the grid width exactly like the emulator's \SugarCraft\Vterm\Handler\ScreenHandler::setTabStop(); the renderer shares its TabHandler model (see tbc()).
escSaveCursor(): voidESC 7 — DECSC (save cursor). Same GENERAL slot as SCO CSI s (scosc()): position + pen triple + truecolour. The renderer stores no charsets/DECOM, so its snapshot is the expressive-range subset the emulator's save also collapses to under grid normalisation.
escRestoreCursor(): voidESC 8 — DECRC (restore cursor); twin of escSaveCursor().
escResetToInitialState(): voidESC c — RIS (hard reset). Clears the grid, restores the cursor to its power-on value object (home + DECTCEM visible + default shape — the emulator's hardReset() builds a new Cursor(); homing with Cursor::at() kept a CSI ? 25 l hide across the reset), drops the pen (palette + truecolour + the OSC 8 link + the DECSC slot) and the REP memory, restores the full-page scroll region and re-enables DECAWM — the renderer's expressive-range match for the emulator's \SugarCraft\Vterm\Handler\ScreenHandler::hardReset(). Scrollback/alt-screen/charsets have no renderer counterpart. Tab stops are rebuilt to the defaults (emulator hardReset parity, ScreenHandler::defaults route). Clearing $lastPrintable is renderer-local hygiene: the emulator never dispatches REP at all, so post-RIS CSI b printing nothing is the agreement xterm/VT510 full-reset semantics demand ("no graphic was the last printable").
escLineRendition(int $final): voidESC # {3,4,5,6} — the DEC "hash" line-rendition family.

PenForwardingOscHandler final class

Pen-forwarding OSC handler for the vcr renderer path.

MethodSummary
__construct(private readonly ?CsiHandlerImpl $sink = null)
title(string $title): void
hyperlink(string $uri, string $id): voidOSC 8 open/close. The sugar-ansi-parser parser contract is that an empty $uri CLOSES the current link (xterm ctlseqs: OSC 8 ; params ; URI, "an empty URI ... terminates the current hyperlink"), so the pen (and every cell printed afterwards) returns to unlinked.
lastTitle(): string
currentHyperlink(): ?HyperlinkThe link currently open on this handler, or null after a close.

RendererHandler final class

Renderer-path Handler that finally routes ESC bytes to the grid.

MethodSummary
__construct(private readonly CsiHandlerImpl $csi, private readonly HandlerAdapter $delegate)
setSubparams(array $subparams): voidThe parser pushes the ECMA-48 colon continuation flags here — this decorator, not the wrapped HandlerAdapter, is the object handed to \SugarCraft\AnsiParser\Parser\Parser::__construct(), so it is the only handler the capability check can see. Forward them down to the concrete CsiHandlerImpl whose sgr() needs them to tell CSI 4 : 3 m (curly underline) from CSI 4 ; 3 m (underline + italic): the parser calls this immediately before the same-call-chain csiDispatch().
printChar(string $rune): void
execute(int $byte): void
csiDispatch(int $final, array $params, int $prefix, int $intermediate): void
oscDispatch(string $data): void
dcsDispatch(int $final, array $params, int $prefix, int $intermediate, string $data): void
sosPmApcDispatch(string $kind, string $data): void
escDispatch(int $final, int $intermediate): voidThe one event the shared adapter dropped on the floor.

SugarCraft\Vterm\Screen

Screen final readonly class

Readonly snapshot of the terminal grid, optionally carrying the scrollback ring that holds the scrolled-off rows.

MethodSummary
__construct(private array $grid, public readonly int $cols, public readonly int $rows, private ?Scrollback $scrollback = null)
static fromBuffer(Buffer $buf, ?Scrollback $scrollback = null): selfBuild a Screen snapshot from the current Buffer state.
scrollback(): ?ScrollbackReturn the scrollback buffer holding rows that have scrolled off-screen. Null when this screen was composed via self::fromBuffer() without a ring; the full Terminal\Terminal::screen() path always wires one.
cell(int $row, int $col): Cell
diff(self $other): arrayCompare two screens and return only the changed cells.
lines(): \GeneratorIterate rows as grapheme strings (continuation cells skipped).
linesWithHistory(): \GeneratorText extraction across the scrollback ring AND the visible screen: rows pushed off the top first (oldest to newest), then every visible line. Keys run 0..n continuously. With no ring attached — or nothing ever scrolled — this yields exactly self::lines().

Scrollback final class

Ring buffer that stores rows scrolled off the top of the screen.

MethodSummary
__construct(private readonly int $maxSize = 1000)
push(array $row): voidAppend a row to the buffer.
all(): \GeneratorIterate the ring from oldest to newest, one row at a time.
at(int $offset): ?arrayReturn the row at the given offset from the oldest entry (0 = oldest).
count(): int
clear(): voidDrop every stored row (ED 3 — "clear scrollback", xterm ctlseqs CSI 3 J). The ring keeps its capacity; head/tail/count rewind to a pristine state so subsequent pushes append from the start again.
maxSize(): int

SugarCraft\Vterm\Sgr

Sgr final readonly class

Select Graphic Rendition flags — bold, italic, underline, etc.

MethodSummary
__construct(public bool $bold = false, public bool $italic = false, public bool $underline = false, public UnderlineStyle $underlineStyle = UnderlineStyle::None, public bool $strikethrough = false, public bool $blink = false, public bool $reverse = false, public bool $dim = false, public bool $hidden = false, public bool $invisible = false, public ?Color $foreground = null, public ?Color $background = null)
static empty(): self
withBold(bool $v): self
withItalic(bool $v): self
withUnderline(bool $v): self
withUnderlineStyle(UnderlineStyle $style): self
withStrikethrough(bool $v): self
withBlink(bool $v): self
withReverse(bool $v): self
withDim(bool $v): self
withHidden(bool $v): self
withForeground(?Color $c): self
withBackground(?Color $c): self
equals(self $other): bool

UnderlineStyle enum

SGR underline style — single, double, curly, dotted, dashed, or none.

Cases: None · Single · Double · Curly · Dotted · Dashed

PHP also provides cases(), from() and tryFrom().

SugarCraft\Vterm\Terminal

Terminal final class

Public terminal facade.

MethodSummary
__construct(int $cols, int $rows, ?Buffer $buffer = null, ?Cursor $cursor = null, ?Mode $mode = null, int $scrollbackSize = 1000, ?\Closure $onFocusEvent = null)
static new(int $cols = 80, int $rows = 24, ?int $scrollbackSize = null, ?Buffer $buffer = null, ?Cursor $cursor = null, ?Mode $mode = null, ?\Closure $onFocusEvent = null): selfCanonical factory — mirrors the constructor params directly, all optional and defaulted: focus-event wiring and a pre-set DEC mode (or injected buffer/cursor) never require positional fillers.
static create(int $cols = 80, int $rows = 24): self
feed(string $bytes, ?callable $respond = null): voidDrive bytes through the parser.
feedCaptured(string $bytes, ?callable $respond = null): voidFeed captured program output: every newline is expanded to \r\n before the bytes reach self::feed(), applying the README's "Captured-stream gotcha (ONLCR)" normalisation for you. Existing \r\n pairs and lone \r are collapsed to one break first, so a capture with mixed terminators lands consistently. The transform is idempotent — already-CRLF bytes pass through untouched — which makes it safe over streams a producer may have pre-expanded. The $respond query→reply channel behaves exactly as in self::feed().
replies(): arrayDrain the queued terminal→host replies (DA1/DA2, DECRPM, CPR, XTWINOPS …) in request order. OSC-sourced requests are NOT in this queue: an OSC 52 read is recorded in the clipboard event log and the palette query forms are ignored — this library never answers them itself, see self::clipboardEvents().
replyOverflowCount(): intReplies evicted by the ring ceilings since construction (sugar-vterm-048): nonzero means answers were dropped before any drain saw them.
feedAsync(string $bytes): PromiseInterfaceAsync form of feed(): parse $bytes and resolve with the terminal→host answer bytes this feed produced (plus any earlier ones still queued), concatenated in request order — exactly the byte stream $respond would have received from feed(), delivered as the promise value instead of a callback.
feedStream(ReadableStreamInterface $input, ?callable $respond = null, ?CancellationToken $cancellation = null): PromiseInterfacePump a stream of terminal input through the parser as it arrives.
flush(): voidForce any in-flight string sequence (OSC/DCS/SOS/PM/APC) to dispatch with its current payload and reset to ground. Useful at end-of-stream when you can't wait for a real terminator byte.
screen(): ScreenFull-screen snapshot. Rebuilds a detached copy of the grid on every call — O(rows × cols) array wrappers (cells are shared readonly objects; the copy separates on write) — so a poll loop that only needs one row should use rowCells() instead.
cellAt(int $row, int $col): CellRead one live cell without rebuilding the screen snapshot.
rowCells(int $row): arrayRead one live row by value without rebuilding the screen snapshot: streaming consumers (site-map diffs, scrollback pumps) never pay the full-screen rebuild of screen().
cursor(): Cursor
isWrapPending(): boolTrue while a DECAWM deferred wrap is armed: a glyph has landed in the last column and the cursor is parked there until the next graphic print consumes it (mirrors xterm _wrapnext / charmbracelet x/vt Emulator.atPhantom).
mode(): Mode
windowTitle(): ?string
windowTitleSanitized(): ?stringThe window title with control bytes neutralized — the safe form for display or onward propagation (OscHandler::sanitizeControl()). self::windowTitle() keeps the stored-verbatim contract.
palette(): array
clipboardEvents(): arrayClipboard events recorded from OSC 52 sequences — DRAIN semantics.
focusEvents(): arrayFocus events recorded while DECSET 1004 was active (CSI I / CSI O).
bells(): intNumber of bell characters (BEL 0x07) the stream has produced.
resize(int $cols, int $rows): void
cols(): intLive grid width, read straight from the handler's buffer — the current value after a self::resize(), not the constructor echo, and without the O(rows × cols) rebuild a screen() costs.
rows(): intLive grid height; same direct-read contract as self::cols().
__clone(): voidSnapshot clone (w4-vt deep-clone semantics): a fresh Parser starts in Ground, so any in-flight string sequence (partial OSC/DCS payload, partial UTF-8 rune) is intentionally dropped — the clone captures committed state only. ScreenHandler::__clone() deep-copies the mutable Buffer/Scrollback (and the saved alt-state buffer) so the clone can never write through into this terminal's grid. The alt-screen saved slots ride that deep copy.
withTabStops(array $cols): selfReplace the active tab stops with explicit column indices.
withScrollbackSize(int $size): selfReturn a new Terminal with a different scrollback buffer size.
withCellPixels(int $widthPx, int $heightPx): selfReturn a new Terminal reporting the given nominal cell pixel size in XTWINOPS 14t/16t replies. The emulator renders no font, so the classic 8×16 defaults are advisory; mosaic's probeFontSize() only consumes them as cell/window ratios.
enableAltScreen(): voidProgrammatically enter the alternate screen buffer (DEC 1049 mode). Saves the main screen buffer, cursor, and SGR state.
disableAltScreen(): voidProgrammatically leave the alternate screen buffer. Restores the main screen buffer, cursor, and SGR state.
isAltScreen(): boolReturns true if the alternate screen buffer is currently active.

Configuration and limits

The library reads no environment variables and no configuration file. Its tunables are constructor and with*() arguments, plus hard limits that protect the emulator from hostile streams:

OptionTypeDefaultEffect
cols, rowsint80, 24Grid size, changed later with resize()
scrollbackSizeint1000 rowsRing capacity for scrolled-off rows, set with withScrollbackSize()
SugarCraft\Vterm\Terminal::MAX_STRING_BUFFERbytes64 KiBCap on one OSC, DCS or APC payload. Excess bytes are dropped
Event logsentries1024Drop-oldest rings for clipboard, focus and similar events
DEC 2026 queuepending cells16384Past this budget a partial flush lands
withCellPixels()pixelsnoneCell pixel size, set on a new terminal

Theming

Theme is a 256-color palette with a default foreground and background. Use one of the named factories, or build your own from a palette, and pass it to the root Terminal::new() with its ?Theme argument:

use SugarCraft\Vterm\Terminal;
use SugarCraft\Vterm\Theme;

$vt = Terminal::new(cols: 80, rows: 24, theme: Theme::tokyoNight());

The bundled catalog is available through Themes::all(), and Themes::v1() returns the first-release subset. The theme supplies the 256-color palette and the default foreground and background.

Examples

  • examples/feed-and-screenshot.php: feeds a scripted ANSI stream and prints the resulting cell grid, the window title, the cursor position and the hyperlink span. It sanitizes the echoed title, rows and hyperlink with Sanitize::untrusted() first.
php examples/feed-and-screenshot.php

The demo GIF further down this page is rendered in CI from the tape at .vhs/snapshot-demo.tape.

Testing

Run the suite from the library root with PHPUnit 10:

cd sugar-vterm && composer install && vendor/bin/phpunit

SnapshotTest.php pins rendered output, ReadmeSnippetsTest.php runs the code samples in the README so they cannot drift, and AllocationTest.php covers allocation behavior. Parser behavior that the emulator inherits is covered in sugar-ansi-parser.

Troubleshooting

SymptomCause and fix
Captured text stacks diagonally, each line starting further rightBare LF moves the cursor down without returning to column 0. Use feedCaptured(), or normalize \n to \r\n before feed(). A real terminal does this translation for you (ONLCR), which a capture does not get.
The window title contains escape bytes or looks like another program's outputwindowTitle() returns the attacker-supplied text verbatim. Use windowTitleSanitized() for control bytes, and Sanitize::untrusted() before printing anything to a real terminal.
lines() output renders control sequences on a real terminalThe grid holds whatever the stream wrote. Treat the output as hostile and sanitize it before echoing, as the example does.
enableAltScreen() throws LogicExceptionThe root Terminal does not model the alternate screen. Use SugarCraft\Vterm\Terminal\Terminal, which does.
The scrollback is empty after a long streamCSI 3 J erases it, and the ring holds only the last scrollbackSize rows. Raise the capacity with withScrollbackSize() if you need more history.
A snapshot looks stale after you edit the grid directlyThis applies to the lightweight root SugarCraft\Vterm\Terminal, which has revision(), grid() and snapshot(); the default emulator on this page does not. On the root class, revision() counts only feed() and flush() calls, so a direct grid() mutation is invisible to it. Go through feed(), or compare snapshots by value.
Long OSC payloads are cut shortPayloads cap at 64 KiB. Anything past the cap is dropped, and the tail of an overlong title or clipboard write is lost.
Static analysis flags a call to Terminal::create()The factory is marked deprecated and takes no scrollbackSize. Use Terminal::new().

Trust boundary and hostile input

The byte stream is untrusted input. The emulator bounds every buffer it fills: string payloads, event logs, the synchronized-output queue and the reply queue all have fixed caps, and the parser refuses to grow past them. Everything the stream sets as text (titles, hyperlink targets, clipboard payloads) is stored verbatim, because a faithful emulator has to report what the program sent. Sanitizing is the consumer's job, and Sanitize::untrusted() is the function to use before display or before forwarding.

Architecture

LayerClassRole
FacadeTerminal\TerminalOwns a parser and a screen handler. feed() drives bytes in
ParserSugarCraft\AnsiParser\Parser\ParserVT500 state machine, owned by sugar-ansi-parser and consumed here
HandlersHandler\ScreenHandler, CursorHandler, EraseHandler, ScrollHandler, SgrHandler, ModeHandler, TabHandler, OscHandlerEach family of sequences updates one part of the state
Parser bridgeParser\CsiHandlerImpl, Parser\OscHandlerImplImplement the sugar-ansi-parser CsiHandler and OscHandler interfaces for this emulator
StateBuffer, Cursor, Mode, ScrollbackThe grid, the cursor, the mode flags and the scrolled-off rows
SnapshotTerminal (root), SnapshotThe lightweight emulator and its frozen frames, used by candy-vcr

Upstream mapping

Charmbracelet sourceSugarCraft portNotes
charmbracelet/x/vtTerminal\Terminal, Screen, ModeThe emulator design, with its state split into cursor, mode, grid and scrollback
charmbracelet/x/ansisugar-ansi-parserThe parser side of the design. The state machine and the handler interfaces live in that package
Paul Williams, DEC parser state diagramsugar-ansi-parser ParserThe VT500 state machine that both libraries follow

Changelog and versioning

The library has no separate changelog file yet. Its history is the commit log of sugar-vterm/ in detain/sugarcraft, and that log is the record of what changed and why.

  • sugar-ansi-parser: the VT500 parser this emulator is built on.
  • sugar-cellbuffer: the immutable cell-grid and diff model. It is separate from this package's mutable grid by design.
  • candy-vcr: the tape renderer that uses the lightweight root Terminal to produce its frames.

Source & demos

Try the quickstart →

Demos

VHS-recorded GIFs of every example shipped with the library. Regenerated automatically on every push that touches the source.

A scripted ANSI byte stream fed to a virtual terminal; the cell grid prints back showing colors, cursor position, and a hyperlink span

Feed and screenshot

An ANSI byte stream feeds into a Terminal; the cell grid prints back as a screenshot, with window title, cursor position, and hyperlink span. The GIF autoplays and cannot be paused by reduced-motion CSS. For a still, run php examples/feed-and-screenshot.php.