All 48 libraries

SugarCellBuffer

Cell-grid value objects for terminal rendering

inspired by charmbracelet/x buffer cell-grid data-model

SugarCellBuffer code coverage

Immutable Buffer (2-D cell grid) and Cell (rune, style, hyperlink, width) value objects: the shared data model that SugarCraft renderers paint into. Each mutation returns a new buffer, Buffer::diff() reduces two frames to the minimal operation list, and DiffEncoder turns that list into a self-contained ANSI byte stream. It mirrors the terminal cell buffer of charmbracelet/x/cellbuf, with the mutable grid replaced by value semantics.

Install

composer require sugarcraft/sugar-cellbuffer

Requires PHP ^8.3. The package ships only a dev-master line on Packagist, so consumers without minimum-stability: dev pin it explicitly with composer require sugarcraft/sugar-cellbuffer:@dev. Inside the monorepo, a path repository on the sugar-cellbuffer/ directory is the alternative.

Quickstart

<?php

require 'vendor/autoload.php';

use SugarCraft\CellBuffer\Buffer;
use SugarCraft\CellBuffer\Cell;
use SugarCraft\CellBuffer\Position;
use SugarCraft\CellBuffer\Region;

// Create a 20x3 buffer filled with blank cells.
$buf = Buffer::new(20, 3);

// Set a cell at (col=5, row=1).
$buf = $buf->withCellAt(5, 1, Cell::new('H'));

// Blit a seeded 2x2 sub-buffer at origin — seeding matters: blitting an
// all-blank sub-buffer over blank cells is a visible no-op.
$sub = Buffer::new(2, 2);
$sub = $sub->withCellAt(0, 0, Cell::new('A'))->withCellAt(1, 0, Cell::new('B'));
$sub = $sub->withCellAt(0, 1, Cell::new('C'))->withCellAt(1, 1, Cell::new('D'));
$buf = $buf->withRegion(Region::new(Position::new(0, 0), 2, 2), $sub);

// Read a cell back.
$cell = $buf->cellAt(5, 1);
echo $cell->rune(); // 'H'

// Access dimensions.
echo $buf->width();  // 20
echo $buf->height(); // 3

Coordinates are zero-based (col, row). The CUP sequences the encoders emit are one-based, and toAnsi() ends each row with a bare LF, so write "\r\n" yourself when the output goes to a raw-mode terminal. The runnable version of this flow is examples/basic.php.

Concepts

A Buffer is a fixed width × height grid of Cell values stored row-major. Nothing is edited in place: withCellAt(), withRegion(), fill() and applyDiff() each return a new Buffer, so a previous frame stays valid while the next one is built. That is what makes frame-to-frame diffing cheap to reason about: you keep the last frame and diff the new one against it.

A Cell holds one grapheme as its rune, an optional Style (the pen), an optional Hyperlink (OSC 8), and a width. Width 1 is a normal cell, width 2 is a wide lead (CJK, many emoji) that owns the next column through a width-0 continuation cell, and larger widths are single run-length spans. The writing API keeps those pairs intact, so a half-pair never survives a public mutation.

Common tasks

Paint a frame and emit only what changed. Keep the previous frame and encode the difference in one call:

$bytes = $curr->diffToAnsi($prev);   // CUP + SGR + literal runs, no full repaint
// or, when the op list is needed for inspection:
$ops   = $curr->diff($prev);
$bytes = (new \SugarCraft\CellBuffer\Diff\DiffEncoder())->encode($ops);

Build a frame in one pass. BufferBuilder is the mutable scratch for bulk work, and toBuffer() freezes it back into an immutable Buffer:

use SugarCraft\CellBuffer\Cell;
use SugarCraft\CellBuffer\Position;
use SugarCraft\CellBuffer\Region;
use SugarCraft\CellBuffer\Buffer;

$builder = Buffer::builder(10, 2)
    ->fillRect(Region::new(Position::new(0, 0), 10, 1), Cell::new('-'))
    ->setCellAt(0, 1, Cell::new('>'));
$frame = $builder->toBuffer();

Place a wide glyph. Declare the width explicitly. Width is never measured for you, and withCellAt() writes the continuation partner to the right:

use SugarCraft\CellBuffer\Buffer;
use SugarCraft\CellBuffer\Cell;

