line-read: suggestions, keys for the caller, initial input; 0.1.2

#:suggester shows a suggestion after the input, dimmed, as fish does. Right,
C-f, End and C-e at the end accept it; M-f, C-Right and M-Right one word.
#:command-key? hands keys to the caller as (LineKey key input), with the
input erased. line-read and simulate-line take #:initial.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Linus Björnstam 2026-12-01 13:07:56 +01:00
parent dc8a3325b8
commit 3021b14aac
7 changed files with 198 additions and 38 deletions

View file

@ -28,6 +28,10 @@
;; computes where the input starts then; see `#:reflow?`.
;; - The history belongs to the editor. Accepted lines that are not empty
;; and not the same as the last one are added to it.
;; - `#:suggester` shows a suggestion after the input, dimmed, as fish does.
;; Keys that move right at the end of the input accept it.
;; - `#:command-key?` hands keys to the caller: `line-read` erases the input
;; and returns `LineKey`.
;; - The design is in plan.org, phase 2.
(import (std prelude))
@ -49,7 +53,10 @@
;; - `LineText`: the accepted input. Lines are separated by "\n".
;; - `LineEof`: Ctrl-D on an empty buffer, or the terminal hung up.
;; - `LineCancelled`: Ctrl-C. The input is left on the screen with "^C".
(type (: LineResult (Union (: LineText string) LineEof LineCancelled)))
;; - `LineKey`: a key that `#:command-key?` claimed, and the input when it
;; was pressed. The input is erased from the screen, prompt included, so
;; the next `line-read` draws in its place.
(type (: LineResult (Union (: LineText string) LineEof LineCancelled (: LineKey TermEvent string))))
;; What a completer returns for the text before the cursor.
;; - `prefix`: the end of that text that the candidates replace, such as
@ -61,6 +68,8 @@
;; A line editor: its options and its history.
(type (: LineEditor #:opaque
(Record (: completer (Option (-> string Completion)))
(: suggester (Option (-> string (Vec string) (Option string))))
(: command-key? (Option (-> TermEvent string bool)))
(: input-done? (Option (-> string bool)))
(: history-size int)
(: reflow? (Option bool))
@ -105,6 +114,11 @@
;; - `#:completer`: called by Tab with the text before the cursor.
;; - `#:input-done?`: called by Enter with the whole input. #f makes Enter
;; start a new line; a REPL returns #f while brackets are open.
;; - `#:suggester`: called with the whole input and the history, oldest
;; first, while the cursor is at the end of the input. Returns the text to
;; show after the input, or None. Called after each key, so it must be fast.
;; - `#:command-key?`: called with each key and the whole input. #t makes
;; `line-read` return `(LineKey key input)`.
;; - `#:history-size`: the most entries kept; the oldest go first.
;; - `#:suspend?`: whether C-z stops the program. A shell sets #f; C-z
;; then rings the bell.
@ -113,14 +127,17 @@
;; above the input when the terminal narrows; a wrong #f leaves a copy of
;; the input above it.
(: (-> (#:completer (Option (-> string Completion)))
(#:suggester (Option (-> string (Vec string) (Option string))))
(#:command-key? (Option (-> TermEvent string bool)))
(#:input-done? (Option (-> string bool)))
(#:history-size int)
(#:reflow? (Option bool))
(#:suspend? bool)
LineEditor))
(defun (make-line-editor #:completer None #:input-done? None #:history-size 1000 #:reflow? None
#:suspend? #t)
(LineEditor (completer completer) (input-done? input-done?)
(defun (make-line-editor #:completer None #:suggester None #:command-key? None #:input-done? None
#:history-size 1000 #:reflow? None #:suspend? #t)
(LineEditor (completer completer) (suggester suggester) (command-key? command-key?)
(input-done? input-done?)
(history-size history-size) (reflow? reflow?) (suspend? suspend?) (history [])))
;; The history, oldest first.
@ -204,6 +221,8 @@
;; searches back, again C-r for an older match, C-g ends the search.
;; - Tab completes with `#:completer`, and a second Tab lists the
;; candidates. Without a completer it inserts a tab.
;; - A suggestion from `#:suggester`: at the end of the input, Right, C-f,
;; End and C-e accept all of it; M-f, C-Right and M-Right one word.
;; - Enter accepts (see `#:input-done?`), M-Enter and C-j start a new line,
;; C-l clears the screen, C-z stops the program (see `#:suspend?`),
;; C-c cancels, and C-d on an empty buffer is end of input.
@ -211,18 +230,24 @@
;; `notice-poll-ms` while it waits for a key. The lines it returns are
;; written above the input, which is then drawn again below them. For a
;; shell's "[1] Done" lines. It must not write to the terminal itself.
;; - `#:initial`: the input to start with, the cursor at its end.
(: (-> LineEditor Terminal string (#:continuation (Option string)) (#:notices (Option (-> (Vec string))))
(#:initial string)
LineResult))
(defun (line-read ed term prompt #:continuation None #:notices None)
(defun (line-read ed term prompt #:continuation None #:notices None #:initial "")
(def cont (match continuation
((Some c) c)
(None (string-pad-left "" (text-width (last-line prompt))))))
(if (terminal-raw? term)
(edit-loop ed term prompt cont notices)
(edit-loop ed term prompt cont notices initial)
;; A `fun` is ordinary code, so the suspending copy passes a
;; bjoroutine.
(by-colour (#:sync (with-raw-mode term (fun () (edit-loop ed term prompt cont notices))))
(#:bjo (with-raw-mode term (bjoroutine () (edit-loop ed term prompt cont notices)))))))
(by-colour (#:sync (with-raw-mode term (fun () (edit-loop ed term prompt cont notices initial))))
(#:bjo (with-raw-mode term (bjoroutine () (edit-loop ed term prompt cont notices initial)))))))
;; How a suggestion is drawn: bright black, which most themes show as grey.
(: (Vec Style))
(def ghost-style [(StyleFg (Ansi 8))])
;; How often `line-read` calls its `#:notices` function, in milliseconds.
(: notice-poll-ms int)
@ -236,14 +261,15 @@
((Some (Tuple _ after)) (go after))
(None rest))))
(: (-> LineEditor State))
(defun (start-state ed)
(State (text []) (cursor 0) (kill "") (killing? #f)
(: (-> LineEditor string State))
(defun (start-state ed initial)
(def text (clusters initial))
(State (text text) (cursor (vec-length text)) (kill "") (killing? #f)
(hist-at (vec-length (record-ref ed history))) (draft [])
(search None) (tabbed? #f)))
(: (-> LineEditor Terminal string string (Option (-> (Vec string))) LineResult))
(defun (edit-loop ed term prompt cont notices)
(: (-> LineEditor Terminal string string (Option (-> (Vec string))) string LineResult))
(defun (edit-loop ed term prompt cont notices initial)
(def out (parameter-ref current-output-port))
(def reflow? (match (record-ref ed reflow?)
((Some r) r)
@ -265,9 +291,15 @@
(record-ref l cursor-col) width)
(record-ref l cursor-row)))))
;; Draws `st`: the rows that fit on the screen, or all when `whole?`.
;; The suggestion is drawn unless `whole?`.
(defun (draw st whole?)
(def (Tuple width height) (terminal-size term))
(def lay (layout-state st prompt cont width))
(def ghost (if whole?
[]
(match (suggestion ed st)
((Some s) (clusters s))
(None []))))
(def lay (layout-state st prompt cont width ghost))
(def shown (window-of lay width (if whole? None (Some height)) top))
(write-string out (str "\r" (cursor-up (rows-up width)) clear-below
(record-ref shown text)
@ -303,7 +335,7 @@
(set! drawn None)
(ignore (draw st #f)))
(poll)))))))
(let go ((st (start-state ed)))
(let go ((st (start-state ed initial)))
(def lay (draw st #f))
(match (line-step ed st (next-event st))
((Edited next) (go next))
@ -320,9 +352,17 @@
(leave lay)
(write-string out (columns items (fst (terminal-size term))))
(go next))
((Finished _ (LineKey ev text))
(def (Tuple width _) (terminal-size term))
(write-string out (str "\r" (cursor-up (rows-up width)) clear-below))
(set! drawn None)
(flush-port out)
(LineKey ev text))
((Finished last result)
(def shown (draw (record-set last (search None) (cursor (vec-length (record-ref last text)))) #t))
(when (= result LineCancelled) (write-string out "^C"))
(match result
(LineCancelled (write-string out "^C"))
(_ unit))
(leave shown)
(flush-port out)
(match result
@ -352,9 +392,9 @@
;; Runs the editor on `events` without a terminal, as `line-read` would.
;; Returns the result, or None when the events ran out first, and the
;; buffer's text at the end. For tests.
(: (-> LineEditor (Vec TermEvent) (Tuple (Option LineResult) string)))
(defun (simulate-line ed events)
(let go ((st (start-state ed))
(: (-> LineEditor (Vec TermEvent) (#:initial string) (Tuple (Option LineResult) string)))
(defun (simulate-line ed events #:initial "")
(let go ((st (start-state ed initial))
(i 0))
(if (= i (vec-length events))
(Tuple None (joined (record-ref st text)))
@ -385,20 +425,21 @@
(type (: Layout (Record (: texts (Vec string)) (: rows (Vec (Vec int)))
(: cursor-row int) (: cursor-col int))))
(: (-> State string string int Layout))
(defun (layout-state st prompt cont width)
(: (-> State string string int (Vec string) Layout))
(defun (layout-state st prompt cont width ghost)
(match (record-ref st search)
((Some s)
(def label (str "(" (if (record-ref s failed?) "failed " "")
"search `" (record-ref s query) "'): "))
(layout (prompt-clusters label) (prompt-clusters cont)
(record-ref st text) (record-ref st cursor) width))
(record-ref st text) (record-ref st cursor) width []))
(None
(layout (prompt-clusters prompt) (prompt-clusters cont)
(record-ref st text) (record-ref st cursor) width))))
(record-ref st text) (record-ref st cursor) width ghost))))
(: (-> (Vec string) (Vec string) (Vec string) int int Layout))
(defun (layout prompt cont text cursor width)
;; `ghost`: clusters drawn dimmed after `text`, where the cursor does not go.
(: (-> (Vec string) (Vec string) (Vec string) int int (Vec string) Layout))
(defun (layout prompt cont text cursor width ghost)
(def out (stringbuilder-empty))
(def/mutable texts [])
(def/mutable row 0)
@ -444,6 +485,15 @@
(when (= cursor (vec-length text))
(set! cursor-row row)
(set! cursor-col col))
(loop (:for c (in-vec ghost))
(:do (cond
((or (= c "\n") (= c "\r\n"))
(break!)
(put-prompt! cont))
((= c "\t")
(def w (- 8 (remainder col 8)))
(put! (string-pad-left "" w) w))
(else (put! (styled (cluster-shown c) ghost-style) (cluster-width c))))))
(Layout (texts (vec-add texts (stringbuilder->string out)))
(rows (vec-add rows this-row))
(cursor-row cursor-row) (cursor-col cursor-col)))
@ -535,6 +585,39 @@
;; Editing
;; ===========================================================================
;; The suggestion for `st`: the text after the input, not empty. None during
;; a search, when the cursor is not at the end, or the input is empty.
(: (-> LineEditor State (Option string)))
(defun (suggestion ed st)
(def text (record-ref st text))
(match (record-ref ed suggester)
(None None)
((Some f)
(if (or (some? (record-ref st search))
(vec-empty? text)
(not (= (record-ref st cursor) (vec-length text))))
None
(match (f (joined text) (record-ref ed history))
((Some s) (if (string-empty? s) None (Some s)))
(None None))))))
;; At the end of the input with a suggestion, adds all of it, or with
;; `word?` up to the end of its first word. Else `otherwise`.
(: (-> LineEditor State bool (-> Step) Step))
(defun (accept-suggestion ed st word? otherwise)
(match (suggestion ed st)
(None (otherwise))
((Some s)
(if (not word?)
(Edited (insert st s))
(let* ((cs (clusters s))
(n (vec-length cs))
(gap (let go ((i 0))
(if (and (< i n) (not (word-cluster? (vec-ref cs i)))) (go (+ i 1)) i)))
(end (let go ((i gap))
(if (and (< i n) (word-cluster? (vec-ref cs i))) (go (+ i 1)) i))))
(Edited (insert st (joined (vec-slice cs 0 end)))))))))
(: (-> (Vec string) string))
(defun (joined text)
(string-join text ""))
@ -749,9 +832,16 @@
;; What `ev` does to `st`.
(: (-> LineEditor State TermEvent Step))
(defun (line-step ed prev ev)
(match (record-ref prev search)
((Some s) (searching ed prev s ev))
(None (editing ed prev ev))))
(def claimed? (and (none? (record-ref prev search))
(match (record-ref ed command-key?)
((Some f) (f ev (joined (record-ref prev text))))
(None #f))))
(cond
(claimed? (Finished prev (LineKey ev (joined (record-ref prev text)))))
(else
(match (record-ref prev search)
((Some s) (searching ed prev s ev))
(None (editing ed prev ev))))))
(: (-> LineEditor State TermEvent Step))
(defun (editing ed prev ev)
@ -780,16 +870,20 @@
;; Moving.
((Tuple KeyLeft (Tuple #f #f)) (Edited (move st (max 0 (- cursor 1)))))
((Tuple (KeyChar #\b) (Tuple #t #f)) (Edited (move st (max 0 (- cursor 1)))))
((Tuple KeyRight (Tuple #f #f)) (Edited (move st (min n (+ cursor 1)))))
((Tuple (KeyChar #\f) (Tuple #t #f)) (Edited (move st (min n (+ cursor 1)))))
((Tuple KeyRight (Tuple #f #f))
(accept-suggestion ed st #f (fun () (Edited (move st (min n (+ cursor 1)))))))
((Tuple (KeyChar #\f) (Tuple #t #f))
(accept-suggestion ed st #f (fun () (Edited (move st (min n (+ cursor 1)))))))
((Tuple KeyLeft _) (Edited (move st (word-back st))))
((Tuple (KeyChar #\b) (Tuple #f #t)) (Edited (move st (word-back st))))
((Tuple KeyRight _) (Edited (move st (word-forward st))))
((Tuple (KeyChar #\f) (Tuple #f #t)) (Edited (move st (word-forward st))))
((Tuple KeyRight _) (accept-suggestion ed st #t (fun () (Edited (move st (word-forward st))))))
((Tuple (KeyChar #\f) (Tuple #f #t))
(accept-suggestion ed st #t (fun () (Edited (move st (word-forward st))))))
((Tuple KeyHome _) (Edited (move st (line-start st))))
((Tuple (KeyChar #\a) (Tuple #t #f)) (Edited (move st (line-start st))))
((Tuple KeyEnd _) (Edited (move st (line-end st))))
((Tuple (KeyChar #\e) (Tuple #t #f)) (Edited (move st (line-end st))))
((Tuple KeyEnd _) (accept-suggestion ed st #f (fun () (Edited (move st (line-end st))))))
((Tuple (KeyChar #\e) (Tuple #t #f))
(accept-suggestion ed st #f (fun () (Edited (move st (line-end st))))))
;; Lines, then the history.
((Tuple KeyUp _)
(match (vertical st #t)