Multiline line editor.
The editor stores the full input as a single string whose bytes may include '\n' to mark logical line breaks. position is a byte offset into that string. Cursor motion is implemented in two layers:
- Logical β left/right step over runes ('\n' counts as one cell); home/end snap to the current logical line; word-left/right cross newlines.
- Visual β up/down move by one visual row (which may be the wrapped tail of a long logical line, or a previous logical line); the column is preserved as best-effort.
After every keystroke the entire buffer is repainted in place. The render walks the cursor back to the row where the prompt was first drawn (we track the cursor's row offset from that anchor in renderRow), erases to end of screen, prints the prompt, the text (wrapping at terminal width with the continuation prompt prefixed to each logical line), and finally walks the cursor to the visual position computed from the current position.
All terminal IO goes through the write/getCh procs passed to readLineWith β the public readLine wires them to stdout / getchr. Tests drive the editor through the β¦With form against an in-memory grid, no PTY required.
Types
GetChProc = proc (): int {.closure.}
HasPendingInputProc = proc (): bool {.closure.}
InputCancelled = object of CatchableError
Key = int
KeyCallback = proc (ed: var LineEditor) {.closure.}
Line = object text*: string position*: int
LineEditor = object completionCallback*: proc (ed: LineEditor): seq[string] {.closure.} onMutate*: proc (ed: var LineEditor) {.closure.} onSubmit*: SubmitCallback onCancelDeferredSubmit*: proc (ed: var LineEditor) {.closure.} preRedraw*: proc (ed: var LineEditor) {.closure.} postRedraw*: proc (ed: var LineEditor) {.closure.} redrawWrappedExternally*: bool submitIcon*: string ## Icon written at end of text before submit newline (set before readLineWith). renderSuffix*: string ## Transient suffix rendered after the buffer, not part of submitted text. renderSuffixCursor*: bool ## Place caret after renderSuffix instead of inside editable text. pendingCaret*: bool ## Hide native caret and show a drawn glyph (renderSuffix) as the caret. prefillText*: string history*: LineHistory line*: Line mode*: LineEditorMode prompt*: string contPrompt*: string promptW*: int contPromptW*: int width*: int renderRow*: int write*: WriteProc getCh*: GetChProc hasPendingInput*: HasPendingInputProc getWidth*: WidthProc echoRows*: int submitted*: bool deferSubmit*: bool canceled*: bool eof*: bool hidechars*: bool complPrefix*: string ## original prefix before first completion complMatches*: seq[string] ## current match list complIndex*: int ## current match index (-1 = none)
LineEditorError = ref Exception
LineEditorMode = enum mdInsert, mdReplace
LineError = ref Exception
LineHistory = object file*: string entries*: Deque[string] max*: int cursor*: int drafts*: Table[int, string] cursorPos*: Table[int, int]
-
Two pieces of state, deliberately separate:
- entries is the persistent, on-disk log. New submissions are appended (after dedup + skip-empty); the file mirrors it byte for byte at all times.
- The navigation view (cursor, drafts, cursorPos) is pure in-memory state for the current readLine call. cursor is -1 when the user is on their own draft, otherwise the index into entries they're viewing. Edits the user makes while parked on any view are stashed in drafts/cursorPos so navigating Up then Down brings them back exactly where they left off (text + cursor). The view is wiped on submit.
SubmitCallback = proc (ed: var LineEditor) {.closure.}
WidthProc = proc (): int {.closure.}
WriteProc = proc (s: string) {.closure.}
Vars
KEYMAP {.threadvar.}: CritBitTree[KeyCallback]
KEYNAMES {.threadvar.}: array[0 .. 31, string]
Consts
CTRL = {0..31}
DIGIT = {48..57}
ESCAPES = {27}
EscapeTailPollMs = 250
- Wait long enough for terminal multi-byte escape tails that can be split from the leading ESC by the terminal/PTY stack. Too short a window misclassifies modified keys as bare Escape and leaves their tail bytes to be printed as normal input.
LETTER = {65..122}
LOWERLETTER = {97..122}
PRINTABLE = {32..126}
UPPERLETTER = {65..90}
Procs
proc back(ed: var LineEditor; n = 1) {....raises: [Exception], tags: [RootEffect], forbids: [].}
- Step the cursor left by n runes / newlines.
proc changeLine(ed: var LineEditor; s: string) {....raises: [Exception], tags: [RootEffect], forbids: [].}
- Replace the entire buffer.
proc clearLine(ed: var LineEditor) {....raises: [Exception], tags: [RootEffect], forbids: [].}
- Empty the buffer.
proc completeLine(ed: var LineEditor): int {....raises: [Exception], tags: [RootEffect], forbids: [].}
- First Tab: insert first match. Subsequent Tabs: cycle forward. Returns the non-Tab keystroke that broke the cycle.
proc cursorVisual(text: string; position, promptW, contW, width: int): (int, int) {. ...raises: [], tags: [], forbids: [].}
- (visualRow, visualCol) of the cursor when text[0 ..< position] has been rendered into a width-wide grid with promptW cells reserved before the first logical line and contW cells reserved before each subsequent logical line.
proc deleteNext(ed: var LineEditor) {....raises: [Exception], tags: [RootEffect], forbids: [].}
proc deletePrevious(ed: var LineEditor) {....raises: [Exception], tags: [RootEffect], forbids: [].}
proc deleteWordLeft(ed: var LineEditor) {....raises: [Exception], tags: [RootEffect], forbids: [].}
proc forward(ed: var LineEditor; n = 1) {....raises: [Exception], tags: [RootEffect], forbids: [].}
proc fullRedraw(ed: var LineEditor) {....raises: [Exception], tags: [RootEffect], forbids: [].}
-
Wipe the previously rendered area, repaint prompt + buffer, place the cursor at the visual position derived from ed.line.position. Updates ed.renderRow to match.
All bytes for the repaint are coalesced into a single write call so the underlying stdout.flushFile runs once per keystroke (was: ~5 flushes per redraw, visible on Windows conhost as flicker because conhost paints between flushes). The whole thing is also wrapped in DEC 2026 synchronized-output (CSI ? 2026 h/l) so conhost treats the repaint as one atomic frame; terminals that don't recognize the mode ignore it silently.
proc getchr(): cint {....raises: [IOError, EOFError], tags: [WriteIOEffect, ReadIOEffect], forbids: [].}
-
Retrieves an ASCII character from stdin.
Open-coded raw-mode read (rather than terminal.getch) for two reasons: (1) we deliberately leave c_oflag alone so OPOST/ONLCR stay on β the spinner and bar-tick threads emit bare \n expecting CRLF translation, and a SIGWINCH that interrupted terminal.getch's readChar would bypass its tcSetAttr restore and leave OPOST permanently disabled, which manifests as the dim prompt drifting right by the bar payload's width on every repaint after a resize. (2) try/finally around the read guarantees the original termios is restored on signal interruption.
proc goToBufferEnd(ed: var LineEditor) {....raises: [Exception], tags: [RootEffect], forbids: [].}
proc goToBufferStart(ed: var LineEditor) {....raises: [Exception], tags: [RootEffect], forbids: [].}
proc goToEnd(ed: var LineEditor) {....raises: [Exception], tags: [RootEffect], forbids: [].}
- Move to the end of the current logical line.
proc goToStart(ed: var LineEditor) {....raises: [Exception], tags: [RootEffect], forbids: [].}
- Move to the start of the current logical line.
proc handleEscape(ed: var LineEditor; c1: int): bool {. ...raises: [Exception, KeyError, InputCancelled], tags: [RootEffect], forbids: [].}
- Process a single escape sequence starting just after the leading prefix byte c1 (POSIX: ESC = 27; Windows console: 0 or 224 for extended keys). Returns true if the sequence requested a submit (Shift+Enter / Alt+Enter β these now insert a real newline rather than backslash-continuation).
proc historyAdd(ed: var LineEditor) {....raises: [OSError, IOError], tags: [ WriteDirEffect, ReadDirEffect, WriteIOEffect], forbids: [].}
- Append the just-submitted line to the persistent log. Empty submissions and consecutive duplicates are dropped β they're noise when scrolling back. Writes the file atomically each time.
proc historyFlush(ed: var LineEditor) {....raises: [], tags: [], forbids: [].}
- Reset the navigation view. Called once per submitted line so the next readLine starts fresh on the user's draft slot.
proc historyInit(size = 256; file: string = ""): LineHistory {. ...raises: [IOError], tags: [ReadDirEffect, ReadIOEffect, WriteIOEffect], forbids: [].}
proc historyNext(ed: var LineEditor) {....raises: [KeyError, Exception], tags: [RootEffect], forbids: [].}
- Step one entry newer. Past the last entry, fall back to the user's draft. On the draft already? No-op.
proc historyPrevious(ed: var LineEditor) {....raises: [KeyError, Exception], tags: [RootEffect], forbids: [].}
- Step one entry older. From the draft slot (cursor == -1) this lands on the newest entry. Already at the oldest? Do nothing β including not stashing, so a no-op Up doesn't perturb anything.
proc initEditor(mode = mdInsert; historySize = 256; historyFile: string = ""): LineEditor {. ...raises: [IOError], tags: [ReadDirEffect, ReadIOEffect, WriteIOEffect], forbids: [].}
proc initKeyTables() {....raises: [], tags: [], forbids: [].}
- KEYNAMES, KEYSEQS and KEYMAP are thread-local because display code may temporarily override callbacks. New input threads therefore must populate their own copies before reading keys.
proc insertNewline(ed: var LineEditor) {....raises: [Exception], tags: [RootEffect], forbids: [].}
proc insertText(ed: var LineEditor; s: string) {....raises: [Exception], tags: [RootEffect], forbids: [].}
- Insert s at the current position. Replace mode overwrites runes within the current logical line; newlines in s always insert.
proc lineText(ed: LineEditor): string {....raises: [], tags: [], forbids: [].}
proc password(ed: var LineEditor; prompt = ""): string {. ...raises: [Exception, IOError, EOFError, OSError, InputCancelled, KeyError], tags: [RootEffect, WriteDirEffect, ReadDirEffect, WriteIOEffect], forbids: [].}
proc printChar(ed: var LineEditor; c: int) {....raises: [Exception], tags: [RootEffect], forbids: [].}
proc putchr(c: cint) {.header: "stdio.h", importc: "putchar", ...raises: [], tags: [], forbids: [].}
- Prints an ASCII character to stdout.
proc readLine(ed: var LineEditor; prompt = ""; hidechars = false; noHistory = false): string {. ...raises: [Exception, IOError, EOFError, OSError, InputCancelled, KeyError], tags: [RootEffect, WriteDirEffect, ReadDirEffect, WriteIOEffect], forbids: [].}
proc readLineWith(ed: var LineEditor; prompt: string; getCh: GetChProc; write: WriteProc; hidechars = false; noHistory = false; getWidth: WidthProc = nil; hasPendingInput: HasPendingInputProc = nil): string {....raises: [ Exception, Exception, Exception, IOError, EOFError, OSError, InputCancelled, KeyError], tags: [RootEffect, WriteDirEffect, ReadDirEffect, WriteIOEffect], forbids: [].}
- Pluggable form of readLine. Provides the same behavior as readLine but with explicit IO procs so tests can drive the editor against a fake terminal.
proc redrawBytes(ed: var LineEditor; synchronized = true): string {. ...raises: [Exception], tags: [RootEffect], forbids: [].}
- Build a full editor repaint and update ed.renderRow to the cursor's new visual row. Callers that share a render lock with other terminal chrome can embed these bytes in a larger atomic frame; fullRedraw is the ordinary standalone writer.
proc renderBuffer(text, prompt, cont: string; width: int): string {....raises: [], tags: [], forbids: [].}
- Bytes that paint the buffer. Visual rows are joined with "\r\n" and no trailing newline is emitted. The prompt is written verbatim (so callers can include color escapes); its display width is taken via visualCols. Same for the continuation prompt.
proc renderedRows(ed: LineEditor): int {....raises: [], tags: [], forbids: [].}
- Visual rows currently owned by the editor, including any transient suffix such as the buffered-submit hourglass.
proc restoreTerminal() {.noconv, ...raises: [], tags: [WriteIOEffect], forbids: [].}
- Single point of terminal restore. Registered once as an exit proc and called from signal handlers. Covers cursor visibility, color/style reset, and bracketed-paste teardown.
proc reverseCompleteLine(ed: var LineEditor) {....raises: [Exception], tags: [RootEffect], forbids: [].}
proc terminalHasPendingInput(): bool {....raises: [], tags: [], forbids: [].}
- Return whether stdin has input waiting after a short poll. Used to distinguish bare Escape from ESC-prefixed key sequences.
proc totalRows(text: string; promptW, contW, width: int): int {....raises: [], tags: [], forbids: [].}
- Number of visual rows the rendered buffer occupies, always >= 1.
proc visualCols(s: string): int {....raises: [], tags: [], forbids: [].}
- Number of cells s would occupy when printed. Skips ANSI CSI sequences ESC [ ... <final> so escape codes embedded in a colored prompt don't inflate the count. Wide CJK / emoji count as two cells; combining marks as zero.
proc visualDown(ed: var LineEditor) {....raises: [Exception], tags: [RootEffect], forbids: [].}
proc visualUp(ed: var LineEditor) {....raises: [Exception], tags: [RootEffect], forbids: [].}
- Move up by one visual row, preserving the visual column as best as possible. If already on the top visual row of the buffer, fall back to historyPrevious (Emacs convention).
proc wordLeft(ed: var LineEditor) {....raises: [Exception], tags: [RootEffect], forbids: [].}
proc wordRight(ed: var LineEditor) {....raises: [Exception], tags: [RootEffect], forbids: [].}