$buf = Buffer::new(4, 1)->withCellAt(1, 0, Cell::new('中', null, null, 2));
// (1,0) carries the lead; (2,0) is now a continuation with width 0.
$buf->cellAt(2, 0)->width(); // 0

Read a style back from SGR. Style::fromSgr() parses an SGR parameter string into a pen, and toAnsi() writes the pen back out:

use SugarCraft\CellBuffer\Style;

$pen = Style::fromSgr('1;38;5;196');   // bold, 256-color foreground
$pen?->hasBold();                     // true
echo $pen?->toAnsi();                 // a full SGR sequence, reset first

Attach a clickable link. Hyperlinks are validated when they are constructed, so hostile control bytes never reach the wire through this type:

use SugarCraft\CellBuffer\Cell;
use SugarCraft\CellBuffer\Hyperlink;

$link = Hyperlink::new('https://example.com/docs', 'docs-group');
$cell = Cell::new('d', null, $link);

What's in the box

BufferImmutable 2-D cell grid: the fluent with*() family plus fill(), copy() and applyDiff(). Every mutation returns a new instance. Bounds-checked cellAt() throws OutOfRangeException.
CellReadonly value object: rune, style, link and width, read through bare accessors. Cell::continuation() marks the neighbor of a wide lead. Derive changes with withRune(), withStyle(), withLink() and withWidth(), each of which returns a new cell.
Position and RegionPosition is a 2-D coordinate that admits negative values for relative offsets. Region is an origin plus width and height, with contains() for hit-testing. Zero-area regions are no-ops in fill() and withRegion().
StylePer-cell pen: foreground and background as RGB 0xRRGGBB or as palette-slot identity (0-255), an underline color, and an attribute bitmask. fromSgr() parses SGR parameter strings back into styles, and toAnsi() writes them out.
HyperlinkOSC 8 anchor with a URL and an optional id grouping field. Both are validated at construction and again on unserialization, so C0 and DEL controls, C1 introducers and semicolons in the id are refused.
Diff pipelineBuffer::diff() returns DiffOp objects (cursor moves, style changes, cell runs, REP and ECH runs, hyperlink changes). DiffOptimiser shapes that list, and DiffEncoder writes it as ANSI.

API reference

ClassMethodDescription
Buffernew(int $width, int $height)Factory for a grid of blank cells
BufferfromString(?string $ansi, int $width, int $height)Test-support parser: walks an ANSI string onto a grid. Lossy by contract, so do not use it as a terminal emulator
BufferfromStyledText(string $text, int $width, int $height)Builds a grid from styled text
BufferfromGrid(int $width, int $height, array $grid)Bulk wrap of exactly width × height cells. Skips pair enforcement, so the pair law is the caller's duty
Bufferbuilder(int $width, int $height), toBuilder()Returns a BufferBuilder for bulk edits, or converts an existing buffer to one
BuffercellAt(int $col, int $row), withCellAt(...)Bounds-checked read, and the immutable single-cell write that enforces the wide-pair law
BufferwithRegion(Region $region, Buffer $source)Blits $source into $region, clipped to the intersection
Bufferfill(Region $region, Cell $cell)Paints a region with one cell
Buffercopy(Region $region)Extracts a region-sized buffer, padding out-of-grid area with blanks. Capped by Buffer::MAX_COPY_CELLS
Buffertext(?Region $region = null)Plain text of the grid or of a region. Runes are returned whatever their style
Bufferdiff(Buffer $previous), applyDiff(array $ops), diffToAnsi(Buffer $previous)Minimal operation list between two frames, its inverse, and the one-call diff-and-encode
BuffertoAnsi()Full repaint of every cell, for terminals where delta output is not safe
BuffersetRowPrefilterEnabled(bool $on), rowPrefilterEnabled()Process-wide switch for the row prefilter used by the diff path. On by default
BufferBuildersetCellAt(...), fillRect(...), toBuffer()Mutable scratch for bulk construction. It shares the wide-pair placement rules with Buffer through the WidePairPlacement trait, so the two cannot diverge
Cellnew(string $rune = ' ', ?Style $style = null, ?Hyperlink $link = null, int $width = 1)Constructs a cell. Negative widths are refused, and a span wider than 2 must measure exactly that many columns
Cellcontinuation(), blank()The width-0 partner of a wide lead, and the default padding cell
Cellrune(), style(), link(), width(), equals(Cell $other)Bare accessors and value equality
CellwithRune(), withStyle(), withLink(), withWidth()Derivations that return a new cell and re-fire the constructor checks
Stylenew(?int $fg = null, ?int $bg = null, int $attrs = 0), bold(), reverse()Convenience factories for RGB colors and the attribute bitmask
StylefromSgr(string $params, ?Style $carry = null)SGR parameter parser. Returns null only when nothing was set
StyletoAnsi(), equals(), valuesEqual()One-shot SGR emission (via SgrEmitter) and value equality
StylewithAttrs(int), withBold() to withInvisible(), has*() predicatesBitmask replacement, nine single-bit toggles, and their predicates
Hyperlinknew(string $url, string $id = ''), Hyperlink::CLOSEValidated OSC 8 anchor and the close frame constant
Regionnew(Position $origin, int $width, int $height), contains(int $col, int $row)Rectangle with inclusive-edge right() and bottom() accessors
Positionnew(int $col, int $row)Coordinate pair with col() and row()
DiffEncoderencode(array $ops)Writes an operation list as ANSI. Every frame opens with an unconditional home CUP, so one instance can be reused across frames
DiffOptimiseroptimise(array $ops)Runs at the end of Buffer::diff(). Last style wins, and adjacent same-state cells are coalesced
SgrEmitterSgrEmitter::emit(?Style $style)Turns a style into SGR bytes, preferring palette-slot identity over the RGB twin

