line-read: redraw correctly after a terminal reflows

- Each row of the input ends with a line break, so only a narrowing
  terminal that reflows moves the cursor. The layout keeps the widths of
  the items on each row, and cursor-row-after-reflow computes the
  cursor's row after the terminal wraps each row again.
- terminal-reflows? guesses from the environment. An unknown terminal
  counts as not reflowing. #:reflow? of make-line-editor overrides it.
- New tests: the model in tests/line.bjo, and tests/reflow.bjo, which
  narrows the terminal with stty under script.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Linus Björnstam 2026-11-30 21:24:16 +01:00
parent ce778f9b1e
commit 95d747cf70
6 changed files with 226 additions and 13 deletions

View file

@ -33,6 +33,8 @@ Examples:
- `tests/terminal.bjo` and `tests/line-terminal.bjo`: raw mode and
`line-read` on a pseudo-terminal, under `script`.
- `tests/text.bjo`: clusters and widths.
- `tests/reflow.bjo`: the redraw after the terminal narrows, with and
without reflow, under `script`.
- `tests/async.bjo`: `line-read` in a bjoroutine, and cancelled by a
deadline.
- `examples/keys.bjo` prints events; `examples/repl.bjo` is a small REPL.

View file

@ -39,7 +39,22 @@ is in raw mode, and gives it back as it found it.
- Each key is a pure step from one state to the next (~line-step~), so
~simulate-line~ tests the keys without a terminal.
- History files have one entry per line, with "\n" and "\\" escaped.
- Not done: redrawing after a terminal reflows lines when it narrows.
- Reflow (2026-11-30): each row of the input ends with a line break, so
widening changes nothing, and a terminal that does not reflow (xterm)
keeps the rows as drawn. A terminal that reflows wraps each row again
when it narrows. The editor keeps the widths of the items on each row,
and when the width is less than at the last drawing it computes the
cursor's row after the wrap (~cursor-row-after-reflow~).
- Whether the terminal reflows is a guess from the environment
(~terminal-reflows?~); ~#:reflow?~ of ~make-line-editor~ overrides it.
An unknown terminal counts as not reflowing: a wrong #f leaves a copy
of the input, a wrong #t erases output above it.
- Several resizes before one redraw give the same result as one, as
the terminal joins its own wraps again.
- Not done: input taller than the screen after a reflow. The rows above
the top are in the scrollback, and the cursor cannot go up to them.
- Tested with ~script~, which does not reflow: the test checks the
escape sequences. Not yet tried on a terminal that reflows.
*Async, and less C# (2026-11-30).*
- ~read-event~ and everything above it work in both colours. The one leaf

View file

