โ† All libraries

CandyAnsi

๐Ÿฌ CandyAnsi

ANSI escape-sequence parser and state machine

port of x/ansi csi-handler sgr dec-modes leaf-package

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. Used by CandyVt to drive the VT500 state machine.

Install

composer require sugarcraft/candy-ansi

Quickstart

use SugarCraft\Ansi\Parser\Parser;
use SugarCraft\Ansi\Parser\CsiHandler;
use SugarCraft\Ansi\Parser\AnsiState;

$state = new AnsiState();
$handler = new MyCsiHandler(); // implements CsiHandler
$parser = new Parser($state, $handler);

$parser->feed("\x1b[1;31m"); // CSI 1;31m โ†’ bold + red foreground
$parser->feed("Hello");
$parser->feed("\x1b[0m");   // reset

What's in the box

CSI handler interfaceComplete set of CSI dispatch methods: CUu/CUD/CUF/CUB/CUP, CHA/VPA, DECSC/DECRC, EL/ED/ECH, SU/SD, IND/RI/NEL, DECSET/DECRST, DECSTBM, TBC, CHT/CBT, and SGR.
Structured stateAnsiState holds current SGR parameters, cursor position, erase mode, DEC mode flags, and scroll region bounds โ€” parseable independently of terminal-cell-grid coupling.
Partial-input safeFeed any byte chunk size; the parser maintains internal state and only dispatches when a complete sequence is recognized.
DEC mode supportPrivate marker (0x3Cโ€“0x3F) handling for DECSET/DECRST; covers 1049 alt screen, 25 cursor visibility, 1000/1002/1003/1006 mouse, 2004 bracketed paste, 2026 sync output, 7 auto-wrap.
SGR full set16-color, bright, 256-color, truecolor for fg+bg; bold / italic / underline / strikethrough / blink / reverse / dim / hidden toggles; underline styles 4:0โ€“4:5; BCE-aware.

Use it for

Source & demos

Try the quickstart โ†’

API

ClassMethodDescription
Parserfeed(bytes)Feed raw ANSI bytes to parser
AnsiStatesgr, cursor, eraseMode, decModesCurrent parsed state
AnsiStatewithSgr(array)New state with updated SGR params
AnsiStatewithCursor(int, int)New state with cursor position
CsiHandlerprintable(string)Handle printable ASCII character
CsiHandlercuu/cud/cuf/cub(int)Cursor movement
CsiHandlercup(int, int)Cursor position (1-indexed)
CsiHandlersgr(array)Select Graphic Rendition
CsiHandlered/el(int)Erase Display / Line
CsiHandlerdecset/decrst(int, int)DEC private mode set/reset
CsiHandlerdecstbm(int, int)Set top/bottom scroll margins
CsiHandlertbc/cht/cbt(int)Tab control

Demos.

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

ANSI parse and state

ANSI parse and state

Feed raw ANSI bytes into the parser; observe structured SGR and cursor state transitions via a CsiHandler.