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

@ -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