Only methods declared in sugar-cellbuffer/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\CellBuffer

Buffer final class

A 2-D grid of terminal cells with immutable mutation semantics.

MethodSummary
static setRowPrefilterEnabled(bool $on): void
static rowPrefilterEnabled(): bool
static new(int $width, int $height): selfDefault factory — creates a width×height grid of blank cells.
static fromString(?string $ansi, int $width, int $height): selfBuild a Buffer from an ANSI-encoded string produced by toAnsi().
static fromStyledText(string $text, int $width, int $height): selfParse a styled ANSI text stream into a full width×height Buffer — the supported production counterpart of the byte-wise test-support self::fromString().
static fromGrid(int $width, int $height, array $grid): selfBuild a Buffer directly from a pre-computed flat cell grid (O(1) wrap).
static builder(int $width, int $height): BufferBuilderFresh mutable scratch for bulk painting (CB-34): setCellAt()/fillRect() write in place under the identical pair law as the fluent with*() paths, and toBuffer() freezes the result through fromGrid(). One allocation per cell, not one Buffer clone per write.
toBuilder(): BufferBuilderMutable scratch seeded with this buffer's cells, for repainting an existing frame in bulk. Writes follow the same pair law as withCellAt(), and BufferBuilder::toBuffer() on the result equals the immutable chain over the same writes; this buffer is not changed.
width(): intWidth in cells.
height(): intHeight in cells.
region(): RegionBounding region of the entire buffer.
text(?Region $region = null): stringExtract plain text, row by row, joined with "\n".
cellAt(int $col, int $row): CellBounds-checked cell accessor.
withCellAt(int $col, int $row, Cell $cell): selfReturn a new Buffer with $cell placed at ($col, $row).
withRegion(Region $region, Buffer $source): selfBlit (composite) $source into this buffer's $region.
fill(Region $region, Cell $cell): selfEfficiently fill a rectangular $region with a single $cell.
copy(Region $region): selfExtract a sub-region of this buffer into a new buffer.
diff(Buffer $previous): arrayCompare this buffer against $previous and return the list of operations needed to transform $previous into this buffer.
applyDiff(array $ops): selfApply a list of DiffOps to this buffer and return the resulting buffer (round-trip inverse of diff): $previous->applyDiff($current->diff($previous)) renders as $current.
diffToAnsi(self $previous): stringDiff against $previous and encode the delta in one step — the canonical two-liner ($curr->diff($prev) fed to a fresh DiffEncoder) collapsed for the frame-loop call sites that hand-wired it (sugar-flexbox, sugar-panels, sugar-overlay, sugar-dashboard, examples/diff_frames.php all repeat the pattern).
toAnsi(): stringRender the buffer to an ANSI escape string.
__serialize(): arraySerialization hook for caching/IPC use cases.
__unserialize(array $data): voidUnserialization hook for caching/IPC use cases.
jsonSerialize(): arrayJSON serialization support.

BufferBuilder final class

Mutable scratch pad for BULK cell painting (CB-34).

