From 3021b14aac63b458fbaa589c4a5b02a9dd58c5432bfe7d3e0cb5667d9f618970 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Linus=20Bj=C3=B6rnstam?= Date: Tue, 1 Dec 2026 13:07:56 +0100 Subject: [PATCH] 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 --- examples/repl.bjo | 3 +- manifest.bjodat | 2 +- src/line.bjo | 162 +++++++++++++++++++++++++++++++--------- tests/async.bjo | 3 +- tests/line-terminal.bjo | 1 + tests/line.bjo | 62 +++++++++++++++ tests/reflow.bjo | 3 +- 7 files changed, 198 insertions(+), 38 deletions(-) diff --git a/examples/repl.bjo b/examples/repl.bjo index 345c670..3a236b2 100644 --- a/examples/repl.bjo +++ b/examples/repl.bjo @@ -38,6 +38,7 @@ (match (line-read ed term (styled "λ> " [(StyleFg (Ansi 2)) StyleBold]) #:continuation (Some ".. ")) ((LineText text) (println (str "read: " (written text))) (go)) (LineCancelled (go)) - (LineEof unit))) + (LineEof unit) + ((LineKey _ _) (go)))) (ignore (line-history-save ed history)) 0) diff --git a/manifest.bjodat b/manifest.bjodat index f053daa..5d0fa9e 100644 --- a/manifest.bjodat +++ b/manifest.bjodat @@ -1,6 +1,6 @@ (package (name (bjoterm)) - (version "0.1.0") + (version "0.1.2") (description "The terminal for Bjolang programs: raw mode, key events and escape sequences. Linux.") (license "MPL-2.0") diff --git a/src/line.bjo b/src/line.bjo index 11eefbc..3919663 100644 --- a/src/line.bjo +++ b/src/line.bjo @@ -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) diff --git a/tests/async.bjo b/tests/async.bjo index a3e370b..b70579c 100644 --- a/tests/async.bjo +++ b/tests/async.bjo @@ -48,7 +48,8 @@ (str (match result ((LineText text) (str "read " (written text))) (LineEof "eof") - (LineCancelled "cancelled")) + (LineCancelled "cancelled") + ((LineKey _ _) "key")) (if (> n 5) ", ticks ran" ", no ticks"))) (: (-> LineEditor Terminal string)) diff --git a/tests/line-terminal.bjo b/tests/line-terminal.bjo index 798f4c0..43c2198 100644 --- a/tests/line-terminal.bjo +++ b/tests/line-terminal.bjo @@ -44,6 +44,7 @@ (match (line-read ed term "> " #:notices (Some (fun () (notice flag)))) ((LineText text) (println (str "read: " (written text))) (go)) (LineCancelled (println "cancelled") (go)) + ((LineKey _ _) (go)) (LineEof (println (str "eof, raw: " (if (terminal-raw? term) "yes" "no"))))))))) (: (-> void)) diff --git a/tests/line.bjo b/tests/line.bjo index fc51b36..af883a4 100644 --- a/tests/line.bjo +++ b/tests/line.bjo @@ -42,6 +42,17 @@ out (go (+ i 1) (vec-append out (vec-ref parts i)))))) +;; Suggests "/usr/local/share" for a line that ends with a prefix of it. +(: (-> string (Vec string) (Option string))) +(defun (suggest-path text history) + (def full "/usr/local/share") + (def word (match (string-split-once text " ") + ((Some (Tuple _ w)) w) + (None ""))) + (if (and (not (string-empty? word)) (string-starts-with? full word) (not (= word full))) + (Some (string-drop full (string-length word))) + None)) + ;; ---- running the editor ---------------------------------------------------- (: (-> (Option LineResult) string)) @@ -50,6 +61,7 @@ ((Some (LineText text)) (str "text " (written text))) ((Some LineEof) "eof") ((Some LineCancelled) "cancelled") + ((Some (LineKey ev text)) (str "key " (event->string ev) " " (written text))) (None "not finished"))) ;; The result, or the buffer when the events end first. @@ -202,6 +214,56 @@ (expect "Tab without a completer inserts a tab" (run-fresh (keys [(typed "a") [(key KeyTab)] [enter]])) "text \"a\\t\"") + ;; Suggestions. + (def suggesting (make-line-editor #:suggester (Some suggest-path))) + (expect "Right accepts the suggestion" + (run-on suggesting (keys [(typed "cd /usr/l") [(key KeyRight)]])) + "buffer \"cd /usr/local/share\"") + (expect "and C-f, End and C-e" + (vec-map (fun (k) (run-on suggesting (keys [(typed "cd /usr/l") [k]]))) + [(ctrl #\f) (key KeyEnd) (ctrl #\e)]) + ["buffer \"cd /usr/local/share\"" "buffer \"cd /usr/local/share\"" "buffer \"cd /usr/local/share\""]) + (expect "M-f accepts one word" + (run-on suggesting (keys [(typed "cd /usr/l") [(alt #\f)]])) + "buffer \"cd /usr/local\"") + (expect "and again the next" + (run-on suggesting (keys [(typed "cd /usr/l") [(alt #\f) (alt #\f)]])) + "buffer \"cd /usr/local/share\"") + (expect "C-Right accepts one word" + (run-on suggesting (keys [(typed "cd /usr/l") [(TermKey KeyRight (Mods (shift? #f) (alt? #f) (ctrl? #t)))]])) + "buffer \"cd /usr/local\"") + (expect "Right before the end moves" + (run-on suggesting (keys [(typed "cd /usr/l") [(key KeyLeft) (key KeyRight)] (typed "x")])) + "buffer \"cd /usr/lx\"") + (expect "Right with no suggestion does nothing at the end" + (run-on suggesting (keys [(typed "ls") [(key KeyRight)]])) + "buffer \"ls\"") + (expect "Enter does not accept it" + (run-on suggesting (keys [(typed "cd /usr/l") [enter]])) + "text \"cd /usr/l\"") + (def seen (make-box [])) + (def with-history + (make-line-editor #:suggester (Some (fun (text history) (box-set! seen history) None)))) + (ignore (run-on with-history (keys [(typed "one") [enter]]))) + (ignore (run-on with-history (keys [(typed "t") [(key KeyRight)]]))) + (expect "the suggester gets the history" (box-ref seen) ["one"]) + + ;; Keys that the caller claims. + (def claiming + (make-line-editor #:command-key? + (Some (fun (ev text) (and (string-empty? text) + (= ev (TermKey KeyLeft (Mods (shift? #f) (alt? #t) (ctrl? #f))))))))) + (expect "a claimed key returns LineKey" + (run-on claiming (keys [[(TermKey KeyLeft (Mods (shift? #f) (alt? #t) (ctrl? #f)))]])) + "key key M- \"\"") + (expect "an unclaimed one edits" + (run-on claiming (keys [(typed "ab") [(TermKey KeyLeft (Mods (shift? #f) (alt? #t) (ctrl? #f)))] + (typed "x") [enter]])) + "text \"xab\"") + (expect "#:initial starts with the input" + (simulate-line (make-line-editor) (keys [(typed "!") [enter]]) #:initial "hi") + (Tuple (Some (LineText "hi!")) "hi!")) + ;; The history file. (def path (path-combine (temp-dir) "bjoterm-history-test.txt")) (def saved (make-line-editor)) diff --git a/tests/reflow.bjo b/tests/reflow.bjo index 697ef26..c59ebd3 100644 --- a/tests/reflow.bjo +++ b/tests/reflow.bjo @@ -36,7 +36,8 @@ (match result ((LineText text) (str "read " (int->string (string-length text)))) (LineEof "eof") - (LineCancelled "cancelled"))) + (LineCancelled "cancelled") + ((LineKey _ _) "key"))) (: (-> bool void)) (defun (child reflow?)