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

43
examples/repl.bjo Normal file
View file

@ -0,0 +1,43 @@
;; A small REPL shell: brackets make a new line, Tab completes a few words,
;; and the history is kept in a file.
;;
;; bjo run examples/repl.bjo
(import (std prelude))
(import (bjoterm terminal))
(import (bjoterm line))
(: (Vec string))
(def words ["define" "display" "lambda" "let" "letrec" "vector-ref" "vector-set!"])
;; Completes the word before the cursor from `words`.
(: (-> string Completion))
(defun (complete before)
(def chars (string->vec before))
(def start (let go ((i (vec-length chars)))
(if (and (> i 0) (not (string-contains? " ()" (char->string (vec-ref chars (- i 1))))))
(go (- i 1))
i)))
(def word (string-join (vec-map char->string (vec-slice chars start (- (vec-length chars) start))) ""))
(Completion (prefix word)
(candidates (vec-filter (fun (w) (string-starts-with? w word)) words))))
;; Done when every open bracket is closed.
(: (-> string bool))
(defun (balanced? text)
(<= (loop (:for c (in-vec (string->vec text)))
(:acc d (summing (cond ((= c #\() 1) ((= c #\)) -1) (else 0)))))
0))
(defun (main args)
(def (Ok term) (terminal-open) :leave ((Err e) (println (terminal-error-message e)) 1))
(def ed (make-line-editor #:completer (Some complete) #:input-done? (Some balanced?)))
(def history (path-combine (match (getenv "HOME") ((Some h) h) (None ".")) ".bjoterm-repl-history"))
(ignore (line-history-load! ed history))
(let go ()
(match (line-read ed term (styled "λ> " [(StyleFg (Ansi 2)) StyleBold]) #:continuation (Some ".. "))
((LineText text) (println (str "read: " (written text))) (go))
(LineCancelled (go))
(LineEof unit)))
(ignore (line-history-save ed history))
0)