MethodSummary
__construct(private readonly int $width, private readonly int $height, ?array $seed = null)A seed grid is validated BEFORE the canvas is allocated, so a mismatched or hostile seed fails with InvalidArgumentException instead of first building a blank grid of the requested size next to it.
static fromGrid(int $width, int $height, array $grid): selfSeed a builder with an existing flat grid, so a frame that already exists can be repainted in place. Buffer::toBuilder() is the in-tree caller; validation lives in the constructor.
setCellAt(int $col, int $row, Cell $cell): selfPaint one cell with the full pair law applied in place. Bounds are fatal (Out Of Range) exactly as withCellAt(), not silently clipped — a bulk loop hitting the edge is a caller bug the builder refuses to hide.
fillRect(Region $region, Cell $cell): selfSweep a region with one cell, clipped to the builder extent (the same intersect-then-sweep shape as Buffer::fill(), which likewise never throws for out-of-frame regions).
width(): intWidth in cells.
height(): intHeight in cells.
region(): RegionBounding region of the entire canvas.
toBuffer(): BufferFreeze the CURRENT grid into an immutable Buffer via the validated fromGrid wrap. Repeat calls after further painting each snapshot the grid as it stands.

Cell final class

A single terminal cell — the atom of buffer rendering.

MethodSummary
__construct(public readonly string $rune, public readonly ?Style $style, public readonly ?Hyperlink $link, public readonly int $width)
static new(string $rune = ' ', ?Style $style = null, ?Hyperlink $link = null, int $width = 1): selfDefault factory — blank cell (shared instance, see property docblock).
static continuation(): selfFactory: a blank continuation cell for wide-char neighbours. Continuation cells have empty rune and zero width. Shared instance.
static blank(): selfFactory: the padding identity — one space, default style, no link, width 1. Named preset so erase paths read as intent (Cell::blank()) rather than as an argumentless default. Same shared instance as the default self::new().
withRune(string $rune): selfCopy carrying a different rune; style, link and width are kept.
withStyle(?Style $style): selfCopy carrying a different style (null clears it); the rest is kept.
withLink(?Hyperlink $link): selfCopy carrying a different hyperlink anchor (null clears it).
withWidth(int $width): selfCopy declaring a different display width.
rune(): stringDisplayed grapheme(s), returned verbatim.
style(): ?StylePer-cell style (or null for default rendering).
link(): ?HyperlinkOSC 8 hyperlink anchor, or null.
width(): intDisplay width in terminal cells.
equals(Cell $other): boolStructural equality: two cells are equal iff their rendered representation (rune, style, link, width) is identical.
__serialize(): arraySerialization hook for caching/IPC use cases.
__unserialize(array $data): voidUnserialization hook for caching/IPC use cases.
jsonSerialize(): arrayJSON serialization support.

OSC 8 hyperlink anchor — a clickable terminal link.

MethodSummary
__construct(public readonly string $url, public readonly string $id = '')
static new(string $url, string $id = ''): selfFactory matching upstream: Hyperlink(url, id).
url(): string
id(): string
toAnsi(): stringThe OSC 8 open frame for this anchor, spelled per spec grammar OSC 8 ; params ; URI ST: ESC ] 8 ; <params> ; <url> ESC \.
equals(self $other): boolValue equality: two hyperlinks are equal iff their url and id match.
static valuesEqual(?self $a, ?self $b): boolNull-safe value equality: two optional hyperlinks are the same link state iff both are null, or both are non-null and url+id match.
__serialize(): arraySerialization hook for caching/IPC use cases.
__unserialize(array $data): voidUnserialization hook for caching/IPC use cases.
jsonSerialize(): arrayJSON serialization support.

Lang final class

Per-library translation facade for sugar-cellbuffer.

Position final class

A 2-D coordinate in the buffer grid.

MethodSummary
__construct(public readonly int $col, public readonly int $row)
static new(int $col, int $row): self
col(): intColumn (0-based, horizontal axis).
row(): intRow (0-based, vertical axis).
equals(self $other): boolValue equality — the same coordinate spelled by a different call site is the same place (consumer idiom: "did the selection move?").
__serialize(): arraySerialization hook for caching/IPC use cases.
__unserialize(array $data): voidUnserialization hook for caching/IPC use cases.
jsonSerialize(): arrayJSON serialization support.

Region final class

A rectangular sub-region of a Buffer, identified by its top-left Position and dimensions.

