bjoterm: the line editor, (bjoterm line)

- line-read with the keys of Emacs and readline: moving by character,
  word and line, a kill buffer, history with C-r search, Tab completion
  through #:completer, and input of several lines with #:input-done?.
- Grapheme clusters and display widths in glue/Text.cs: the editor moves
  and deletes by cluster, and wraps lines by width.
- Each key is a pure step, so tests/line.bjo runs the keys without a
  terminal through simulate-line. tests/line-terminal.bjo runs line-read
  on a pseudo-terminal.
- History files, line-history-save and line-history-load!.
- examples/repl.bjo: a small REPL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Linus Björnstam 2026-11-30 20:49:26 +01:00
parent fe42387a4c
commit 6863503fa7
7 changed files with 1235 additions and 2 deletions

74
tests/line-terminal.bjo Normal file
View file

@ -0,0 +1,74 @@
;; This Source Code Form is subject to the terms of the Mozilla Public
;; License, v. 2.0. If a copy of the MPL was not distributed with this
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
;; `line-read` on a real terminal: what it returns, and what it leaves on
;; the screen.
;;
;; bjo test tests/line-terminal.bjo
;;
;; The test runs itself again under `script`, and writes keys to it with
;; pauses between them, as tests/terminal.bjo does.
(import (std prelude))
(import (std simpletest))
(import (std run))
(import (bjoterm terminal))
(import (bjoterm line))
(import/extern
(command-line (: System.Environment.GetCommandLineArgs (-> (Array string)) #:no-raise)))
(: (-> string bool))
(defun (balanced? text)
(<= (loop (:for c (in-vec (string->vec text)))
(:acc d (summing (cond ((= c #\() 1) ((= c #\)) -1) (else 0)))))
0))
(: (-> void))
(defun (child)
(match (terminal-open)
((Err e) (println (str "open: " (terminal-error-message e))))
((Ok term)
(def ed (make-line-editor #:input-done? (Some balanced?)))
(let go ()
(match (line-read ed term "> ")
((LineText text) (println (str "read: " (written text))) (go))
(LineCancelled (println "cancelled") (go))
(LineEof (println (str "eof, raw: " (if (terminal-raw? term) "yes" "no")))))))))
(: (-> void))
(defun (parent)
(def self (str "dotnet " (array-ref (command-line) 0)))
;; Each step waits, so that the child reads each key on its own.
(def keys (string-join ["sleep 2" "printf 'one\\r'" "sleep 0.3"
"printf '(a'" "sleep 0.2" "printf '\\r'" "sleep 0.2" "printf 'b)\\r'" "sleep 0.3"
"printf 'gone'" "sleep 0.2" "printf '\\003'" "sleep 0.3"
"printf '\\020'" "sleep 0.2" "printf '\\020'" "sleep 0.2" "printf '!\\r'" "sleep 0.3"
"printf '\\004'" "sleep 1"]
"; "))
(def command (str "(" keys ") | script -qec 'stty cols 40 rows 20; " self " child' /dev/null"))
(def out (match (run/output '(sh "-c" ,command))
((Ok (Tuple _ text)) (string-replace text "\r" ""))
((Err e) (run-error-message e))))
(expect-true "the terminal opens" (not (string-contains? out "open:")))
(expect-true "a line" (string-contains? out "read: \"one\""))
(expect-true "Enter in open brackets starts a new line" (string-contains? out "read: \"(a\\nb)\""))
(expect-true "the continuation prompt is as wide as the prompt" (string-contains? out "\n b)"))
(expect-true "C-c cancels" (string-contains? out "cancelled"))
;; The cursor goes to the end of the input with an escape sequence, so
;; "gone" and "^C" are not next to each other in the output.
(expect-true "and leaves the input with ^C" (string-contains? out "^C\ncancelled"))
;; C-p, not Up: Up in the two lines of the newer entry moves up a line.
(expect-true "C-p twice shows an older entry" (string-contains? out "read: \"one!\""))
(expect-true "C-d on an empty line is end of input, and raw mode is over"
(string-contains? out "eof, raw: no"))
(unless (string-contains? out "eof, raw: no")
(println out)))
(defun (main args)
(cond
((= args ["child"]) (child))
((file-exists? "/usr/bin/script") (parent))
(else (println "skipped: no script command")))
0)

219
tests/line.bjo Normal file
View file

@ -0,0 +1,219 @@
;; This Source Code Form is subject to the terms of the Mozilla Public
;; License, v. 2.0. If a copy of the MPL was not distributed with this
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
;; The line editor's keys, history and completion, without a terminal.
;;
;; bjo test tests/line.bjo
(import (std prelude))
(import (std simpletest))
(import (bjoterm terminal))
(import (bjoterm line))
(import/extern (temp-dir (: System.IO.Path.GetTempPath (-> string))))
;; ---- events ----------------------------------------------------------------
(: (-> string (Vec TermEvent)))
(defun (typed s)
(vec-map (fun (c) (TermKey (KeyChar c) no-mods)) (string->vec s)))
(: (-> char TermEvent))
(defun (ctrl c)
(TermKey (KeyChar c) (Mods (shift? #f) (alt? #f) (ctrl? #t))))
(: (-> char TermEvent))
(defun (alt c)
(TermKey (KeyChar c) (Mods (shift? #f) (alt? #t) (ctrl? #f))))
(: (-> Key TermEvent))
(defun (key k)
(TermKey k no-mods))
(: TermEvent)
(def enter (key KeyEnter))
;; The events, one after the other.
(: (-> (Vec (Vec TermEvent)) (Vec TermEvent)))
(defun (keys parts)
(let go ((i 0) (out []))
(if (= i (vec-length parts))
out
(go (+ i 1) (vec-append out (vec-ref parts i))))))
;; ---- running the editor ----------------------------------------------------
(: (-> (Option LineResult) string))
(defun (result-text r)
(match r
((Some (LineText text)) (str "text " (written text)))
((Some LineEof) "eof")
((Some LineCancelled) "cancelled")
(None "not finished")))
;; The result, or the buffer when the events end first.
(: (-> LineEditor (Vec TermEvent) string))
(defun (run-on ed events)
(match (simulate-line ed events)
((Tuple None buffer) (str "buffer " (written buffer)))
((Tuple r _) (result-text r))))
(: (-> (Vec TermEvent) string))
(defun (run-fresh events)
(run-on (make-line-editor) events))
(: (-> string (Vec (Vec TermEvent)) string void))
(defun (expect-line name parts wanted)
(expect name (run-fresh (keys parts)) wanted))
;; Open brackets make the input incomplete, as in a Lisp REPL.
(: (-> string bool))
(defun (balanced? text)
(def depth (loop (:for c (in-vec (string->vec text)))
(:acc d (summing (cond ((= c #\() 1) ((= c #\)) -1) (else 0))))))
(<= depth 0))
(: (Vec string))
(def words ["vec-map" "vec-add" "vector" "display"])
;; Completes the last word from `words`.
(: (-> string Completion))
(defun (complete-word before)
(def parts (string-split before " "))
(def word (if (vec-empty? parts) "" (vec-ref parts (- (vec-length parts) 1))))
(Completion (prefix word)
(candidates (vec-map (fun (w) (str w " "))
(vec-filter (fun (w) (string-starts-with? w word)) words)))))
(defun (main args)
;; Typing and accepting.
(expect-line "typing and Enter" [(typed "hello") [enter]] "text \"hello\"")
(expect-line "the events end first" [(typed "hel")] "buffer \"hel\"")
(expect-line "C-d on an empty buffer" [[(ctrl #\d)]] "eof")
(expect-line "C-d deletes under the cursor" [(typed "ab") [(ctrl #\a) (ctrl #\d)] [enter]] "text \"b\"")
(expect-line "C-c cancels" [(typed "abc") [(ctrl #\c)]] "cancelled")
(expect-line "the terminal hangs up" [(typed "abc") [TermEnd]] "eof")
(expect-line "a paste is inserted" [(typed "a") [(TermPaste "x\ny")] (typed "b") [enter]] "text \"ax\\nyb\"")
;; Moving.
(expect-line "Left and insert" [(typed "helo") [(key KeyLeft)] (typed "l") [enter]] "text \"hello\"")
(expect-line "C-a and C-e" [(typed "bc") [(ctrl #\a)] (typed "a") [(ctrl #\e)] (typed "d") [enter]]
"text \"abcd\"")
(expect-line "M-b and M-f" [(typed "one two") [(alt #\b) (alt #\b) (alt #\f)] (typed "!") [enter]]
"text \"one! two\"")
(expect-line "C-Left by word"
[(typed "one two") [(TermKey KeyLeft (Mods (shift? #f) (alt? #f) (ctrl? #t)))] (typed "_") [enter]]
"text \"one _two\"")
;; Deleting and the kill buffer.
(expect-line "Backspace" [(typed "abc") [(key KeyBackspace)] [enter]] "text \"ab\"")
(expect-line "Delete" [(typed "abc") [(ctrl #\a) (key KeyDelete)] [enter]] "text \"bc\"")
(expect-line "C-k and C-y" [(typed "abcd") [(ctrl #\a) (ctrl #\f) (ctrl #\k)] [(ctrl #\a) (ctrl #\y)] [enter]]
"text \"bcda\"")
(expect-line "C-u kills to the start" [(typed "abcd") [(ctrl #\b) (ctrl #\u)] [enter]] "text \"d\"")
(expect-line "C-w kills a word" [(typed "foo bar") [(ctrl #\w)] [enter]] "text \"foo \"")
(expect-line "kills one after another add up" [(typed "a b c") [(ctrl #\w) (ctrl #\w) (ctrl #\y)] [enter]]
"text \"a b c\"")
;; The second C-w takes only "b": the cursor is before the space.
(expect-line "a key between kills starts a new kill"
[(typed "a b c") [(ctrl #\w) (key KeyLeft) (ctrl #\w) (ctrl #\e) (ctrl #\y)] [enter]]
"text \"a b\"")
(expect-line "M-d kills the next word" [(typed "one two") [(ctrl #\a) (alt #\d)] [enter]] "text \" two\"")
(expect-line "C-t swaps at the end" [(typed "ab") [(ctrl #\t)] [enter]] "text \"ba\"")
(expect-line "C-t swaps in the middle" [(typed "abc") [(ctrl #\a) (ctrl #\f) (ctrl #\t)] [enter]]
"text \"bac\"")
;; Grapheme clusters.
(expect-line "a combining mark joins the letter before it"
[(typed "e") [(TermKey (KeyChar (int->char 769)) no-mods) (key KeyBackspace)] [enter]]
"text \"\"")
(expect-line "an emoji with a modifier is one cluster"
[[(TermPaste "a👍🏽b")] [(key KeyLeft) (key KeyLeft) (key KeyBackspace)] [enter]]
"text \"👍🏽b\"")
;; Several lines.
(expect-line "M-Enter starts a new line" [(typed "a") [(TermKey KeyEnter (Mods (shift? #f) (alt? #t) (ctrl? #f)))]
(typed "b") [enter]]
"text \"a\\nb\"")
(expect-line "C-j starts a new line" [(typed "a") [(ctrl #\j)] (typed "b") [enter]] "text \"a\\nb\"")
(expect "Enter in incomplete input starts a new line"
(run-on (make-line-editor #:input-done? (Some balanced?))
(keys [(typed "(+ 1") [enter] (typed "2)") [enter]]))
"text \"(+ 1\\n2)\"")
(expect-line "Up moves to the line above, at the same column"
[(typed "abc") [(ctrl #\j)] (typed "de") [(key KeyUp)] (typed "X") [enter]]
"text \"abXc\\nde\"")
(expect-line "Down moves to the line below, as far as it reaches"
[(typed "abcdef") [(ctrl #\j)] (typed "x") [(key KeyUp) (ctrl #\e) (key KeyDown)] (typed "Y") [enter]]
"text \"abcdef\\nxY\"")
(expect-line "C-a goes to the start of the line" [(typed "ab") [(ctrl #\j)] (typed "cd") [(ctrl #\a)] (typed "X") [enter]]
"text \"ab\\nXcd\"")
(expect-line "C-k at the end of a line joins the next"
[(typed "ab") [(ctrl #\j)] (typed "cd") [(key KeyUp) (ctrl #\e) (ctrl #\k)] [enter]]
"text \"abcd\"")
;; History.
(def ed (make-line-editor #:history-size 3))
(ignore (run-on ed (keys [(typed "one") [enter]])))
(ignore (run-on ed (keys [(typed "two") [enter]])))
(ignore (run-on ed (keys [(typed "two") [enter]])))
(ignore (run-on ed (keys [[enter]])))
(expect "accepted lines go to the history, not repeats or empty ones" (line-history ed) ["one" "two"])
(expect "Up shows the last entry" (run-on ed (keys [[(key KeyUp)] [enter]])) "text \"two\"")
(expect "Up twice, and Down" (run-on ed (keys [[(key KeyUp) (key KeyUp) (key KeyUp) (key KeyDown)] [enter]]))
"text \"two\"")
(expect "Down past the newest shows the draft"
(run-on ed (keys [(typed "draft") [(ctrl #\p) (ctrl #\p) (ctrl #\n) (ctrl #\n) (ctrl #\n)]]))
"buffer \"draft\"")
(line-history-add! ed "three")
(line-history-add! ed "four")
(expect "the oldest entry goes above the size" (line-history ed) ["two" "three" "four"])
;; Search.
(def searched (make-line-editor))
(loop (:for e (in-vec ["make build" "make test" "git status" "make install"]))
(:do (line-history-add! searched e)))
(expect "C-r finds the newest match" (run-on searched (keys [[(ctrl #\r)] (typed "make") [enter]]))
"text \"make install\"")
(expect "C-r again finds an older one" (run-on searched (keys [[(ctrl #\r)] (typed "make") [(ctrl #\r)] [enter]]))
"text \"make test\"")
(expect "a longer query narrows the match" (run-on searched (keys [[(ctrl #\r)] (typed "make b") [enter]]))
"text \"make build\"")
(expect "C-g ends the search and restores the input"
(run-on searched (keys [(typed "x") [(ctrl #\r)] (typed "git") [(ctrl #\g)]]))
"buffer \"x\"")
(expect "another key keeps the match and does what it does"
(run-on searched (keys [[(ctrl #\r)] (typed "status") [(ctrl #\e)] (typed "!") [enter]]))
"text \"git status!\"")
;; The test before added "git status!" to the history.
(expect "no match keeps the last one"
(run-on searched (keys [[(ctrl #\r)] (typed "gitx") [(key KeyRight)]]))
"buffer \"git status!\"")
;; Completion.
(def completing (make-line-editor #:completer (Some complete-word)))
(expect "Tab inserts the common prefix" (run-on completing (keys [(typed "x ve") [(key KeyTab)]]))
"buffer \"x vec\"")
(expect "one candidate is inserted whole" (run-on completing (keys [(typed "x vec-m") [(key KeyTab)]]))
"buffer \"x vec-map \"")
(expect "no candidate changes nothing" (run-on completing (keys [(typed "zz") [(key KeyTab) (key KeyTab)]]))
"buffer \"zz\"")
(expect "Tab without a completer inserts a tab" (run-fresh (keys [(typed "a") [(key KeyTab)] [enter]]))
"text \"a\\t\"")
;; The history file.
(def path (path-combine (temp-dir) "bjoterm-history-test.txt"))
(def saved (make-line-editor))
(line-history-add! saved "plain")
(line-history-add! saved "two\nlines")
(line-history-add! saved "a \\ backslash and \\n")
(expect "the history is saved" (line-history-save saved path) (Ok unit))
(def loaded (make-line-editor))
(expect "and loaded" (line-history-load! loaded path) (Ok unit))
(expect "with lines and backslashes as they were" (line-history loaded) (line-history saved))
(ignore (file-delete path))
(expect "a history file that does not exist is empty"
(line-history-load! (make-line-editor) (path-combine (temp-dir) "bjoterm-no-such-history.txt"))
(Ok unit))
(println "line ok"))