Search by

sugarcraft / sugar-readline

detain

Interactive line-editing prompts for terminal UIs — text input with validation/completion/hidden-password mode, selection prompts with filtering/pagination/cursor navigation, multi-select prompts, confirmation prompts and multi-line textarea input. Design antecedent: erikgeiser/promptkit; developed

dev-master 2026-11-18 21:06 UTC

This package is auto-updated.

Last update: 2026-11-20 01:04:12 UTC


README

sugar-readline

CI codecov Packagist Channel License PHP

SugarReadline

sugar-readline — an interactive line-editing prompt library for terminal UIs on PHP 8.3+.

Status: the full surface ships green with examples, and Readline::interactive() has since 2026-11 carried the raw-mode ritual a host needs — what remains before a 🟢 readiness badge is a real in-repo consumer; the docs/MATCHUPS.md row (🟡) records the open G5 adoption call.

Features

  • TextPrompt — single-line input with validation, autocomplete, hidden/password mode, char limit, default value, history navigation, and an optional display-width viewport
  • SelectionPrompt — filtered list with type-to-filter, cursor navigation and pagination
  • MultiSelectPrompt — filtered multi-choice with min/max enforcement and FIFO rollover at the cap
  • Dynamic choice lists — withChoices($choices, $preserveCursor = true) on both list prompts replaces the options at runtime, re-applying the active filter and keeping (clamped to what survives) or homing the cursor on request
  • ConfirmationPrompt — Yes/No with customizable labels (withConfirmLabel() / withCancelLabel()): choose with arrows/Tab/Space or pick directly with y/n (one keystroke to set), commit with Enter
  • TextareaPrompt — multi-line text input with line/column cursor and optional max-line cap; Enter submits and Shift+Enter, Alt+Enter or Ctrl+J break lines
  • Immutable state — every input-handling method returns a new instance and view() returns the ANSI string; the answer rides a per-shape accessor (value()/selectedValue()/selectedValues()/result()), and the Readline pump owns all terminal writes
  • Vim keybindings — ViMode (Insert/Normal, plus a motion-only Visual scaffold) maps keys through VimKeyHandler in sugar-forms — shared with the sugar-forms widgets — with text objects (ci", di(, da{, yiw) and a working unnamed register (x/dd/yy/text-object yanks feed p)
  • NO_COLOR respected — when the NO_COLOR environment variable is set to a non-empty value, every decoration (colour and style alike) falls away and prompts print as plain text
  • Translated chrome — filter bar, page footer, Yes/No, the search indicator and the default validation message ride a lang/ catalog (namespace readline); your labels, choices and validator messages stay opaque (see Internationalization)
  • Capability gating — the pump probes the terminal before it speaks: dumb or unrecognized surfaces get plain-text frames with no private-mode pushes, and non-TTY sinks keep escape frames because they are the recording (full discipline under Terminal mode)

Install

composer require sugarcraft/sugar-readline:dev-master

No tagged release exists yet, so dev-master is the only resolvable constraint — the versionless form fails Packagist's default stability filter. Working from a checkout of this library? Run composer install inside sugar-readline/ before executing the examples/ scripts; they boot from vendor/autoload.php.

Quick start

Each prompt is a pure state machine: feed it key characters and it returns a new prompt. Readline is the terminal loop that does the feeding — it reads keypresses through sugar-input's InputDriver, repaints the prompt's view() after every change, and returns a typed ReadlineResult once the prompt is submitted or aborted: submitted, aborted, stopped (the one-shot stop() latch), value (the answer) and prompt (the final state machine). run() paints to STDOUT when the output argument is omitted; pass your own stream handle to paint elsewhere, or an explicit null to advance state without writing anything (the headless shape the tests use). Each run() starts its repaint series from row 0 of the display — never write to the output stream while a run is in flight; between run()s you own the lines freely. On a live terminal, reach for Readline::interactive() instead of run(): it wraps the loop with the raw-mode flip and restore the key chords need (see "Terminal mode" below).

use SugarCraft\Readline\Readline;
use SugarCraft\Readline\TextPrompt;

$result = Readline::interactive(TextPrompt::new('Enter your name: '), STDOUT);

if ($result->submitted) {
    echo $result->value . "\n";
}

You can also drive the state machine directly without a terminal — the shape the tests use:

$prompt = TextPrompt::new('> ');
$prompt = $prompt->handleChar('h')->handleChar('i');
$prompt = $prompt->handleKey(\SugarCraft\Readline\Key::Enter);
$prompt->value();  // 'hi'

That direct shape is also the screen-reader- and CI-friendly path: prompts never emit cursor escapes themselves — only Readline's repaint loop does — so a host that feeds keys and renders view() through its own output channel gets identical state without the cursor traffic.

Text prompt

use SugarCraft\Readline\Readline;
use SugarCraft\Readline\TextPrompt;

$result = Readline::fromStdin()->run(
    TextPrompt::new('Enter your name: ')
        ->withDefault('Anonymous')
        ->withCompletions(['Alice', 'Bob', 'Carol']),
    STDOUT
);
echo $result->value;  // 'Alice' after typing + Tab + Enter

The remaining prompt surface is all fluent — every setter returns a new instance:

  • withValidator(callable) gates submit() on a rule that can say why. Return true (or any truthy non-string) to accept; return a non-empty string to reject and paint that string as the error row (sanitized, cell-clipped to the display width); return false, '' or null to reject with the default Invalid input. Rejection still never travels by throwing — but a throwing validator is now caught: its exception is contained as a default-message rejection instead of escaping submit(), handleKey() and run().
  • withCharLimit(int) caps the buffer. Limit and default are order-independent: whichever of withDefault() and withCharLimit() runs last enforces the clamp (withMaxLines() behaves the same way on the textarea).
  • withHidden() masks input (for secrets) and disables history pushes and completion echoes. The masked frame renders one glyph per typed character (* by default; withMask() or the setter's nullable $mask argument changes the glyph — toggling hidden off keeps the configured glyph), so assistive output perceives the length of what is typed but never its content. When even a growing mask run is unwanted, drive the prompt through the pure state-machine API and render whatever subset you choose.
  • withAutoSuggest(bool) proposes the most recent matching history entry as a dim row under the prompt. It is on by default whenever history is attached — the setter's practical use is turning it off — and the proposal scans the whole history on each repaint.
  • withUndoManager(manager) attaches an UndoManager: an immutable bounded (512-state) snapshot stack fed automatically as you type and edit, driven by Ctrl+Z/Ctrl+Y (or vi u in normal mode).

Selection prompt

Type to filter the list as you go; Backspace edits the filter and Ctrl+U clears it. Space acts on the row under the cursor: in SelectionPrompt it is a second Enter, submitting the row under the cursor; in MultiSelectPrompt it toggles the mark. Space never joins the filter — it is a bound key, so a filter containing a space is unreachable and typing one acts on the row under the cursor instead. While the filter matches nothing, the list renders (no matches) and Enter/Space are refused until Backspace restores a match:

use SugarCraft\Readline\Readline;
use SugarCraft\Readline\SelectionPrompt;

$result = Readline::fromStdin()->run(
    SelectionPrompt::new('Choose a fruit:', ['Apple', 'Banana', 'Cherry', 'Date']),
    STDOUT
);
echo $result->value;      // 'Banana' after typing 'an' + Enter

Multi-select prompt

use SugarCraft\Readline\Readline;
use SugarCraft\Readline\MultiSelectPrompt;

$result = Readline::fromStdin()->run(
    MultiSelectPrompt::new('Pick:', ['A', 'B', 'C'])
        ->withMinSelections(1),
    STDOUT
);
print_r($result->value);  // ['A', 'B'] after Space + navigation + Enter

withChoices() resets the marks: they are indexed by the old choice list, so a swapped-in set starts unmarked.

Textarea prompt

use SugarCraft\Readline\Readline;
use SugarCraft\Readline\TextareaPrompt;

$result = Readline::fromStdin()->run(
    TextareaPrompt::new('Describe:')->withMaxLines(5),
    STDOUT
);
print_r($result->prompt->lines());  // edited multi-line text

TextareaPrompt::new() takes only the label — a textarea has no choices. Keyboard contract: Enter submits, Shift+Enter and Ctrl+J insert a new line, Ctrl+U kills the text before the cursor on the current line only, Up/Down move between lines, Escape/Ctrl+C abort. The pump negotiates modified-key reporting for the life of the prompt — the kitty keyboard protocol's disambiguate flag, pushed on start and popped on teardown, TTY output only — so terminals that honor it deliver the break chords as distinct frames. Where the terminal ignores the push, or the output is not a TTY, Shift+Enter and Ctrl+J degrade to bare 0x0A/0x0D — indistinguishable from Enter — and submit. When a maxLines cap is reached, further line breaks are silently refused wherever the cursor sits and text accumulates on the line under the cursor.

Confirmation prompt

use SugarCraft\Readline\Readline;
use SugarCraft\Readline\ConfirmationPrompt;

$result = Readline::fromStdin()->run(
    ConfirmationPrompt::new('Delete file?'),
    STDOUT
);
echo $result->value ? 'yes' : 'no';  // 'yes' or 'no'

ConfirmationPrompt::withHint(string) paints a hint row (e.g. "Press Enter to confirm") under the Yes/No choice. ConfirmationPrompt::withAutoSubmit(bool $on = true) is the immediate-answer opt-in: when armed, a y or n press selects and submits in one keystroke (the gum reflex), while arrows and the Space/Tab toggle remain browse-only. The feature defaults off, so the Enter-to-commit contract above is shipped behaviour.

Custom key handlers

onKey() registers additional handlers; it adds to the keymap rather than replacing it, and registering the same key twice keeps the latest handler for that key. ctrl_c still aborts the prompt itself.

use SugarCraft\Readline\Readline;
use SugarCraft\Readline\TextPrompt;

$result = Readline::fromStdin()
    ->onKey('ctrl_c', fn($event) => print("aborted\n"))
    ->onKey('ctrl_u', fn($event) => print("cleared\n"))
    ->run(TextPrompt::new('> '), STDOUT);

echo $result->value;

onMouse(), onFocus() and onPaste() register the same way for mouse reporting, focus in/out, and bracketed paste. The bracketed-paste enable is gated on the output stream being a tty, so a program with piped stdin behind a tty stdout may still receive pastes as raw bytes. On the genuine bracketed path — a PasteEvent framed by ESC[200~ / ESC[201~ — the content is inserted as literal text: TextPrompt and TextareaPrompt expose insertPastedText(string), which strips every control byte except TAB before inserting — the textarea additionally keeps LF and honours embedded newlines as line breaks — so a bracketed paste payload can never forge a submit or replay editor commands. A raw-fallback delivery has no such framing: its bytes take the ordinary key path as they arrive, so a pasted CR or LF submits exactly as if it had been typed. TAB survives on both surfaces, so a host relying on the strip to vet a secret or URL field must still reject tabs itself.

Untrusted content

Prompt material routinely derives from data the program did not author — completion candidates from the filesystem, choices fetched over the network, git branch names, history left by an earlier session. Every emission choke runs that content through Ansi::sanitize(): C0 control bytes and DEL are stripped (CR included; TAB and LF survive because they have legitimate display roles), so hostile text cannot inject escape sequences into the frame a prompt paints.

The guarantee is display-only. Values returned by value(), selectedValue() / selectedValues() and entries pushed into history keep their raw bytes — the library sanitises what it renders, not what it hands back. Printing a prompt's result somewhere else is the host's responsibility: sanitise or re-encode it before you emit it.

Long lines and repaint

view() returns one logical row; painting that row wider than the terminal makes it wrap and the cursor-up repaint maths desyncs (the classic staircase). TextPrompt::withDisplayWidth($cells) bounds the editable region to a window around the cursor (clipped ends marked …, cell-width aware; 0 renders the row unbounded). Only one of the width's three states can adopt: null (the default, restored by withDisplayWidth(null)) means not given yet and is the only value run() fills in; a positive cell count is an explicit bound and 0 an explicit unbounded choice — neither is ever overwritten. When adoption fires, it reads COLUMNS first if that carries a positive integer (the lever a headless or CI harness pulls); failing that, and if the output stream is a real TTY, it probes TIOCGWINSZ (via sugar-core Tty) and adopts the terminal's own columns. bash leaves COLUMNS unset (zsh exports it), so the TTY probe is what covers ordinary interactive use; when neither source answers, nothing is adopted and the host may probe the size itself (e.g. stty size) and pass it to withDisplayWidth(). The same adoption exists vertically: the list prompts (SelectionPrompt, MultiSelectPrompt) and TextareaPrompt accept withViewportRows($rows) / viewportRows(), and an unset state adopts the terminal's row count the same way — LINES first, then the TIOCGWINSZ probe of the output stream. Choices-per-page shrink to fit (label, filter bar and page footer stay visible); the textarea windows its lines around the cursor with … indicator rows. On tiny terminals (under 5 rows) the indicators are gated off and a page floors at one choice — the frame never renders empty, but it may exceed such a screen by a row or two; size the terminal up or pass withViewportRows(0) to opt out. Mid-session resizes follow the adopted bounds: when the driver yields a sugar-input ResizeEvent, the fit re-runs against the new frame and the next frame is a full repaint from a cleared display (a width or height the caller pinned explicitly is never moved). A plain StreamInputDriver reports only bytes, so it never resizes; to get live reflow your input source must emit ResizeEvent (sugar-input's SignalResizeDriver detects SIGWINCH but carries no key bytes, so it is a resize source to merge, not a standalone driver). Multi-line textarea output and wrapped labels can still exceed the window: the bound covers the editable region and the choice list, not the label — long labels are the host's layout responsibility, bounded width or not.

Terminal mode (raw vs cooked)

run() never touches termios — the library deliberately leaves terminal settings to the host program. Readline::interactive() carries the flip for the common case: it captures the stty -g snapshot, runs the recipe below around run(), and restores on every exit path — the finally and a shutdown backstop for hard exits — guarded by stream_isatty(STDIN) so piped and CI hosts never shell out at all. On a cooked TTY the line discipline consumes Enter, Backspace, and Ctrl+ combinations, so arrow keys and multi-key chords cannot reach the prompt — which is why the quick start uses interactive(). Hosts that own their loop can compose the recipe directly:

$isTty = stream_isatty(STDIN);
$saved = $isTty ? trim((string) shell_exec('stty -g')) : '';
if ($isTty) {
    shell_exec('stty -icanon -echo -isig -ixon min 1 time 0');
}
try {
    $result = Readline::fromStdin()->run(TextPrompt::new('> '), STDOUT);
} finally {
    if ($isTty && $saved !== '') {
        shell_exec('stty ' . escapeshellarg($saved));
    }
}

The stream_isatty(STDIN) guard is load-bearing, not ceremony: run the unguarded recipe with piped stdin and stty errors "Inappropriate ioctl for device" on every call — the captured state is empty and the restore degrades to a usage dump (interactive() carries this guard; so did the hand-rolled ritual examples/interactive.php used to run before the entry point existed). stty is also POSIX-only — there is no such command on Windows, and sugar-readline deliberately carries no Windows raw-mode path: sugar-pty is NOT a dependency of this library (check its composer.json require). On a Windows console interactive() therefore warns once to STDERR and proceeds cooked — arrows and Ctrl chords reach the prompt only after the console discipline has had its say. A host that wants real raw input there owns the flip out-of-tree (a console-API layer, sugar-pty's ConPty stack if it is already a dependency of the host app, …) and drives run() the way interactive() drives it around stty.

-isig matters: with signals left enabled, Ctrl+C raises SIGINT, which kills the process before the finally restore runs — the shell is then left with echo and canonical mode off. With -isig, Ctrl+C arrives as an ordinary byte the prompt aborts on, and the restore always executes.

-ixon matters for the same reason: with output flow control left enabled, the discipline swallows Ctrl+S (0x13, XOFF) as a stop-output request before the prompt ever sees it, so forward history search is unreachable and the terminal simply freezes until Ctrl+Q (0x11, XON) resumes it. With -ixon, Ctrl+S arrives as an ordinary byte and the prompt opens forward search.

The captured -g string is implementation-specific — GNU stty prints it as dense single tokens (-icanon) while BSD/macOS stty uses space-separated words — so capture and restore on the same machine in the same run; never store the string to replay it on another platform.

sugar-pty's FFI Termios::makeRaw() (cfmakeraw) clears signal generation and delivers the same transition. sugar-core's SugarCraft\Core\Util\RawMode delivers the same flow-control half — it runs -ixon — but deliberately leaves signal generation on: Ctrl+C raises SIGINT there, and the abort chords documented below remain the stty -isig recipe's contract; only that recipe — shipped as Readline::interactive() with the stream_isatty guard, finally-restore and shutdown backstop built in — delivers them. Over a pipe or socket (no tty at all) no stty is needed — the bytes arrive as written, which is exactly how the test-suite drives chords.

Escape discipline: on a real TTY every frame repaints with cursor escapes (\r, cursor-up CSI nA, clear-below CSI 0J); under TERM=dumb or an unrecognized terminal class the private-mode pushes (bracketed paste, kitty keyboard) are skipped and frames paint as plain text on fresh lines — no escape noise on assistive or dumb surfaces. Non-TTY sinks (log files, php://memory) keep the escape frames because they are the recording, but Ctrl+L clears below there instead of wiping the screen with CSI 2J CSI H, so captured streams stay parseable. For fully escape-free output in your own tests, drive the prompts as pure state machines (see the Quick start's terminal-free shape).

Input driver

Readline accepts an optional SugarCraft\Input\InputDriver to control where input comes from. new Readline() and Readline::fromStdin() both open php://stdin themselves — with that default pump the loop also detects a true EOF (see below). For testing, inject a driver over a fixture stream:

// Testing: inject a fake stream (socket pair or pipe — the driver polls
// the stream, so non-selectable php://memory is not a good fixture here)
$pair = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, 0);
fwrite($pair[1], "hello\x0d");   // \x0d = Enter
fclose($pair[1]);
$readline = new Readline(new SugarCraft\Input\Driver\StreamInputDriver($pair[0]));
$result = $readline->run(TextPrompt::new('> '));
// $result->value === 'hello'

An injected driver answers "no event yet" and "stream ended" with the same read() === null: the InputDriver contract cannot distinguish them. The loop therefore keeps idling until the prompt ends or stop() is called. To finish a fixture run, close or drain the stream and arm stop() from your test when it runs dry.

Key bindings

Bindings fire from both spellings: raw control bytes off a live stream and symbolic key names (Key:: constants or plain strings like 'ctrl_a') are normalised to one canonical language at the choke point. The Key class lists the primary bindings; it is not an exhaustive enumeration of every sequence a terminal can send.

  • Key::Left / Key::Right — move cursor (text input); Ctrl+B / Ctrl+F alias them on TextPrompt
  • Key::Up / Key::Down — navigate selection list / history / textarea line; also Ctrl+P / Ctrl+N on every text and list surface
  • Key::Home / Key::End — jump within the current line / list; also Ctrl+A / Ctrl+E on every text and list surface
  • Key::Enter — submits: the row under the cursor on SelectionPrompt, the highlighted answer on ConfirmationPrompt, the buffer on the text prompts. In the textarea, Shift+Enter, Alt+Enter and Ctrl+J break a line instead; those arrive as distinct chords only on terminals that honor the pump's kitty-protocol push, and plain Enter submits where the wire never distinguishes them. On single-line prompts Alt+Enter submits like Enter (readline's accept-line law for the chord).
  • Key::Space — a second Enter in SelectionPrompt (submits the row under the cursor); toggles the mark in MultiSelectPrompt; toggles Yes/No in ConfirmationPrompt; inserts a literal space in text inputs
  • Key::Tab — autocompletes on the text prompts and toggles the confirmation value. The first press extends the buffer to the longest common prefix; further presses cycle the matches. Key::ShiftTab walks the cycle backwards. On an empty buffer the first press paints a bounded preview of the candidates instead of committing one — press Tab again to enter the ring.
  • y / n (any case) — set Yes/No directly in ConfirmationPrompt (Enter still commits); there the Left/Right arrows alias to the same one-keystroke Yes/No picks
  • ConfirmationPrompt::withAutoSubmit() arms the immediate-answer reflex: y/n then selects and submits in one press (arrows and the Space/Tab toggle stay browse-only); off by default, so the Enter-to-commit contract above is the shipped behaviour
  • Key::Backspace / Key::Delete — delete characters. Ctrl+H erases before the cursor; both the BS 0x08 and DEL 0x7F spellings bind to Backspace. Ctrl+D deletes under the cursor, and on an empty buffer aborts (GNU delete-char-or-eof).
  • Key::CtrlU / Key::CtrlK — delete to start / end of line; Ctrl+W deletes the previous word
  • Key::CtrlR / Key::CtrlS — reverse / forward incremental history search. Ctrl+S needs the -ixon recipe (see Terminal mode above): without it the discipline intercepts 0x13 as an XOFF stop-output request instead of opening the search, and Ctrl+Q (XON) unfreezes output.
  • Ctrl+Z / Ctrl+Y — undo / redo the last edit run (a run of consecutive typing collapses into one undo step)
  • Ctrl+L — Readline clears the screen and repaints the prompt
  • Key::PageUp / Key::PageDown — jump the selection list by one page
  • Key::Escape / Key::CtrlC — abort. Each surface keeps its exception:
    • On a real tty the Ctrl+C chord requires the -isig recipe above; with signal generation still on, 0x03 raises SIGINT before the prompt sees it.
    • Inside an attached EmacsMode, Escape is the meta prefix instead (a second Escape cancels it); use Ctrl+C to abort there.
    • Inside an attached ViMode, Escape only switches submodes (insert to normal, visual to normal) and never aborts; Ctrl+C aborts from every submode, and bare Q additionally aborts from normal mode.
    • While a history search is active, Ctrl+C is reclaimed: it cancels back to the pre-search line rather than aborting.

Not every Ctrl+X shown has a matching Key:: constant — there is no Key::CtrlD, CtrlL, CtrlZ or CtrlY, for example. Those bindings are implemented under the canonical string spelling instead: Readline::onKey() and every prompt's key path accept all of 'ctrl_a' through 'ctrl_z', which is what Key::normalize() turns a raw control byte into.

Ctrl+[ is an ESC on every terminal and behaves as esc, not as Ctrl+C.

Editing modes (Vi vs Emacs)

TextPrompt uses a dual-engine architecture. The prompt itself owns the buffer, cursor, history, and rendering; an optional mode object attached via withMode() owns the key-to-operation mapping:

use SugarCraft\Readline\Mode\EmacsMode;
use SugarCraft\Readline\Mode\ViMode;

$prompt = TextPrompt::new('> ')->withMode(new EmacsMode()); // readline bindings
$prompt = TextPrompt::new('> ')->withMode(new ViMode());    // modal vi bindings

Every key fed to TextPrompt::handleKey() is delegated to the attached Mode\ModeInterface implementation. Two carve-outs: while an incremental search is active, the search consumes keys before the mode is consulted; and a plain character the mode does not claim is inserted without going through its handleKey().

While the mode is claiming characters (consumesCharacters() — an armed Emacs meta prefix, or Vi outside insert mode), typed characters are routed through the mode too, so ^W never lands in the buffer while the prefix waits.

The mode calls back into handleKeyDirect() (the mode-bypassing entry point — using handleKey() would recurse) to turn a key into prompt operations, then re-attaches itself so its own state survives the prompt's immutable cloning.

  • EmacsMode implements the classic readline chords — Ctrl+A/E (line start/end), Ctrl+B/F (char motion), Alt+B/F/D (word motion/delete, via the Escape prefix or a Kitty-style alt_b), Ctrl+W (delete word before), Ctrl+T (transpose), Ctrl+P/N (history), Ctrl+R/Ctrl+S (incremental search), Ctrl+K/U (kill to end/start). Ctrl+L reaches the mode as a no-op: screen clearing is the Readline pump's job. Escape arms the meta prefix; a second Escape cancels it. While the prefix is armed, an unbound key is not swallowed — it is dispatched as if Escape had never been typed (so Ctrl+C aborts, Enter submits, and plain characters insert even between the prefix and its binding); only bound Alt+B/F/D consume the keystroke, and unbound Kitty alt_x chords (which never armed a prefix) stay no-ops. The mode never aborts the prompt on its own — Escape only arms the prefix, while Ctrl+C still falls through to the prompt's abort binding; leave it detached if Escape-quit is what you want.

  • ViMode is a modal state machine: it starts in insert mode, Escape moves to normal, and V opens a line-wise visual mode (a motion-only scaffold — selection is not yet rendered or operated on; plain v is deliberately unbound). Pending motions like dd/yy/cc are supported. In normal mode, j/k walk history, x cuts the char under the cursor, D cuts to end-of-line, p puts the unnamed register, u undoes the last edit, Enter submits the line, and space moves right. Ctrl+R and Ctrl+S start incremental search in every submode, insert included. On a hidden prompt the unnamed register never captures the secret text — the same posture undo frames already take. viMode() reports the current submode as the public ViModeState enum. Vi bindings are not hardcoded: normal and visual keys are mapped through sugar-forms' VimKeyHandler, which returns a VimAction enum case that ViMode then executes as TextPrompt operations. New vi bindings therefore belong in sugar-forms (VimAction + VimKeyHandler), not in ViMode's branching. In normal mode the cursor rests on the last character (vi semantics), so $ and Escape-at-end land on — not after — the final char.

    Normal mode supports vi text objects: an operator (c change, d delete, y yank) followed by a scope (i inner / a around) and a target — quotes (" ' `), brackets (( ) b, [ ], { } B, < >), or w for the word under the cursor. So ci" retypes a quoted string, da{ deletes braces and contents, diw/daw delete a word (aw takes the trailing space), yi( copies the parenthesised text into the unnamed register and moves the cursor to its start. Resolution lives in sugar-forms (TextObject::resolve() via VimKeyHandler::handleTextObject()): innermost bracket pair wins, cursor-on-delimiter counts as inside, quotes pair up left-to-right (a cursor before a quoted region jumps forward to it), and unmatched/absent delimiters are a silent no-op (where vim would beep). Escape cancels a half-typed sequence. Simplifications vs vim: a" does not absorb trailing whitespace, escaped quotes are not special, and the unnamed register is a single slot (no named registers, no linewise/charwise distinction on put). dd, cc and yy store the affected line in the register before acting; p pastes register contents as literal text after the cursor — pasted control characters never replay as commands.

With no mode attached, TextPrompt still carries the default GNU-readline movement chords (Ctrl+A/E/B/F/P/N) plus arrows, Home/End, space, Ctrl+U/K/W/D/H/R/S, Ctrl+Z/Ctrl+Y undo/redo, Ctrl+L screen clear (via Readline), Tab completion with match cycling, and Escape/Ctrl+C abort. Attached modes carry their own state: mode() returns the ModeInterface object (or null), and the vi submode string sits one hop behind it at mode()?->viMode() — an accessor only ViMode defines (EmacsMode has no submodes). By default view() never paints that state, so the prompt renders identically across vi submodes; pass withModeIndicator() to make view() append a dim bottom row reading --NORMAL--, --VISUAL-- or --INSERT-- under a ViMode. Hosts that want a custom status line can still read the submode and paint it themselves.

Incremental history search

With a history attached (withHistory()), Ctrl+R enters reverse incremental search and Ctrl+S forward search, in any mode. Ctrl+S only arrives at all on a terminal with flow control switched off: without the -ixon recipe, 0x13 stops the output instead of opening the search (see Key bindings, Ctrl+R/Ctrl+S, for the recovery chord). Typed characters refine the query, repeated Ctrl+R/Ctrl+S steps through older/newer matches, Enter accepts the match into the buffer (without submitting), and Escape/Ctrl+G cancels back to the original line — and so does Ctrl+C while a search is active: it cancels the search, not the prompt, and only the next keypress can abort. The prompt renders a (reverse-i-search)`query': match indicator, switching to (failed reverse-i-search)`query': match when nothing matches (including empty history). On a hidden prompt the line masks query and match alike, in the same idiom.

History

Prompts start with no history attached: navigation and Ctrl+R do nothing until you pass a store via withHistory(). InMemoryHistory keeps entries for the process lifetime; FileHistory persists them across processes. new FileHistory($filePath, $maxHistory, $tempDir, $deferWrites) takes the file to persist to, an entry cap (0 = unlimited), the directory for rewrite temp files, and a flag deferring writes to batch flush() (the paragraphs below spell out the durability contract): the file is created (or tightened, if it exists) at mode 0600, loaded on construction, and flushed at the latest on destruction. With $deferWrites = true, pushes queue in memory until flush() batch-writes them — queued entries are lost if the process dies before any flush runs (e.g. SIGKILL), so call flush() at each submit if the history must survive a hard kill. Pass a $maxHistory and the cap bounds the file too: bounded stores rewrite the whole file on each push, merging anything another process appended in between.

Two write-path prerequisites: every store call stages a temp file beside the history and renames it over the target, so the history directory must be writable — a read-only mount or a cross-device boundary (when the staging directory and the target live on different filesystems) throws RuntimeException at the first append, never half-writes. The $tempDir argument overrides where that temp file is staged (default: dirname($path)) — point it inside the history's own filesystem when /tmp is elsewhere. And the sidecar <path>.lock persists by design: it is never written to (only its inode is flocked) and never unlinked, because an unlink/rename rotation would reintroduce the very race the lock closes.

History is a trust boundary of its own: the file records what was typed, so it can contain secrets. The constructor therefore insists on 0600 — a pre-existing file whose mode cannot be tightened (typically foreign-owned) is refused loudly rather than loaded and appended under someone else's permissions. Keep the history in a private directory: 0600 protects the content, not the filename listing, so the mere name of the file is visible to anyone who can read its directory.

The bounded full rewrite makes the file self-describing: it stamps #sugar-readline-history/v2 as the first line. Every decoder skips the marker, and the append paths never add one — a markerless file decodes identically, so a store simply gains the marker at its first full rewrite. Entries are stored one per line with backslash escapes (\\, \n, \r) applied at the write choke and undone on load — a value that somehow contains a raw newline survives a save/reload round-trip as one entry instead of splitting into two. A history file written before the escaping format existed can therefore have a literal \n two-character sequence decoded into a real newline on the first load — the one decode trade-off the escape format introduces. An unterminated final line — a fragment left by a crash mid-write — is likewise not decoded as an entry: readers drop it, and the next rewrite truncates the file back to the last terminated line. A history path that is a symlink is refused loudly at construction and again under the write lock: without the check, an attacker-planted link turns every append (and the 0600 chmod) against, say, ~/.bashrc.

Dedup is stricter than the base HistoryInterface minimum: FileHistory skips a line equal to any entry already retained (including ones loaded from disk) — zsh HIST_IGNORE_ALL_DUPS style — while plain InMemoryHistory collapses only adjacent duplicates (HIST_IGNORE_DUPS). All writers serialise on a sidecar <file>.lock (flock exclusive, held across read-write-rename), so two processes pushing at once never lose an entry, and a write that cannot happen throws rather than dropping the line.

Note: that throw guarantee covers push() and explicit flush() calls only. The automatic flush in __destruct cannot throw usefully: it degrades to an error_log line, and with deferWrites any entries still queued are lost at exit.

Note: the 0600 promise on Windows rides icacls — PHP's chmod there maps only the read-only bit and returns true regardless. When icacls cannot run, the store logs a one-time disclosure that permissions are advisory on that host. Swap contention: when renaming over the destination is refused — a transient AV/indexer hold on Windows, or a tempDir on a different filesystem (EXDEV) — the writer retries once and then copies the content onto the target under the still-held sidecar lock. The copy cannot interleave with other writers, but it is not rename-atomic: a reader landing mid-copy can briefly see a mixed old/new file.

The writers fsync the content bytes before releasing the lock (where PHP exposes fsync), so a process death cannot leave a half-flushed tail; a crash straddling the rename swap can roll the file back to the previous version but never surfaces a torn line — readers drop an unterminated final line. Reads themselves degrade, not deny: on a filesystem where flock fails outright (NFS without lockd, some FUSE/9p/container mounts — an active writer makes the blocking call wait, never fail), load() and the duplicate guard's peek proceed unlocked with a one-time error_log disclosure per store, because rename-atomic content is safe to read without the advisory lock (at worst a stale version). Writers keep the fail-closed contract: without a usable lock they cannot serialize, so they still throw.

Hidden prompts (withHidden()) never push their value: a secret stays out of both in-memory and on-disk history, and it never enters an attached UndoManager chain either. Incremental history search is the one surface hidden mode does not suppress — Ctrl+R/Ctrl+S still open a search on a hidden prompt with a history attached — so the search line masks the typed query exactly like the buffer, character for character, with the same mask glyph; what you type as a query never appears in clear text.

Submit/abort semantics

Each prompt is a state machine with three states: pending, submitted, aborted.

  • submit() finalises the prompt; for MultiSelectPrompt it only succeeds when canSubmit() is true.
  • abort() discards the prompt; value() / selectedValues() then return empty. Default bindings reach it through Key::Escape or Key::CtrlC (inside an attached EmacsMode, Ctrl+C — Escape is the meta prefix there). Two exceptions: on a live tty the Ctrl+C chord requires the -isig raw-mode recipe above — with signals on, it is a SIGINT death, not an abort; and while an incremental history search is active, these keys cancel the search back to the original line, with abort resuming ownership on the next keypress.
  • isSubmitted() / isAborted() report status. currentValue() (Confirmation) always reflects the current choice, submitted or not. selectedValue() (Selection) tracks the cursor while one exists, but returns null after an abort and whenever the filter matches no choice — with no cursor to point at, there is no value to report, submitted state or not.
  • True end-of-input: when Readline owns the stdin pump and the stream reaches EOF after the decoder drains, run() returns a result with neither submitted nor aborted set, carrying the prompt's last state.
    • The pump is per-Readline-instance, not per-run(): calling run() again feeds the next prompt from wherever the stream stands — printf 'a\nb\n' | php app.php drives two successive prompts with a and b. Once EOF is seen it stays seen.
    • Injected drivers report EOF and "nothing yet" identically, so they cannot trigger this exit; end those loops by submitting, aborting, or stop().
  • stop() requests the loop exit; it lands within one idle poll interval (capped at 20 ms) when the driver's read is non-blocking (min 1 time 0, or an injected driver that returns null promptly). A driver blocking in read() is not interrupted — the stop takes effect on the first pass after it wakes.

Internationalization

The painted chrome — filter bar, page footer, (no matches), Yes/No labels, the search indicator, the default validation message — is translated. User content is not: labels, choices, and your validator's own rejection strings are opaque strings; translating them is your layer's job. A examples/-style host that wants localized prompts supplies them pre-localized.

  • The catalog lives in lang/en.php (source of truth, per LOCALES.md) with the fleet's 16 sibling locales. SugarCraft\Readline\Lang::t($key) is the internal facade over the shared SugarCraft\Core\I18n\T registry, namespace readline.
  • Lookup follows the house law: exact locale → base language (so fr.php covers fr-ca) → en → the raw key, which makes a missing translation surface visibly instead of rendering blank.
  • Switch languages with T::setLocale('de') (process-wide) or per call via T::t('readline.confirm.yes', [], 'ja'). Applications re-theme any string with T::overrideNamespace('readline', $dir).
  • 'confirm.hint' stays [y/n] in every locale: it names the literal keys you press, not a word. Count chrome rides whole-sentence keys with named {placeholder} tokens per the LOCALES.md plural policy — selection.matches_one/matches_other are chosen at the call site and a translation may reorder its tokens, never rename them.
  • The localized-usage story: the examples/ ship baked-English prompts ('Enter your name: ' and friends) because caller-supplied labels are the CORRECT layering — the host that needs a French session passes French labels; the library translates only its own chrome.

API reference

Every public symbol of src/, class by class. Behavior lives in the sections above; this is the index. Backtick tokens are method names, constants, or enum cases; the roster is pinned by tests/ReadmeApiRosterTest.php, so a new public symbol without a row here goes red.

TextPrompt — single-line text input

symbol what it does
__construct() / new() (string $label = '> '); the static factory mirrors upstream
withDefault() initial buffer text; re-clamped by withCharLimit() whenever the later setter runs (finding 092)
withCharLimit() buffer cap in characters; order-independent against withDefault()
withHidden() secret mode: masks rendering, never pushes history, never frames undo; optional second ?string $mask argument sets the mask glyph as it enables
withMask() replaces the mask glyph alone (withHidden(false) keeps it — the S-60 split)
withValidator() `callable(string): bool
withCompletions() candidate list for Tab
withCompleter() lazy candidate source (string $buffer, int $cursor): list<string>, consulted per Tab; null restores the static list (finding 089)
withHistory() attaches a live HistoryInterface store — Up/Down and Ctrl+R/Ctrl+S read the same entries the caller pushes (finding 082)
withMode() attaches an EmacsMode/ViMode key-mapping object
withModeIndicator() paints the mode's name beside the prompt
withUndoManager() attaches an undo stack; typing folds into runs, structural edits snapshot
withAutoSuggest() inline grey suggestion from history ahead of the cursor
withLabelStyle() / withCursorStyle() / withErrorStyle() / withCompletionStyle() SGR code or Style for each chrome slot (collapsed by Styles::code())
withDisplayWidth() / displayWidth() the width seat of SizingInterface
withCursor() position the caret (clamped)
cursor() caret index, characters
handleKey() full dispatch through the attached mode
handleKeyDirect() mode-bypassing entry point (what modes call back into)
handleChar() printable-character entry (paste-safe, search-aware)
insertPastedText() multi-character paste ingestion, control bytes refused
deleteRange() structural delete [start,end); snapshots undo
value() current buffer text (submitted or not)
submit() / abort() finalise / discard
startHistorySearch() opens incremental search with a SearchDirection
isSearching() / searchQuery() search bar state
suggestion() current autosuggest completion text
error() last validator rejection message (or null)
isHidden() secret-mode state
isSubmitted() / isAborted() terminal state
mode() the attached mode object (or null)
view() the painted frame (see Long lines and repaint)
SEARCH_REVERSE / SEARCH_FORWARD direction constants for startHistorySearch()
AUTOSUGGEST_SCAN_WINDOW how far back autosuggest scans history
EMACS_MOVEMENT_ALIASES the ctrl_b-style alias table the movement map carries

TextareaPrompt — multi-line input

symbol what it does
__construct() / new() (string $label = '')
withDefault() seeds the lines; order-independent against withMaxLines()
withMaxLines() hard line cap; slicing on shrink, caret follows (finding 092)
withLabelStyle() / withCursorStyle() chrome style slots
withViewportRows() / viewportRows() windowed rows; unset adopts LINES/TTY
withDisplayWidth() / displayWidth() the width seat
handleKey() / handleChar() / insertPastedText() same dispatch law as TextPrompt; Enter submits, Shift+Enter/Alt+Enter/Ctrl+J break lines
submit() / abort() finalise / discard
value() the joined text
lines() the line list
lineCount() lines present
cursorLine() / cursorCol() caret position
isSubmitted() / isAborted() terminal state
view() the painted frame

SelectionPrompt — one choice from a filtered list

symbol what it does
__construct() / new() (string $label = '', array<string> $choices = [])
submit() commits the row under the cursor
selectedValue() cursor-following value; null after abort or with an empty filter
view() the painted frame

MultiSelectPrompt — marked subset of a list

symbol what it does
__construct() / new() (string $label = '', array<string> $choices = [])
submit() commits the marked set; refuses (transient notice) when the filter matches nothing
selectedValues() marks in list order
selectionCount() marks held
marked() index map of marks
withMinSelections() / withMaxSelections() the selection-count bounds canSubmit() enforces
canSubmit() min/max selection gate
view() the painted frame

SelectionEngine — trait behind both list prompts

symbol what it does
withChoices() replaces the choice list
withFilter() seeds the filter string
withPageSize() choices per page
withViewportRows() / viewportRows() height seat of SizingInterface
withDisplayWidth() / displayWidth() width seat
withCursorStyle() / withLabelStyle() chrome style slots
cursor() current row index
filteredCount() / totalChoices() filter width vs whole list
currentPage() / totalPages() / currentPageItems() pagination surface
handleKey() / handleChar() filter editing + motion dispatch
abort() discard
isSubmitted() / isAborted() terminal state

ConfirmationPrompt — Yes/No

symbol what it does
__construct() / new() (string $label = '')
withConfirmLabel() / withCancelLabel() replace the Yes/No words
withHint() the grey hint line
withAutoSubmit() y/n answers submit in one press
withLabelStyle() / withSelectedStyle() chrome style slots
withDisplayWidth() / displayWidth() width seat
handleKey() letters, arrows, Tab/Space all land here (no handleChar — printable keys must reach the mapping)
submit() / abort() finalise / discard
result() ?bool — true Yes, false No, null undecided
currentValue() live Yes/No regardless of submission
isSubmitted() / isAborted() terminal state
view() the painted frame

Readline — the driving loop

symbol what it does
__construct() (?SugarCraft\Input\InputDriver $input = null, ?callable $idleSleeper = null) — inject a driver for headless use; the sleeper is the idle-backoff test seam
fromStdin() the ordinary-interactive factory
interactive() canonical recipe: guarded stty raw-mode flip, run, restore
run() drives one prompt to submit/abort/EOF; mixed $output = self::PAINT_DEFAULT (omitted paints STDOUT with a one-time notice, explicit null stays headless); returns a ReadlineResult
onKey() / onMouse() / onFocus() / onPaste() extra event handlers, additive, latest registration wins
stop() requests loop exit within one idle poll (non-blocking drivers)
isStopped() whether a stop is pending
idlePollDelayMicroseconds() current adaptive idle backoff
__destruct() releases a lazily-owned stdin pump
PAINT_DEFAULT the paint-sentinel constant
IDLE_POLL_MIN_MICROSECONDS / IDLE_POLL_MAX_MICROSECONDS the backoff bounds

ReadlineResult — typed run() outcome

symbol what it does
__construct() the full record (hosts rarely build it; fromPrompt() is the ergonomic path)
fromPrompt() (object $prompt, bool $stopped) — resolves value() / selectedValues() / selectedValue() / null in that order
submitted / aborted / stopped the three exits
value the answer (resolution order above)
prompt the final prompt object

Contracts

symbol what it does
PromptInterface::view() / ::handleKey() / ::isSubmitted() / ::isAborted() the four methods run() boundary-checks; a missing one throws by name at entry
SizingInterface::displayWidth() / ::withDisplayWidth() the width pair prompts may answer
HistoryInterface::push() / ::previous() / ::next() / ::reset() / ::clear() / ::entries() / ::count() / ::search() the history contract (previous()/next() bare per the accessor law)
ModeInterface::handleKey() / ::consumesCharacters() / ::name() the attached-keymap contract

History stores

symbol what it does
InMemoryHistory::__construct() (int $maxHistory = 0); negative throws fail-fast
InMemoryHistory::push() newest-first insert; adjacent-dup collapse; cap trim + cursor re-clamp
InMemoryHistory::setMaxHistory() the live cap, mutated (findings 012/032); negative throws
InMemoryHistory::withMaxHistory() @deprecated one-line forwarder (REMOVED-IN: 2.0.0)
InMemoryHistory::previous() / next() history walking; getPrevious() / getNext() are the deprecated spellings of the same pair
InMemoryHistory::entries() / count() newest-first view
InMemoryHistory::search() incremental search from a position in a SearchDirection
InMemoryHistory::reset() / clear() cursor rewind / wipe
FileHistory::__construct() (string $filePath, int $maxHistory = 0, string $tempDir = '', bool $deferWrites = false); refuses symlinks and un-tightenable files loudly
FileHistory::tryOpen() graceful-degradation entry: returns null instead of throwing when file history is unavailable
FileHistory::path() the history file location
FileHistory::push() persist-then-swap append (finding 063)
FileHistory::setMaxHistory() live cap; shrinking commits a bounded rewrite before memory follows (finding 065)
FileHistory::flush() drains the deferred queue; throws loudly on refusal
FileHistory::clear() file + memory + queue, atomically
FileHistory::__destruct() auto-flush best effort; queued entries are lost at exit (README Note)
FileHistory::__clone() clones never re-flush the original's queue
FileHistory::FORMAT_HEADER the optional #sugar-readline-history/v2 first line
FileHistory::armRenameSeamForTests() @internal swap-ladder test seam (finding 022)
SearchDirection::Reverse / SearchDirection::Forward the two walk directions (cases()/from()/tryFrom() are the standard enum API)
SearchHit::new() the search result pair
SearchHit::index / ::entry position and text of the hit

Modes

symbol what it does
EmacsMode::__construct() default readline chord set
EmacsMode::handleKey() / consumesCharacters() / name() the mode contract ('emacs')
ViMode::__construct() modal state machine, starts insert
ViMode::handleKey() / consumesCharacters() / name() the mode contract ('vi')
ViMode::viMode() current submode as ViModeState
ViMode::register() the unnamed register's content (secret-scrubbed on hidden prompts)
ViModeState::Insert / Normal / Visual the public submode enum (cases()/from()/tryFrom() standard)

Support classes

symbol what it does
Key::normalize() raw byte/string → canonical 'ctrl_x'-style spelling
Key constants Up, Down, Left, Right, Home, End, PageUp, PageDown, Tab, Enter, ShiftTab, ShiftEnter, AltEnter, Backspace, Delete, Space, Escape, CtrlA, CtrlB, CtrlC, CtrlD, CtrlE, CtrlF, CtrlG, CtrlH, CtrlI, CtrlJ, CtrlK, CtrlL, CtrlM, CtrlN, CtrlO, CtrlP, CtrlQ, CtrlR, CtrlS, CtrlT, CtrlU, CtrlV, CtrlW, CtrlX, CtrlY, CtrlZ, Undo, Redo — the full ctrl letter set (finding 074)
Styles::LABEL / CURSOR / ERROR / COMPLETION / SELECTED the shared default SGR codes
Styles::code() `Style
Ansi::sanitize() strips control bytes from host-supplied content
Ansi::sanitizeForSingleLine() the same sweep, with LF eaten too — a pasted newline must not forge a submit in a one-line prompt
Ansi::wrap() paints a code over text
RowFit::row() cell-clips a segment run to a width
RowFit::clip() single-cell clipping helper
UndoManager::__construct() (int $cap = self::MAX_STATES)
UndoManager::push() records a frame pair; coalesces typing runs
UndoManager::undo() / redo() node-chain walk (finding 078)
UndoManager::canUndo() / canRedo() stack state
UndoManager::MAX_STATES the visible-window cap (512)
UndoState::__construct() @internal cons node (state, older)
Lang::NAMESPACE / Lang::DIR the i18n registration constants

Accessor deprecation (2026-10-24)

Per the house bare-accessor convention (AGENTS.md: "Bare accessors (no get)), the history navigation pair getPrevious()/getNext() was renamed to its bare twins previous()/next(), and the interface moved with the whole family: HistoryInterface now declares only the bare pair (PHP forbids interface method bodies, so the legacy spellings could not ride the contract as default forwarders). InMemoryHistory — and FileHistory by inheritance — keep the old names as byte-identical one-line BC forwarders, each marked @deprecated with REMOVED-IN: 2.0.0 in its docblock — they will be removed in sugar-readline v2.0.0.

Namespace Class Deprecated Use instead
History InMemoryHistory getPrevious() previous()
History InMemoryHistory getNext() next()

Navigation is stateful (each call advances the position cursor), so tests/AccessorDeprecationTest.php pins the BC legs as full walks through both spellings, plus forwarder shape, an interface-contract leg, a discovery-first src/ census, and the README table agreement. Internal call sites in src/ were switched to the bare forms in the same commit.

License

MIT

Credits & inspiration

Design antecedent: erikgeiser/promptkit; SugarCraft is developed as a native PHP project.