@ -20,6 +20,9 @@
;; its width in columns: East Asian wide characters and emoji take two.
;; - It wraps lines itself, with a line break where a line is full. The
;; whole input is drawn again after each key.
;; - When the terminal gets narrower, a terminal that reflows wraps the
;; rows of the input again, and the cursor moves down. The editor
;; 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.
;; - The design is in plan.org, phase 2.
@ -33,7 +36,7 @@
LineEditor LineResult Completion
make-line-editor line-read
line-history line-history-add! line-history-load! line-history-save
simulate-line)
simulate-line cursor-row-after-reflow)
;; ===========================================================================
;; Types
@ -57,6 +60,7 @@
(Record (: completer (Option (-> string Completion)))
(: input-done? (Option (-> string bool)))
(: history-size int)
(: reflow? (Option bool))
(: history (Vec string) #:mutable))))
;; Reverse search through the history.
@ -98,13 +102,18 @@
;; - `#:input-done?`: called by Enter with the whole input. #f makes Enter
;; start a new line; a REPL returns #f while brackets are open.
;; - `#:history-size`: the most entries kept; the oldest go first.
;; - `#:reflow?`: whether the terminal wraps its lines again when it gets
;; narrower. None uses `terminal-reflows?`. A wrong #t can erase output
;; above the input when the terminal narrows; a wrong #f leaves a copy of
;; the input above it.
(: (-> (#:completer (Option (-> string Completion)))
(#:input-done? (Option (-> string bool)))
(#:history-size int)
(#:reflow? (Option bool))
LineEditor))
(defun (make-line-editor #:completer None #:input-done? None #:history-size 1000)
(defun (make-line-editor #:completer None #:input-done? None #:history-size 1000 #:reflow? None)
(LineEditor (completer completer) (input-done? input-done?)
(history-size history-size) (history [])))
(history-size history-size) (reflow? reflow?) (history [])))
;; The history, oldest first.
(: (-> LineEditor (Vec string)))
@ -210,19 +219,36 @@
(: (-> LineEditor Terminal string string LineResult))
(defun (edit-loop ed term prompt cont)
(def out (parameter-ref current-output-port))
(def/mutable row 0)
(def reflow? (match (record-ref ed reflow?)
((Some r) r)
(None (terminal-reflows? term))))
;; The input on the screen, and the width it was drawn at. None when the
;; cursor is at the start of a row with no input after it.
(def/mutable drawn None)
(def/mutable drawn-width 0)
;; The rows from the start of the input to the cursor.
(defun (rows-up width)
(match drawn
(None 0)
((Some l)
(if (and reflow? (< width drawn-width))
(cursor-row-after-reflow (record-ref l rows) (record-ref l cursor-row)
(record-ref l cursor-col) width)
(record-ref l cursor-row)))))
(defun (draw st)
(def lay (layout-state st prompt cont (fst (terminal-size term))))
(write-string out (str "\r" (cursor-up row) clear-below
(def width (fst (terminal-size term)))
(def lay (layout-state st prompt cont width))
(write-string out (str "\r" (cursor-up (rows-up width)) clear-below
(record-ref lay shown)
(cursor-up (- (record-ref lay end-row) (record-ref lay cursor-row)))
"\r" (cursor-forward (record-ref lay cursor-col))))
(set! row (record-ref lay cursor-row))
(set! drawn (Some lay))
(set! drawn-width width)
lay)
;; Moves below the input, for output that follows it.
(defun (leave lay)
(write-string out (str (cursor-down (- (record-ref lay end-row) (record-ref lay cursor-row))) "\n"))
(set! row 0))
(set! drawn None))
(let go ((st (start-state ed)))
(def lay (draw st))
(match (line-step ed st (read-event term))
@ -230,7 +256,7 @@
((Bell next) (write-string out "\u{7}") (go next))
((ClearScreen next)
(write-string out (str clear-screen (cursor-to 0 0)))
(set! row 0)
(set! drawn None)
(go next))
((SuspendNow next)
(leave lay)
@ -299,7 +325,10 @@
;; line that ends exactly at the edge.
;; - `end-row`: the row where `shown` leaves the cursor, from 0.
;; - `cursor-row` and `cursor-col`: where the editor's cursor is drawn.
(type (: Layout (Record (: shown string) (: end-row int) (: cursor-row int) (: cursor-col int))))
;; - `rows`: the widths of the items on each row, for
;; `cursor-row-after-reflow`.
(type (: Layout (Record (: shown string) (: end-row int) (: cursor-row int) (: cursor-col int)
(: rows (Vec (Vec int))))))
(: (-> State string string int Layout))
(defun (layout-state st prompt cont width)
@ -320,7 +349,11 @@
(def/mutable col 0)
(def/mutable cursor-row 0)
(def/mutable cursor-col 0)
(def/mutable rows [])
(def/mutable this-row [])
(defun (break!)
(set! rows (vec-add rows this-row))
(set! this-row [])
(stringbuilder-add-string! out "\n")
(set! row (+ row 1))
(set! col 0))
@ -328,6 +361,7 @@
(defun (put! shown w)
(when (and (> col 0) (> (+ col w) width)) (break!))
(stringbuilder-add-string! out shown)
(set! this-row (vec-add this-row w))
(set! col (+ col w))
(when (>= col width) (break!)))
(defun (put-prompt! items)
@ -351,7 +385,35 @@
(set! cursor-row row)
(set! cursor-col col))
(Layout (shown (stringbuilder->string out)) (end-row row)
(cursor-row cursor-row) (cursor-col cursor-col)))
(cursor-row cursor-row) (cursor-col cursor-col)
(rows (vec-add rows this-row))))
;; The row of the cursor, counted from the start of the input, after a
;; terminal that reflows has got narrower.
;; - `rows`: the widths of the items on each row as drawn. Each row ended
;; with a line break, so the terminal wraps each row on its own.
;; - `cursor-row` and `cursor-col`: the cursor as drawn.
;; - `width`: the new width. An item that does not fit at the end of a
;; row goes to the next row, as wide characters do on a terminal.
;; - A cursor at the edge, after a full row, is at the start of the next.
(: (-> (Vec (Vec int)) int int int int))
(defun (cursor-row-after-reflow rows cursor-row cursor-col width)
;; Places the items of `row` until `stop-col` columns of it are placed.
;; Returns the rows taken before the last one, and the column on it.
(defun (place row stop-col)
(let go ((i 0) (old 0) (r 0) (col 0))
(if (or (= i (vec-length row)) (>= old stop-col))
(Tuple r col)
(let* ((w (vec-ref row i))
(wraps? (and (> col 0) (> (+ col w) width))))
(go (+ i 1) (+ old w)
(if wraps? (+ r 1) r)
(+ (if wraps? 0 col) w))))))
(def above
(loop (:for i (range 0 cursor-row))
(:acc n (summing (+ 1 (fst (place (vec-ref rows i) 1000000)))))))
(def (Tuple r col) (place (vec-ref rows cursor-row) cursor-col))
(+ above r (if (>= col width) 1 0)))
;; ===========================================================================
;; Editing

View file

@ -33,7 +33,7 @@
(export
Terminal TerminalError Color Style
terminal-open terminal-error-message with-raw-mode terminal-raw?
terminal-size terminal-suspend
terminal-size terminal-suspend terminal-reflows?
read-event read-event/timeout
;; Escape sequences.
cursor-to cursor-up cursor-down cursor-forward cursor-back cursor-column
@ -135,6 +135,32 @@
(def size (tty-size (record-ref term tty)))
(Tuple (array-ref size 0) (array-ref size 1)))
;; Whether the terminal probably wraps its lines again when it gets
;; narrower, a guess from the environment.
;; - #t for tmux, and for kitty, VTE terminals (GNOME Terminal and
;; others), Konsole, Alacritty, foot, WezTerm, Ghostty, iTerm2,
;; Terminal.app, Windows Terminal and the VS Code terminal.
;; - #f for GNU screen, xterm, and a terminal it does not know.
;; - Environment variables can be wrong: a terminal started from another
;; can inherit its variables, and ssh passes on only TERM.
(: (-> Terminal bool))
(defun (terminal-reflows? term)
(defun (set? name) (not (= (getenv name) None)))
(def term-name (match (getenv "TERM") ((Some t) t) (None "")))
(def program (match (getenv "TERM_PROGRAM") ((Some t) t) (None "")))
(cond
((set? "TMUX") #t)
((or (set? "STY") (set? "XTERM_VERSION")) #f)
((or (set? "KITTY_WINDOW_ID") (set? "VTE_VERSION") (set? "KONSOLE_VERSION")
(set? "WT_SESSION") (set? "ALACRITTY_WINDOW_ID") (set? "WEZTERM_PANE")
(set? "GHOSTTY_RESOURCES_DIR"))
#t)
((vec-contains? ["WezTerm" "iTerm.app" "Apple_Terminal" "vscode" "ghostty"] program) #t)
(else
(> (loop (:for prefix (in-vec ["xterm-kitty" "alacritty" "foot" "wezterm" "xterm-ghostty"]))
(:acc n (summing (if (string-starts-with? term-name prefix) 1 0))))
0))))
;; Stops the program as Ctrl-Z does in a shell. For a program in raw mode
;; that reads Ctrl-Z as a key.
;; - The modes from before raw mode are restored while it is stopped, and

View file

@ -216,4 +216,16 @@
(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))
;; Reflow: where the cursor is after a terminal that reflows narrows.
(expect "rows that still fit move nothing" (cursor-row-after-reflow [[1 1 1] [1 1]] 1 2 10) 1)
(expect "a row above that wraps moves the cursor down"
(cursor-row-after-reflow [[1 1 1 1 1 1] [1 1]] 1 1 4) 2)
(expect "every row above counts" (cursor-row-after-reflow [[1 1 1 1 1] [1 1 1 1 1] [1]] 2 0 2) 6)
(expect "the cursor's own row wraps before it" (cursor-row-after-reflow [[1 1 1 1 1 1]] 0 5 4) 1)
(expect "but not after it" (cursor-row-after-reflow [[1 1 1 1 1 1]] 0 2 4) 0)
(expect "a cursor after a full row is on the next" (cursor-row-after-reflow [[1 1 1 1]] 0 4 4) 1)
(expect "a wide item that does not fit goes to the next row"
(cursor-row-after-reflow [[1 1 1 2] [1]] 1 0 4) 2)
(expect "an empty row is one row" (cursor-row-after-reflow [[] [] [1]] 2 1 4) 2)
(println "line ok"))

96
tests/reflow.bjo Normal file
View file

@ -0,0 +1,96 @@
;; 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` when the terminal gets narrower: how far up it goes to draw
;; the input again.
;;
;; bjo test tests/reflow.bjo
;;
;; The test runs itself again under `script`. The child makes its terminal
;; narrower with `stty cols` while `line-read` waits in another
;; bjoroutine. `script` does not reflow, so the test checks the escape
;; sequences the editor writes, not the screen.
(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)))
;; ---- the child -------------------------------------------------------------
(: (-> void))
(defbjo (narrow-later)
(sync (timeout (milliseconds 3000)))
(ignore (sync (blocking (fun () (run/output '(sh "-c" "stty cols 20 </dev/tty")))))))
(: (-> LineEditor Terminal string))
(defbjo (read-and-narrow ed term)
(def narrowing (bjo (narrow-later)))
(def result (line-read ed term "> "))
(ignore (sync (promise-join narrowing)))
(match result
((LineText text) (str "read " (int->string (string-length text))))
(LineEof "eof")
(LineCancelled "cancelled")))
(: (-> bool void))
(defun (child reflow?)
(match (terminal-open)
((Err e) (println (str "open: " (terminal-error-message e))))
((Ok term)
(def ed (make-line-editor #:reflow? (Some reflow?)))
(match (sync/blocking (promise-join (bjo (read-and-narrow ed term))))
((Ok text) (println (str "result: " text)))
((Err e) (println (str "raised " (.-Message e))))))))
;; ---- the parent ------------------------------------------------------------
;; The output of the child, with the terminal 40 columns wide at the start.
(: (-> string string))
(defun (run-child mode)
(def self (str "dotnet " (array-ref (command-line) 0)))
;; "> " and 50 characters: a full row of 40 and a row of 12, the cursor
;; at its end. At 20 columns the first row takes 2 rows, so the cursor is
;; 2 rows below the start of the input, not 1.
(def keys (str "sleep 2; printf '" (string-pad-left "" 50 #:with #\x) "'; sleep 2.5; printf '\\r'; sleep 0.5"))
(def command (str "(" keys ") | script -qec 'stty cols 40 rows 20; " self " " mode "' /dev/null"))
(match (run/output '(sh "-c" ,command))
((Ok (Tuple _ text)) (string-replace text "\r" ""))
((Err e) (run-error-message e))))
;; Whether the first drawing at 20 columns comes right after going up `up`
;; rows and clearing.
(: (-> string int bool))
(defun (first-narrow-draw-after? out up)
;; Only a drawing at 20 columns has a row of "> " and 18 x.
(def row (str "> " (string-pad-left "" 18 #:with #\x) "\n"))
(match (string-split-once out row)
((Some (Tuple before _))
(string-ends-with? before (str "\u{1B}[" (int->string up) "A\u{1B}[J")))
(None #f)))
(: (-> void))
(defun (parent)
(def reflowing (run-child "reflow"))
(expect-true "the input is read" (string-contains? reflowing "result: read 50"))
(expect-true "after a reflow it goes up the 2 rows of the wrapped input"
(first-narrow-draw-after? reflowing 2))
(def fixed (run-child "fixed"))
(expect-true "the input is read" (string-contains? fixed "result: read 50"))
(expect-true "without a reflow it goes up the 1 row as drawn"
(first-narrow-draw-after? fixed 1))
(unless (string-contains? reflowing "result: read")
(println reflowing)))
(defun (main args)
(cond
((= args ["reflow"]) (child #t))
((= args ["fixed"]) (child #f))
((file-exists? "/usr/bin/script") (parent))
(else (println "skipped: no script command")))
0)