SugarAnsiParser
ANSI escape-sequence parser and state machine
Parse ANSI escape sequences into structured state transitions — SGR attributes, cursor movement, erase operations, and DEC private modes — without coupling to terminal-cell-grid concerns. This is the VT500 state machine sugar-vterm consumes for its cell-grid rendering.
Install
composer require sugarcraft/sugar-ansi-parser
Quickstart
use SugarCraft\AnsiParser\Parser\{DebugHandler, Parser};
$handler = new DebugHandler(); // records every parse action
$parser = new Parser($handler);
// Chunks may split anywhere; in-flight sequences carry across feed() calls.
$parser->feed("\x1b[1;");
$parser->feed("31mHi\x1b[0m");
$parser->flush(); // end of stream: dispatches a pending string payload
$handler->filter('csi'); // two csi entries: params [1, 31] then [0], final 'm' (109)
$handler->filter('print'); // rows with detail 'H', 'i'
To drive a cell grid, implement CsiHandler (cursor, erase, scroll, SGR, DEC modes) and OscHandler (title, hyperlink), then bridge them to the parser:
use SugarCraft\AnsiParser\Parser\{HandlerAdapter, Parser};
$parser = new Parser(new HandlerAdapter($myCsiHandler, $myOscHandler));
$parser->parseComplete($bytes); // feed() + flush() in one call
What's in the box
VT500 state machine
Parser implements the Paul Williams DEC parser and dispatches abstract Handler events: printChar, execute, csiDispatch, escDispatch, oscDispatch, dcsDispatch, sosPmApcDispatch.Partial-input safeFeed any chunk size. Incomplete sequences and UTF-8 runes wait for the next
feed(); flush() (or parseComplete()) settles a pending OSC/DCS/SOS/PM/APC string at end of stream — an in-flight CSI or ESC, and a half-finished DCS prelude, end undispatched.CSI handler interface
CsiHandler covers the renderer's working CSI set (plus CR/LF routed from C0 executes): CUU/CUD/CUF/CUB/CUP/HVP, ED/EL, SU/SD, IL/DL, ICH/DCH, REP, SCO save/restore, DECSET/DECRST, DECSTBM, TBC/CHT/CBT and SGR. HandlerAdapter translates parser events into these calls.Sub-parameters
subparams() and Parser::groupSubparameters() keep ECMA-48 colon groups apart, so CSI 4:3 m (curly underline) is not confused with CSI 4;3 m. Handlers can opt in through SubparamsAwareHandler.Bounded payloadsDCS/OSC/SOS/PM/APC payloads are capped (64 KiB by default; the third constructor argument changes it — any positive int, so smaller values tighten the cap), so a hostile stream cannot grow the parser's buffers without limit. Past the cap the excess is dropped and decoders see a truncated payload;
Codec\Iterm1337 flags it as malformed only when fewer bytes arrive than its declared size= — a payload longer than declared passes unflagged, as the check is one-way.DebugHandlerDevelopment mirror: records every action as
['type' => …, 'detail' => …] rows. The default shape is an unbounded public $log — test-fixture ergonomics on finite input; pass maxLogRows: for a long-lived mirror and the log becomes a keep-newest ring that counts every eviction in a public $dropped. filter($type) selects one kind; resetLog() clears rows and eviction counter together. Stream inspection for trusted input, never a hostile-stream sink.Null sink
NullHandler is the shipped Handler that consumes everything and does nothing, with seven bare counter accessors (printCount() … sosPmApcCount()) so even a silent sink stays observable. Deliberately not a BulkPrintHandler: a null sink always wants byte-level truth, so printCount() counts runes, never runs.Recording doubles (testing)
Support\RecordingCsiHandler ships in src/ as a final … implements CsiHandler recording test double — interface growth breaks it at compile time instead of silently drifting hand-rolled stubs. Every call (grid queries included) logs a row in the DebugHandler vocabulary; maxRows: caps the log counting drops in a public $dropped. RecordingOscHandler is the ready-made OscHandler: it stores the window title and tracks the current hyperlink pair.Limits & hostile input
- Bounded accumulation — DCS/OSC/SOS/PM/APC payloads stop at 64 KiB (the third constructor argument changes it; smaller values tighten), CSI parameter lists cap at 32 slots with each value clamped at 65535.
- Byte-space fidelity — C0 bytes arriving inside an OSC string are dropped, so a payload can differ from the raw bytes sent; the first prefix byte survives and only the last intermediate is kept (disclosed parity deviations).
- Raw accessors are untrusted —
OscHandler::title()/hyperlink(),Iterm1337::name()/args()(whose percent-decode can re-synthesize control bytes) andKittyApc::control()hand back wire text as dispatched; validate or reject before display or re-emission — the escape discipline is confined todescribe(). - UTF-8 policy splits by mode — completed runes pass verbatim by default;
$replaceMalformedsubstitutes U+FFFD and also replaces incomplete runes dropped silently in the default mode. Lone C1 bytes never reachprintChar(), but UTF-8-encoded C1 (C2 80-C2 9F) is legal text — consumers re-emitting printable text reject or replace U+0080-U+009F themselves.
Assistive / text-bridge notes
printChar()delivers codepoints, not graphemes — buffer and cluster withgrapheme_str_split()/ICU before re-voicing a stream.- Dropped bytes produce no character at all, so a reconstructed transcript may be shorter than the sender's intent; U+FFFD appears only in replacement mode.
- Hyperlinks pair: an OSC 8 event opens a span and one with an empty URI closes it; through
HandlerAdaptera malformed8;…payload closes the current link rather than being dropped.
Use it for
- ANSI stream inspection — parse escape sequences into structured events without spawning a terminal.
- Built into SugarVterm — give vterm raw bytes and it drives the machine for you.
- SGR decoding — receive every SGR parameter list, colon sub-parameters included, as the stream arrives.
Source & demos
- Source on GitHub
- Full README
- Runnable examples
- Originally inspired by charmbracelet/x/ansi (Go); SugarCraft is developed as a native PHP project.
API
| Class | Method | Description |
|---|---|---|
| Parser | __construct(Handler, bool $replaceMalformed = false, int $maxStringBuffer = 65536) | Parser bound to one handler |
| Parser | feed(bytes) / flush() / parseComplete(bytes) / reset() | Stream bytes, settle end of stream, one-shot parse, and reset (flushes an in-flight string first — it dispatches, then clears) |
| Parser | currentState(): State / subparams(): list<bool> | Current state-machine state; colon flags for the last parameter list |
| Parser | static groupSubparameters(params, flags) | Regroup a flat parameter list by its colon flags |
| Handler | printChar / execute / csiDispatch / escDispatch / oscDispatch / dcsDispatch / sosPmApcDispatch | Parse events a handler receives |
| HandlerAdapter | __construct(CsiHandler, OscHandler, ?Handler $fallback = null) | Bridges parser events to the CSI and OSC handler interfaces; unhandled and non-emulator events (ESC/DCS/SOS/PM/APC, unmapped finals, extra executes) forward to the optional fallback |
| CsiHandler | printable / cuu/cud/cuf/cub / cup / sgr / ed / el / decset / decrst / decstbm / tbc / cht / cbt / … | Emulator-facing CSI actions |
| OscHandler | title(string) / hyperlink(uri, id) | Emulator-facing OSC actions; the adapter maps OSC 0/1/2 to title and OSC 8 (including the backtick 8;URI` spelling) to hyperlink — a malformed 8; payload closes the open link instead of dropping silently |
| DebugHandler | $log / $dropped / filter(type) / resetLog() / ctor maxLogRows: | Development mirror — unbounded $log by default, keep-newest ring when maxLogRows is set; evictions counted in $dropped and resetLog() clears both |
| NullHandler | printCount() / executeCount() / csiCount() / escCount() / oscCount() / dcsCount() / sosPmApcCount() | Shipped null Handler — consumes everything, stays observable; counts runes not runs (never a BulkPrintHandler) |
| Support\RecordingCsiHandler | $log / $dropped / filter(type) / resetLog() / ctor maxRows: (grid default 25×80) | Final recording CsiHandler test double shipped in src/ so consumers autoload it instead of hand-rolling anonymous doubles |
| RecordingOscHandler | title() / hyperlink() in; lastTitle() / hyperlinkUri() / hyperlinkId() out | Ready-made OscHandler — stores the window title and the current hyperlink pair (raw, unvalidated; validate before re-emission) |
| Codec\Dcs | static parse(final, params, prefix, intermediate, data) → kind() / isSixel() / isTruncated() / describe() | Typed DCS decoder: sixel, XTVERSION, DECRQSS/PSS, tmux, truncation |
| Codec\Iterm1337 | static parse(data) / static fromDcs(final, data) | iTerm2/WezTerm 1337 inline-image + control decoder; parse() returns null when the payload is not 1337; malformed() records on a rejected-as-mine payload, never throws |
| Codec\KittyApc | static parse(data) | Kitty graphics frame decoder (null unless the frame opens with `G`, no space after the `G`): control pairs, geometry labels, payload size |