All 42 libraries

SugarReadline

Interactive line-editing prompt state machines for terminal UIs — text, selection, multi-select, textarea and confirmation prompts

Design antecedent: erikgeiser/promptkit promptinputreadlineinteractive

SugarReadline code coverage

Text, selection, multi-select, textarea and confirmation prompts with full keyboard handling, filter-as-you-type and pagination. Prompts are pure state machines — drive them directly, or let Readline wire them to a real TTY. No external readline dependency.

Install

composer require sugarcraft/sugar-readline

No tagged release exists yet; dev-master is the only resolvable constraint. From a checkout of the library, run composer install inside sugar-readline/ before executing the examples/ scripts.

Quick Start

use SugarCraft\Readline\{Key, MultiSelectPrompt, SelectionPrompt, TextPrompt};

// Prompts are immutable state machines: feed input, read the result.
$name = TextPrompt::new('Your name:')
    ->handleChar('A')->handleChar('d')->handleChar('a')
    ->submit();
$name->value();                                 // 'Ada'

$lang = SelectionPrompt::new('Pick a language:', ['PHP', 'Go', 'Rust', 'Python'])
    ->handleKey(Key::Down)
    ->handleKey(Key::Enter);
$lang->selectedValue();                         // 'Go'

// Multi-select with constraints: Space toggles, Enter submits only when allowed
$tools = MultiSelectPrompt::new('Pick tools:', ['vim', 'git', 'docker', 'php'])
    ->withMinSelections(1)
    ->withMaxSelections(3)
    ->handleKey(Key::Space)->handleKey(Key::Down)->handleKey(Key::Space)
    ->handleKey(Key::Enter);
$tools->selectedValues();                       // ['vim', 'git']

For a real terminal, the same prompts run under Readline, which reads keypresses through a sugar-input driver, repaints view() as you type and hands back a typed ReadlineResult — the finished answer, its submission state and the final prompt. Pass an output stream (the terminal needs non-canonical mode for arrows and chords — the README's "Terminal mode" section carries the stty recipe):

use SugarCraft\Readline\{Readline, TextPrompt};

$result = Readline::fromStdin()->run(TextPrompt::new('Your name: '), STDOUT);
$result->submitted;                         // false (pending) on Esc/Ctrl+C; left unsubmitted at EOF when Readline owns the pump
$result->value;                             // the finished answer
$result->prompt;                             // the final prompt object

What's in the box

TextPromptSingle-line input with default value, password masking, completions, validation, history, reverse search and autosuggest (on by default with history).
ConfirmationPromptYes/No with customizable labels and default.
SelectionPromptArrow-key selection with filter-as-you-type and pagination.
MultiSelectPromptMulti-item selection with min/max enforcement, marker (◉/○), pagination.
TextareaPromptMulti-line editor with cursor movement and an explicit newline channel.
Untrusted contentEvery emission choke sanitizes displayed content (C0/DEL stripped, CR included) so choices and candidates cannot inject escape sequences; returned values keep raw bytes and are the host's to sanitize before printing.

Source & demos

Try the quickstart →

API

ClassMethodDescription
TextPromptstatic new(label) / withDefault() / withHidden() / withCompletions() / withValidator() / withCharLimit() / withHistory() / withAutoSuggest(bool) / withUndoManager(manager) / withDisplayWidth() / withMode()Single-line input; autosuggest is enabled by default whenever history is attached; withValidator(): return a non-empty string to reject and paint that string as the error row; return false/''/null to reject with the default Invalid input; a truthy non-string accepts, and a throwing validator is contained as a default rejection
TextPrompthandleChar(char) / handleKey(key) / insertPastedText(text) / submit() / abort() / value() / isSubmitted() / mode()Drive the prompt and read the result
ConfirmationPromptstatic new(label, defaultValue = false) / withConfirmLabel() / withCancelLabel() / withHint() / handleKey() / submit() / abort() / result() / currentValue() / isSubmitted() / isAborted()Yes/No prompt (y/n or the Left/Right arrows set the choice with one keystroke; Tab or Space toggles; Enter submits, Escape/Ctrl+C aborts — every key, letters included, arrives through the single normalized handleKey() seam; there is no handleChar())
SelectionPromptstatic new(label, choices) / withPageSize() / withFilter() / handleChar() / handleKey() / selectedValue()Single choice with type-to-filter and pagination (PageUp/PageDown jump pages)
MultiSelectPromptstatic new(label, choices) / withMinSelections(n) / withMaxSelections(n) / handleChar() / handleKey() / selectedValues() / canSubmit()Several choices with min/max enforcement
TextareaPromptstatic new(label) / withDefault() / withMaxLines() / handleChar() / handleKey() / insertPastedText() / value() / lines()Multi-line editor: Enter submits, Shift+Enter/Ctrl+J break lines on terminals that honor the pump's kitty-keyboard negotiation (where the wire never reports modifiers, both bytes are a plain Enter and submit)
ReadlinefromStdin() / new Readline($driver = null) / onKey(name, handler) / onMouse() / onFocus() / onPaste() / stop() / run(prompt, output)TTY loop: feeds key events into any prompt and repaints it
Mode\EmacsMode · Mode\ViModeattach via TextPrompt::withMode()Editing modes; vi normal drives history (j/k), edits (x), the unnamed register (yy/dd/diw → p) and undo (u)
History\InMemoryHistorynew(maxHistory = 0) / push() / previous() / next() / search(query, fromIndex, direction) / reset() / clear()Per-process store; collapses adjacent duplicates
History\FileHistorynew(filePath, maxHistory = 0, tempDir = '', deferWrites = false) / push() / flush() / clear() / search()Cross-process history: 0600 file, escaped one-line entries, sidecar-locked bounded writes, symlinked paths refused; deferred pushes stay queued until flush() and are lost on a hard kill (SIGKILL)
UndoManagerpush(state) / undo(current) / redo(current) / canUndo() / canRedo()Immutable bounded (512) snapshot stack; attach via withUndoManager(). undo/redo take the current buffer string and return a [manager, state, ok] triple — a host driving the manager directly must re-attach the returned manager, exactly as TextPrompt does internally
KeyUp, Down, Enter, Space, Escape, CtrlC, …Canonical key names for handleKey() — raw control bytes normalize to the same language

Demos.

VHS-recorded GIFs from the shipped demos. Regenerated automatically on every push that touches the source.

Text prompt

Text prompt

A guided tour of four shipped prompt types: text, selection, textarea and confirmation.
Multi-select

Multi-select

Multi-select list with toggle + submit.