MethodSummary
__construct(public readonly Position $origin, public readonly int $width, public readonly int $height)
static new(Position $origin, int $width, int $height): self
origin(): PositionTop-left corner.
width(): intWidth in cells.
height(): intHeight in cells.
right(): intRightmost column (inclusive).
bottom(): intBottommost row (inclusive).
contains(int $col, int $row): boolWhether a cell at ($col, $row) falls within this region. A zero-area region contains nothing (see class docblock).
intersect(self $other): ?selfThe rectangle common to this region and $other — the clip math Buffer::withRegion()/Buffer::fill() use against the grid, exposed for overlay compositors.
equals(self $other): boolValue equality of the rectangle: origin corner plus extents (the inclusive right/bottom edges follow from those, so equal here means equal corners and edges). Consumer idiom: "did the selection move?"
__serialize(): arraySerialization hook for caching/IPC use cases.
__unserialize(array $data): voidUnserialization hook for caching/IPC use cases.
jsonSerialize(): arrayJSON serialization support.

Style final class

Minimal per-cell style record — foreground colour, background colour, palette-slot identity, underline colour, and a raw attribute bitmask.

MethodSummary
__construct(?int $fg = null, ?int $bg = null, int $attrs = 0, ?int $fgSlot = null, ?int $bgSlot = null, ?int $ul = null, ?int $ulSlot = null)
static new(?int $fg = null, ?int $bg = null, int $attrs = 0): selfDefault factory.
static bold(): selfFactory: bold.
static reverse(): selfFactory: reverse.
fg(): ?int
bg(): ?int
attrs(): int
fgSlot(): ?int
bgSlot(): ?int
ul(): ?int
ulSlot(): ?int
hasBold(): bool
hasItalic(): bool
hasUnderline(): bool
hasStrike(): bool
hasFaint(): bool
hasBlink(): bool
hasReverse(): bool
hasOverline(): bool
hasInvisible(): bool
withFg(?int $fg): selfSets the RGB foreground and discards palette-slot identity (the two representations are mutually exclusive by this class's with*() law).
withBg(?int $bg): selfSets the RGB background and discards its palette-slot identity.
withFgSlot(?int $fgSlot): selfSets the foreground palette slot (0-255, or null to clear it) and discards the RGB foreground so a stale hex can never shadow the slot.
withBgSlot(?int $bgSlot): selfSets the background palette slot (0-255 or null) and discards its RGB twin.
withUl(?int $ul): selfSets the underline RGB and discards its palette-slot identity.
withUlSlot(?int $ulSlot): selfSets the underline palette slot (0-255 or null) and discards its RGB twin.
withAttrs(int $attrs): selfReturn a new Style with the given attribute bitmask (replaces).
withBold(bool $on = true): selfReturn a new Style with bold toggled on or off.
withReverse(bool $on = true): selfReturn a new Style with reverse toggled on or off.
withItalic(bool $on = true): selfReturn a new Style with italic toggled on or off.
withUnderline(bool $on = true): selfReturn a new Style with underline toggled on or off.
withStrike(bool $on = true): selfReturn a new Style with strike toggled on or off.
withFaint(bool $on = true): selfReturn a new Style with faint toggled on or off.
withBlink(bool $on = true): selfReturn a new Style with blink toggled on or off.
withOverline(bool $on = true): selfReturn a new Style with overline toggled on or off.
withInvisible(bool $on = true): selfReturn a new Style with invisible (conceal) toggled on or off.
equals(self $other): boolValue equality: two styles are equal iff their fg, bg, attrs, palette slots, and underline colour values are all identical.
static valuesEqual(?self $a, ?self $b): boolNull-safe value equality: two optional styles are the same render state iff both are null, or both are non-null and value-equal.
toAnsi(): stringOne-shot full SGR emission for this style (CB-31): the exact bytes the diff encoder writes whenever its pen transitions onto it — the canonical emitter (Support\SgrEmitter, relocated in CB-30) is the single home, so this is the parse→emit identity surface for callers outside a Buffer stream. Note the leading reset term: emission is assertive (\x1b[0;…m), self-contained on any terminal state.
static fromSgr(string $params, ?self $carry = null): ?selfParse one SGR parameter run (the digits between "\x1b[" and 'm') into a Style, carried on top of $carry.
__serialize(): arraySerialization hook for caching/IPC use cases.
__unserialize(array $data): voidUnserialization hook for caching/IPC use cases.
jsonSerialize(): arrayJSON serialization support.

SugarCraft\CellBuffer\Diff

DiffEncoder final class

Encodes a list of DiffOp objects into a minimal ANSI byte stream.

MethodSummary
encode(array $ops): stringEncode a list of DiffOps to a raw ANSI byte string.

DiffOp abstract class

Abstract base for all buffer-diff operations.

DiffOptimiser final class

Peephole optimiser over a list of DiffOps.

MethodSummary
optimise(array $ops): arrayOptimize a list of DiffOps.

EraseRunOp final class

Erase N characters starting at the current cursor position using ECH (Erase Character) sequence \x1b[N X.

MethodSummary
__construct(public readonly int $count)

MoveCursorOp final class

Move cursor to ($col, $row) using CUP (Cursor Position) sequence.

MethodSummary
__construct(public readonly int $col, public readonly int $row)
col(): intDestination column (0-based; CUP emits it 1-based).
row(): intDestination row (0-based; CUP emits it 1-based).
info(): array

RepeatRunOp final class

Repeat the preceding character N times using REP sequence \x1b[N b.

MethodSummary
__construct(public readonly string $rune, public readonly int $count, public readonly int $width = 1)

SetCellOp final class

Write one or more cells at the current cursor position using direct character output (SGR transitions are separate SetStyleOp).

MethodSummary
__construct(public readonly array $cells)
count(): intNumber of cells in this op.

SetHyperlinkOp final class

Open or close an OSC 8 hyperlink at the current cursor position.

MethodSummary
__construct(public readonly ?Hyperlink $hyperlink)

SetStyleOp final class

Transition the active SGR (Select Graphic Rendition) style before the next cell write.

MethodSummary
__construct(public readonly ?Style $style)

SugarCraft\CellBuffer\Support

RepeatGate final class

Byte-cost gate deciding whether a REP sequence actually pays for itself.

MethodSummary
static worth(int $count, int $runeBytes = 1): boolWhether encoding $count repeats of a $runeBytes-wide rune as one ESC[count b sequence is strictly smaller than repeating it literally.
static repByteCost(int $count): intWire size of the REP encoding for $count repeats (3 frame bytes plus the decimal digits of the count). Public so the break-even ladder in tests/RepeatGateTest derives its expectations instead of re-spelling the arithmetic.

SgrEmitter final class

Shared SGR (Select Graphic Rendition) sequence emitter.

MethodSummary
static emit(?Style $style): stringEmit the SGR sequence for a style (or reset if null).

WidePairPlacement trait

The wide-pair placement law, shared verbatim by Buffer's copy-on-write paths and the mutable BufferBuilder scratch (CB-34) so the degradation rules exist in exactly one place — a builder that diverged from withCellAt() would mint grids the immutable API can never produce.

Configuration and limits

The package has no configuration file or environment variables. Its tunable surface is a handful of constructor-time values and class-level limits:

SettingTypeDefaultEffect
Buffer width and heightint, intnone (required)Grid dimensions. Dimensions are trusted at construction, so size the grid to the pane rather than to the content
Buffer::MAX_COPY_CELLSint constant1_000_000Upper bound on the cells a single copy() may produce
Buffer::setRowPrefilterEnabled()bool, process-widetrueEnables the row prefilter that skips unchanged rows in diff().
Cell widthint10 is a continuation, 2 a wide lead, and N > 2 a span whose rune must be exactly N columns wide
Style palette slotsint, 0-255unsetPalette identity for a channel. Validated at construction. Slot and RGB are mutually exclusive per channel
Hyperlink url and idstringid ''C0 and DEL controls, C1 introducers and semicolons in the id are refused

Theming and styling

A Style is a pen, not a theme. It carries the colors and attributes a cell paints with, and it does not look up colors from a palette of its own. Two color channels are available for each of foreground, background and underline:

  • RGB: Style::new(0xFF0000) paints a fixed color and discards any slot identity on that channel.
  • Palette slot: withFgSlot(n), withBgSlot(n) and withUlSlot(n) keep the color symbolic, so it follows the terminal theme and survives a delta round-trip without being baked into a hex value.

The attribute bitmask uses this package's own bit layout, which does not match sugar-vterm's bits:

ConstantBitNote
Style::ATTR_BOLD1
Style::ATTR_ITALIC2
Style::ATTR_UNDERLINE4The underline color is stored apart from this bit and emitted whenever the pen is set
Style::ATTR_STRIKE8
Style::ATTR_FAINT16Cleared together with bold by SGR 22
Style::ATTR_BLINK32The bit is carried verbatim. The terminal decides what it means, so TUIs honoring reduced motion should substitute static emphasis
Style::ATTR_REVERSE64
Style::ATTR_OVERLINE128
Style::ATTR_INVISIBLE256A display attribute, not a redaction boundary. Runes in invisible cells are still returned by text()

Wide characters

Wide cells (CJK, many emoji) declare width: 2. Width is declared, never measured, so pass it explicitly. The writing API (withCellAt(), fill() and withRegion()) writes the width-0 continuation to the right of every lead and degrades a lead that would straddle the last column to a blank. When a lead is replaced, its old continuation is blanked, and a new lead that lands on an existing pair displaces the partner. Larger widths are run-length spans with no continuation cells, and their rune must measure exactly the declared width. Buffer::fromGrid() is the one entry point that skips these rules.

Diffing and delta ANSI

Buffer::diff(Buffer $previous) compares two frames and returns a minimal list of DiffOp objects. DiffEncoder::encode() turns that list into bytes. The encoder resets its cursor, style and hyperlink state on every call and opens each frame with a home CUP, so an encoder can be reused safely across frames. Each frame is self-contained and does not depend on what the previous frame left on screen.

OperationANSIUsed when
MoveCursorOpCUP ESC [row;colHRepositions before a run of changes, and is skipped when the cursor is already there
SetStyleOpSGR ESC [...mThe pen changes by value. This is a full reset and restatement, not a minimal delta
SetCellOpRaw rune bytesOne or more consecutive changed cells
RepeatRunOpREP ESC [N bThe tail of a long identical run where the RepeatGate byte arithmetic favors REP. The gate answers false on ties, so plain glyphs stay literal
EraseRunOpECH ESC [N XRuns of three or more blank default cells
SetHyperlinkOpOSC 8Opens or closes a hyperlink anchor

Worked example: two 5×2 buffers, one blank and one with a red A and a bold blue BBB. The diff yields seven operations: a cursor move, a style change and the red cell, then a cursor move, a style change, the blue cell, and a repeat run for the remaining Bs.

use SugarCraft\CellBuffer\Buffer;
use SugarCraft\CellBuffer\Cell;
use SugarCraft\CellBuffer\Style;
use SugarCraft\CellBuffer\Diff\DiffEncoder;

$prev = Buffer::new(5, 2);
$blueBold = Style::new(0x0000FF)->withAttrs(Style::ATTR_BOLD);
$curr = $prev
    ->withCellAt(0, 0, Cell::new('A', Style::new(0xFF0000)))
    ->withCellAt(1, 0, Cell::new('B', $blueBold))
    ->withCellAt(2, 0, Cell::new('B', $blueBold))
    ->withCellAt(3, 0, Cell::new('B', $blueBold));

$ops   = $curr->diff($prev);
$bytes = (new DiffEncoder())->encode($ops);
ESC[1;1H            home anchor, the unconditional prologue of every frame
ESC[0;38;2;255;0;0m  SGR: red foreground
A                   the changed cell
ESC[0;38;2;0;0;255;1m  SGR: blue foreground and bold
BBB                 the repeat run is written literally, because REP would cost more here
ESC[0m              closing reset, so a stale color never bleeds into the next frame

The diff round-trips: $prev->applyDiff($curr->diff($prev)) renders byte-identically to $curr through toAnsi(), and hyperlinks, ids included, survive the trip.

Examples

  • examples/basic.php: the Quickstart, runnable. It prints the rune read back from the cell, then the grid. Because toAnsi() ends rows with a bare LF, the H runs into the first row, so the output begins HAB.
  • examples/diff_frames.php: the worked diff example. It prints the seven delta operations for two 5×2 frames, the encoded delta size (50 bytes), and the size of a full toAnsi() repaint of the same frame (51 bytes).
php examples/basic.php
php examples/diff_frames.php

Testing

Run the suite from the library root. It uses PHPUnit 10 and the phpunit.xml in the package:

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

The tests are the executable specification for the package. BufferTest.php covers the immutable mutators, WideCellPairingTest.php the pair law, DiffEncoderTest.php, DiffOptimiserTest.php and DiffRowPrefilterTest.php the delta path, RepeatGateTest.php the REP arithmetic, SgrEmitterTest.php and StyleTest.php the SGR vocabulary, and HyperlinkTest.php the OSC 8 validation.

Troubleshooting

SymptomCause and fix
Output rows stack diagonally in a raw terminaltoAnsi() joins rows with a bare LF, which a raw-mode terminal does not turn into a carriage return. Write "\r\n" between rows, or position each row yourself with CUP.
A wide character leaves a gap or overwrites its neighborThe width was not declared. Pass width: 2 to Cell::new(), and write the lead with withCellAt(), which writes the continuation for you. fromGrid() skips that step, so pair the cells yourself there.
OutOfRangeException from cellAt()Coordinates are zero-based and bounded by width() and height(). Clamp the coordinate, or check region()->contains() first.
InvalidArgumentException from Hyperlink::new()The URL or id contains a C0 or DEL control, a C1 introducer, or (in the id) a semicolon. Sanitize untrusted text first. Well-formed multibyte IRIs are accepted.
Cell::new() refuses a wide spanA width above 2 is a run-length span, and its rune must measure exactly that many display columns. Use a width-2 lead for a single wide glyph, or pad the rune to the span width.
A diff replay leaves cells out of the grid unchangedapplyDiff() skips any write that lands past the last row or column, by design, so a diff never grows the grid. Check that the ops were produced from a buffer of the same dimensions.

Security and trust boundaries

  • Runes are written verbatim. toAnsi() and the diff encoder emit whatever rune a cell holds. Strip control bytes from untrusted text first with SugarCraft\Core\Util\Sanitize::untrusted(). Raw escapes in a rune desynchronize the cursor and inject live SGR.
  • Hyperlinks are validated at construction and again on unserialization, so their fields cannot carry forged OSC 8 frames.
  • fromString() is test support. It is not an emulator. It drops every CSI that is not SGR-shaped and skips OSC frames, so do not feed it untrusted input expecting a faithful parse.
  • Serialized payloads are re-validated. __unserialize() re-runs every constructor invariant, so a forged payload fails closed.

Architecture

Buffer / BufferBuilder     immutable grid  (BufferBuilder is the mutable scratch)
        |  diff($previous)
        v
DiffOp list               MoveCursorOp, SetStyleOp, SetCellOp, RepeatRunOp,
        |                  EraseRunOp, SetHyperlinkOp
        |  DiffOptimiser (last style wins, runs coalesced)
        v
DiffEncoder               ANSI bytes, home-anchored and self-contained
        ^
Support\SgrEmitter        Style -> SGR parameters (palette slot first)
Support\RepeatGate        REP-versus-literal byte arithmetic
Support\WidePairPlacement wide-pair law, shared by Buffer and BufferBuilder

The memory model is copy-on-write: every mutation clones the cell list, so an old and a new grid briefly coexist. That is the price of value semantics, and it is why grid dimensions should follow the pane rather than the content.

Upstream mapping

Charmbracelet sourceSugarCraft portNotes
charmbracelet/x/cellbuf buffer.goBuffer, CellThe grid model, with copy-on-write mutation in place of in-place edits. There is no Resize, Scroll or SetSize
charmbracelet/x/cellbuf hardscroll.go, hashmap.gonot portedThe scroll optimization and line-hash map. Scrolling belongs to sugar-vterm's mutable grid
charmbracelet/lipglossStyle, SgrEmitterThe pen and SGR vocabulary
ratatui Buffer::diffBuffer::diff(), DiffEncoderThe framing of the delta, cited in the DiffOp notes

The deliberate departures from the Go package are listed in the Divergences section of the library README.

Changelog and versioning

The library has no separate changelog file yet, so its history is the commit log of sugar-cellbuffer/ in detain/sugarcraft. Packagist publishes the dev-master line only. The package was renamed from sugarcraft/candy-buffer in 2026-10, with its namespace changed from SugarCraft\Buffer\ to SugarCraft\CellBuffer\. Depend on the new name only.

  • sugar-vterm: the mutable terminal emulator that parses ANSI into a cell grid. Its own grid is independent of this package by design.
  • sugar-ansi-parser: the VT500 byte-stream parser that drives sugar-vterm.
  • sugar-style: the rich styling API (borders, padding, transforms). It converts to and from this package's regions.

Source & demos