Async line-read, and the decoder and text handling in Bjolang

- read-event, line-read and the editor loop work in both colours. The
  leaf is read-bytes, a defbjouble: a bjoroutine awaits the glue's read,
  other code blocks. with-raw-mode takes a body of either colour.
- Cancelling the scope of a waiting line-read ends it and restores the
  terminal modes. The glue runs reads one at a time.
- The key decoder is (bjoterm keys), and widths, prompt escapes, search
  and common prefixes are (bjoterm text). Clusters and categories come
  from (std unicode grapheme) and (std unicode chars).
- Keys.cs and Text.cs are removed. The glue is termios, signals, poll
  and read.
- New tests: tests/async.bjo and tests/text.bjo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Linus Björnstam 2026-11-30 21:05:59 +01:00
parent 6863503fa7
commit ce778f9b1e
11 changed files with 970 additions and 733 deletions

430
src/keys.bjo Normal file
View file

@ -0,0 +1,430 @@
;; 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/.
;; (bjoterm keys): terminal input as events. Bytes in, keys, pastes and
;; resizes out.
;;
;; - Keys: CSI and SS3 sequences of xterm with the modifier parameter
;; ("ESC [ 1 ; 5 A" is Ctrl-Up), the "~" keys, F1 to F12, Shift-Tab
;; ("ESC [ Z"), ESC before a key as Alt, and UTF-8.
;; - Bracketed paste: the bytes between "ESC [ 200 ~" and "ESC [ 201 ~" are
;; one paste, decoded as UTF-8 with CR LF and CR made LF.
;; - A `Decoder` holds bytes until they make a whole event. The reader in
;; (bjoterm terminal) asks for a partial event with `final? #t` when no
;; more bytes came within its timeout: a lone ESC is then Escape.
;; - (bjoterm terminal) re-exports the types, so a program imports this
;; module only to decode bytes it has itself.
(import (std prelude))
(export
Key Mods TermEvent Decoder
no-mods key->string event->string decode-input
make-decoder decoder-feed! decoder-next! decoder-partial? decoder-in-paste?)
;; ===========================================================================
;; Types
;; ===========================================================================
;; The modifier keys held with a key.
(type (: Mods (Record (: shift? bool) (: alt? bool) (: ctrl? bool))))
;; A key.
;; - `KeyChar`: a character. Ctrl and a letter is the letter with `ctrl?`:
;; Ctrl-A is `(KeyChar #\a)`. Ctrl-J (a line feed) is `(KeyChar #\j)`, not
;; `KeyEnter`.
;; - `KeyBackspace` with `ctrl?` is byte 8, which is Ctrl-H and, on some
;; terminals, Ctrl-Backspace.
;; - `KeyF`: F1 to F12.
;; - `KeyUnknown`: a sequence the decoder does not know, with ESC shown as
;; "^[".
(type (: Key (Union (: KeyChar char) KeyEnter KeyTab KeyBackspace KeyEscape
KeyUp KeyDown KeyLeft KeyRight KeyHome KeyEnd
KeyPageUp KeyPageDown KeyInsert KeyDelete
(: KeyF int) (: KeyUnknown string))))
;; An event read from the terminal.
;; - `TermKey`: a key and its modifiers.
;; - `TermPaste`: text pasted while bracketed paste is on, with line ends
;; made "\n".
;; - `TermResized`: the new size, columns then rows. Also after the program
;; was stopped and continued: draw the screen again.
;; - `TermEnd`: end of input; the terminal hung up.
(type (: TermEvent (Union (: TermKey Key Mods) (: TermPaste string)
(: TermResized int int) TermEnd)))
;; Bytes not yet decoded: `buf` from `start` to `end`.
;; - `paste?`: inside a bracketed paste.
;; - `scanned`: how far a paste has been searched for its end, so that a
;; long paste is searched once.
(type (: Decoder #:opaque
(Record (: buf (Array byte) #:mutable)
(: start int #:mutable)
(: end int #:mutable)
(: paste? bool #:mutable)
(: scanned int #:mutable))))
;; What decoding at one place found.
;; - `NeedMore`: a partial event; wait for more bytes.
;; - `Got`: an event, and how many bytes it took.
;; - `PasteBegins`: "ESC [ 200 ~", and how many bytes it took.
(type (: Decoded (Union NeedMore (: Got TermEvent int) (: PasteBegins int))))
;; ===========================================================================
;; Events as text
;; ===========================================================================
;; No modifier keys.
(: Mods)
(def no-mods (Mods (shift? #f) (alt? #f) (ctrl? #f)))
;; A key as text, such as "C-a", "M-<up>" or "S-<tab>": modifiers as
;; Emacs writes them (C- Ctrl, M- Alt, S- Shift), and names in brackets.
(: (-> Key Mods string))
(defun (key->string key mods)
(def name
(match key
((KeyChar #\space) "<space>")
((KeyChar c) (char->string c))
(KeyEnter "<enter>")
(KeyTab "<tab>")
(KeyBackspace "<backspace>")
(KeyEscape "<escape>")
(KeyUp "<up>")
(KeyDown "<down>")
(KeyLeft "<left>")
(KeyRight "<right>")
(KeyHome "<home>")
(KeyEnd "<end>")
(KeyPageUp "<pageup>")
(KeyPageDown "<pagedown>")
(KeyInsert "<insert>")
(KeyDelete "<delete>")
((KeyF n) (str "<f" (int->string n) ">"))
((KeyUnknown text) (str "<unknown " text ">"))))
(str (if (record-ref mods ctrl?) "C-" "")
(if (record-ref mods alt?) "M-" "")
(if (record-ref mods shift?) "S-" "")
name))
;; An event as text, for logs and tests.
(: (-> TermEvent string))
(defun (event->string ev)
(match ev
((TermKey key mods) (str "key " (key->string key mods)))
((TermPaste text) (str "paste " (written text)))
((TermResized cols rows) (str "resized " (int->string cols) "x" (int->string rows)))
(TermEnd "end")))
;; ===========================================================================
;; The decoder
;; ===========================================================================
;; A decoder with no bytes.
(: (-> Decoder))
(defun (make-decoder)
(Decoder (buf (make-array 256)) (start 0) (end 0) (paste? #f) (scanned 0)))
;; Whether the decoder holds bytes of an event not yet complete.
(: (-> Decoder bool))
(defun (decoder-partial? d)
(> (record-ref d end) (record-ref d start)))
;; Whether the decoder is inside a bracketed paste. A paste waits for its
;; end however long it takes.
(: (-> Decoder bool))
(defun (decoder-in-paste? d)
(record-ref d paste?))
;; Adds the first `count` bytes of `bytes`.
(: (-> Decoder (Array byte) int void))
(defun (decoder-feed! d bytes count)
(when (= (record-ref d start) (record-ref d end))
(record-set! d (start 0) (end 0) (scanned 0)))
(def buf (record-ref d buf))
(def start (record-ref d start))
(def end (record-ref d end))
(def live (- end start))
(when (> (+ end count) (array-length buf))
;; Move the live bytes to the front, into a larger array if they do
;; not fit.
(def target (if (> (+ live count) (array-length buf))
(make-array (max (* 2 (array-length buf)) (+ live count)))
buf))
(array-copy! buf start target 0 live)
(record-set! d (buf target) (start 0) (end live)
(scanned (- (record-ref d scanned) start))))
(array-copy! bytes 0 (record-ref d buf) (record-ref d end) count)
(record-set! d (end (+ (record-ref d end) count))))
;; The next whole event, or None when the bytes so far are part of one.
;; With `final?`, a partial event is decoded as it is: a lone ESC is
;; Escape, ESC and one byte is Alt and that key, a cut UTF-8 character is
;; U+FFFD, and a cut sequence is `KeyUnknown`. A paste is never cut.
(: (-> Decoder bool (Option TermEvent)))
(defun (decoder-next! d final?)
(cond
((record-ref d paste?) (next-paste! d))
((not (decoder-partial? d)) None)
(else
(match (decode d (record-ref d start) final?)
(NeedMore None)
((Got ev used)
(record-set! d (start (+ (record-ref d start) used)))
(Some ev))
((PasteBegins used)
(def start (+ (record-ref d start) used))
(record-set! d (start start) (paste? #t) (scanned start))
(next-paste! d))))))
;; Decodes all of `bytes` as input that ends there: a partial event at the
;; end is decoded as it is. For tests, and for input recorded earlier.
(: (-> (Array byte) (Vec TermEvent)))
(defun (decode-input bytes)
(def d (make-decoder))
(decoder-feed! d bytes (array-length bytes))
(let go ((out []))
(match (decoder-next! d #f)
((Some ev) (go (vec-add out ev)))
(None
(match (decoder-next! d #t)
((Some ev) (go (vec-add out ev)))
(None out))))))
;; ---------------------------------------------------------------------------
;; Bracketed paste
;; ---------------------------------------------------------------------------
;; The paste, when its end has come.
(: (-> Decoder (Option TermEvent)))
(defun (next-paste! d)
(def start (record-ref d start))
(def end (record-ref d end))
;; The end marker can start up to 5 bytes before what was searched.
(let go ((i (max start (- (record-ref d scanned) 5))))
(cond
((> (+ i 6) end)
(record-set! d (scanned (max start (- end 5))))
None)
((paste-end-at? d i)
(def text (bytes->string/lossy (record-ref d buf) #:start start #:end i))
(record-set! d (start (+ i 6)) (paste? #f) (scanned 0))
(Some (TermPaste (string-replace (string-replace text "\r\n" "\n") "\r" "\n"))))
(else (go (+ i 1))))))
;; Whether "ESC [ 2 0 1 ~" starts at `i`.
(: (-> Decoder int bool))
(defun (paste-end-at? d i)
(and (= (byte-at d i) 27) (= (byte-at d (+ i 1)) 91) (= (byte-at d (+ i 2)) 50)
(= (byte-at d (+ i 3)) 48) (= (byte-at d (+ i 4)) 49) (= (byte-at d (+ i 5)) 126)))
;; ---------------------------------------------------------------------------
;; Keys
;; ---------------------------------------------------------------------------
(: (-> Decoder int int))
(defun (byte-at d i)
(cast int (array-ref (record-ref d buf) i)))
(: (-> Key TermEvent))
(defun (plain k)
(TermKey k no-mods))
(: (-> 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))))
;; The event at `at`.
(: (-> Decoder int bool Decoded))
(defun (decode d at final?)
(def avail (- (record-ref d end) at))
(def b (byte-at d at))
(cond
((= b 27)
(cond
((= avail 1) (if final? (Got (plain KeyEscape) 1) NeedMore))
((= (byte-at d (+ at 1)) 91) (csi d at final?))
((= (byte-at d (+ at 1)) 79) (ss3 d at final?))
(else
;; ESC and a key is Alt and that key.
(match (decode d (+ at 1) final?)
(NeedMore NeedMore)
((Got (TermKey key mods) used)
(if (unknown? key)
(Got (plain (KeyUnknown (shown d at (+ 1 used)))) (+ 1 used))
(Got (TermKey key (record-set mods (alt? #t))) (+ 1 used))))
((Got _ used) (Got (plain (KeyUnknown (shown d at (+ 1 used)))) (+ 1 used)))
((PasteBegins used) (Got (plain (KeyUnknown (shown d at (+ 1 used)))) (+ 1 used)))))))
((< b 128) (Got (ascii b) 1))
(else (utf8 d at final?))))
(: (-> Key bool))
(defun (unknown? key)
(match key
((KeyUnknown _) #t)
(_ #f)))
(: (-> int TermEvent))
(defun (ascii b)
(cond
((= b 13) (plain KeyEnter))
((= b 9) (plain KeyTab))
((= b 127) (plain KeyBackspace))
((= b 8) (TermKey KeyBackspace (Mods (shift? #f) (alt? #f) (ctrl? #t))))
((= b 0) (ctrl #\space))
((< b 27) (ctrl (int->char (+ 96 b))))
((< b 32) (ctrl (int->char (+ 64 b))))
(else (plain (KeyChar (int->char b))))))
(: TermEvent)
(def replacement (plain (KeyChar (int->char 65533))))
;; A UTF-8 character at `at`, whose first byte is 128 or more.
(: (-> Decoder int bool Decoded))
(defun (utf8 d at final?)
(def b (byte-at d at))
(def end (record-ref d end))
(def length (cond ((and (>= b 0xc2) (< b 0xe0)) 2)
((and (>= b 0xe0) (< b 0xf0)) 3)
((and (>= b 0xf0) (< b 0xf5)) 4)
(else 0)))
(def have (let go ((n 1))
(if (and (< n length) (< (+ at n) end)
(= (bitwise-and (byte-at d (+ at n)) 0xc0) 0x80))
(go (+ n 1))
n)))
(cond
((= length 0) (Got replacement 1))
((< have length)
;; Cut: wait for the rest, unless a byte that cannot continue it came,
;; or no more will come.
(if (and (= (+ at have) end) (not final?)) NeedMore (Got replacement have)))
(else
(def first-bits (bitwise-and b (cond ((= length 2) 0x1f) ((= length 3) 0x0f) (else 0x07))))
(def code (let go ((n 1) (c first-bits))
(if (= n length)
c
(go (+ n 1) (bitwise-ior (shift-left c 6) (bitwise-and (byte-at d (+ at n)) 0x3f))))))
(def valid? (cond ((= length 3) (and (>= code 0x800) (or (< code 0xd800) (> code 0xdfff))))
((= length 4) (and (>= code 0x10000) (<= code 0x10ffff)))
(else #t)))
(Got (if valid? (plain (KeyChar (int->char code))) replacement) length))))
;; "ESC [", parameters, intermediates and a final byte.
(: (-> Decoder int bool Decoded))
(defun (csi d at final?)
(def end (record-ref d end))
(def after-params (let go ((i (+ at 2)))
(if (and (< i end) (>= (byte-at d i) 0x30) (<= (byte-at d i) 0x3f)) (go (+ i 1)) i)))
(def last-at (let go ((i after-params))
(if (and (< i end) (>= (byte-at d i) 0x20) (<= (byte-at d i) 0x2f)) (go (+ i 1)) i)))
(cond
((= last-at end)
(cond
((not final?) NeedMore)
;; "ESC [" alone is Alt-[.
((= (- end at) 2) (Got (alt #\[) 2))
(else (Got (plain (KeyUnknown (shown d at (- end at)))) (- end at)))))
(else
(def last (byte-at d last-at))
(def used (+ 1 (- last-at at)))
(def params (csi-params d (+ at 2) after-params))
(def first (param params 0 1))
(def mods (mods-of (param params 1 1)))
(defun (key k) (Got (TermKey k mods) used))
(cond
((or (< last 0x40) (> last 0x7e)) (Got (plain (KeyUnknown (shown d at used))) used))
((= last 65) (key KeyUp))
((= last 66) (key KeyDown))
((= last 67) (key KeyRight))
((= last 68) (key KeyLeft))
((= last 72) (key KeyHome))
((= last 70) (key KeyEnd))
((and (>= last 80) (<= last 83)) (key (KeyF (- last 79))))
((= last 90) (Got (TermKey KeyTab (Mods (shift? #t) (alt? #f) (ctrl? #f))) used))
((and (= last 126) (= first 200)) (PasteBegins used))
((= last 126)
(match (tilde-key first)
((Some k) (key k))
(None (Got (plain (KeyUnknown (shown d at used))) used))))
(else (Got (plain (KeyUnknown (shown d at used))) used))))))
;; The numbers of a parameter list "1;5": -1 for one left out.
(: (-> Decoder int int (Vec int)))
(defun (csi-params d from to)
(let go ((i from) (n -1) (out []))
(cond
((= i to) (vec-add out n))
((= (byte-at d i) 59) (go (+ i 1) -1 (vec-add out n)))
((and (>= (byte-at d i) 48) (<= (byte-at d i) 57))
(go (+ i 1) (+ (* (max n 0) 10) (- (byte-at d i) 48)) out))
(else (go (+ i 1) n out)))))
(: (-> (Vec int) int int int))
(defun (param params i missing)
(if (and (< i (vec-length params)) (>= (vec-ref params i) 0))
(vec-ref params i)
missing))
;; xterm's modifier parameter is 1 plus the bits shift 1, alt 2, ctrl 4,
;; meta 8. Meta is Alt here.
(: (-> int Mods))
(defun (mods-of parameter)
(def bits (max 0 (- parameter 1)))
(Mods (shift? (not (= 0 (bitwise-and bits 1))))
(alt? (not (= 0 (bitwise-and bits 10))))
(ctrl? (not (= 0 (bitwise-and bits 4))))))
;; The keys "ESC [ n ~".
(: (-> int (Option Key)))
(defun (tilde-key n)
(cond
((or (= n 1) (= n 7)) (Some KeyHome))
((= n 2) (Some KeyInsert))
((= n 3) (Some KeyDelete))
((or (= n 4) (= n 8)) (Some KeyEnd))
((= n 5) (Some KeyPageUp))
((= n 6) (Some KeyPageDown))
((and (>= n 11) (<= n 15)) (Some (KeyF (- n 10))))
((and (>= n 17) (<= n 21)) (Some (KeyF (- n 11))))
((or (= n 23) (= n 24)) (Some (KeyF (- n 12))))
(else None)))
;; "ESC O" and a key: the keys of application cursor mode, and F1 to F4.
(: (-> Decoder int bool Decoded))
(defun (ss3 d at final?)
(cond
((< (- (record-ref d end) at) 3)
(if final? (Got (alt #\O) 2) NeedMore))
(else
(def k (byte-at d (+ at 2)))
(Got (cond
((= k 65) (plain KeyUp))
((= k 66) (plain KeyDown))
((= k 67) (plain KeyRight))
((= k 68) (plain KeyLeft))
((= k 72) (plain KeyHome))
((= k 70) (plain KeyEnd))
((= k 77) (plain KeyEnter))
((and (>= k 80) (<= k 83)) (plain (KeyF (- k 79))))
(else (plain (KeyUnknown (shown d at 3)))))
3))))
;; `count` bytes from `at` as text: ESC as "^[", other controls and bytes
;; above 126 as "\xNN".
(: (-> Decoder int int string))
(defun (shown d at count)
(def out (stringbuilder-empty))
(loop (:for i (range at (+ at count)))
(:do (def b (byte-at d i))
(cond
((= b 27) (stringbuilder-add-string! out "^["))
((or (< b 32) (> b 126))
(stringbuilder-add-string! out (str "\\x" (string-pad-left (int->string b #:radix 16) 2 #:with #\0))))
(else (stringbuilder-add! out (int->char b))))))
(stringbuilder->string out))

View file

@ -27,6 +27,7 @@
(import (std prelude))
(import (std maths))
(import (bjoterm terminal))
(import (bjoterm text))
(export
LineEditor LineResult Completion
@ -34,16 +35,6 @@
line-history line-history-add! line-history-load! line-history-save
simulate-line)
(import/extern
(text-clusters (: Bjoterm.Text.Clusters (-> string (Array string)) #:no-raise))
(prompt-clusters (: Bjoterm.Text.PromptClusters (-> string (Array string)) #:no-raise))
(cluster-width (: Bjoterm.Text.Width (-> string int) #:no-raise))
(cluster-shown (: Bjoterm.Text.Shown (-> string string) #:no-raise))
(text-width (: Bjoterm.Text.TextWidth (-> string int) #:no-raise))
(word-cluster? (: Bjoterm.Text.IsWord (-> string bool) #:no-raise))
(common-prefix (: Bjoterm.Text.CommonPrefix (-> (Array string) string) #:no-raise))
(find-clusters (: Bjoterm.Text.Find (-> string string int) #:no-raise)))
;; ===========================================================================
;; Types
;; ===========================================================================
@ -183,6 +174,9 @@
;; by default, spaces as wide as `prompt`.
;; - Sets raw mode for the time it reads, unless the terminal is in raw
;; mode already.
;; - In a bjoroutine it suspends while it waits for keys; elsewhere it parks
;; the thread. Cancelling the scope around it ends it with the modes
;; restored.
;; - Moving: Left, Right, C-b, C-f; by word M-b, M-f, C-Left, C-Right; to
;; the line's start and end Home, End, C-a, C-e; between lines Up, Down.
;; - Deleting: Backspace, Delete, C-d; to the kill buffer C-k (to the end of
@ -195,14 +189,17 @@
;; - Enter accepts (see `#:input-done?`), M-Enter and C-j start a new line,
;; C-l clears the screen, C-z stops the program, C-c cancels, and C-d on
;; an empty buffer is end of input.
(: (-> LineEditor Terminal string (#:continuation (Option string)) LineResult) #:sync)
(: (-> LineEditor Terminal string (#:continuation (Option string)) LineResult))
(defun (line-read ed term prompt #:continuation None)
(def cont (match continuation
((Some c) c)
(None (string-pad-left "" (text-width prompt)))))
(if (terminal-raw? term)
(edit-loop ed term prompt cont)
(with-raw-mode term (fun () (edit-loop ed term prompt cont)))))
;; 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))))
(#:bjo (with-raw-mode term (bjoroutine () (edit-loop ed term prompt cont)))))))
(: (-> LineEditor State))
(defun (start-state ed)
@ -210,7 +207,7 @@
(hist-at (vec-length (record-ref ed history))) (draft [])
(search None) (tabbed? #f)))
(: (-> LineEditor Terminal string string LineResult) #:sync)
(: (-> LineEditor Terminal string string LineResult))
(defun (edit-loop ed term prompt cont)
(def out (parameter-ref current-output-port))
(def/mutable row 0)
@ -310,10 +307,10 @@
((Some s)
(def label (str "(" (if (record-ref s failed?) "failed " "")
"search `" (record-ref s query) "'): "))
(layout (array->vec (prompt-clusters label)) (array->vec (prompt-clusters cont))
(layout (prompt-clusters label) (prompt-clusters cont)
(record-ref st text) (record-ref st cursor) width))
(None
(layout (array->vec (prompt-clusters prompt)) (array->vec (prompt-clusters cont))
(layout (prompt-clusters prompt) (prompt-clusters cont)
(record-ref st text) (record-ref st cursor) width))))
(: (-> (Vec string) (Vec string) (Vec string) int int Layout))
@ -366,7 +363,7 @@
(: (-> string (Vec string)))
(defun (clusters s)
(array->vec (text-clusters s)))
(text-clusters s))
(: (-> State string State))
(defun (insert st s)
@ -521,7 +518,7 @@
((= (vec-length candidates) 0) (Bell st))
((= (vec-length candidates) 1) (Edited (replace-with (vec-ref candidates 0))))
(else
(def common (common-prefix (vec->array candidates)))
(def common (common-prefix candidates))
(cond
((> (vec-length (clusters common)) k) (Edited (replace-with common)))
(tabbed? (ShowList st candidates))

View file

@ -19,16 +19,22 @@
;; module: .NET then sets its own terminal modes.
;; - Output is strings: write them to standard output. `read-event` flushes
;; `current-output-port` before it waits.
;; - See glue/Tty.cs and glue/Keys.cs for the C# side.
;; - `read-event` and the functions that call it work in both colours: in a
;; bjoroutine they suspend while they wait, elsewhere they park the
;; thread.
;; - Read events from one fiber at a time. The bytes not yet decoded are
;; kept for the whole process, as there is one terminal.
;; - The event types and the decoder are (bjoterm keys), re-exported here.
;; glue/Tty.cs has termios, the signals, and the reading of bytes.
(import (std prelude))
(import (bjoterm keys))
(export
Terminal TerminalError Key Mods TermEvent Color Style
Terminal TerminalError Color Style
terminal-open terminal-error-message with-raw-mode terminal-raw?
terminal-size terminal-suspend
read-event read-event/timeout
no-mods key->string event->string decode-input
;; Escape sequences.
cursor-to cursor-up cursor-down cursor-forward cursor-back cursor-column
cursor-save cursor-restore cursor-hide cursor-show
@ -36,9 +42,10 @@
alt-screen-on alt-screen-off bracketed-paste-on bracketed-paste-off
styled style-start style-reset)
(re-export Key Mods TermEvent no-mods key->string event->string decode-input)
(import/class
(Tty (: Bjoterm.Tty))
(NEvent (: Bjoterm.TermEvent)))
(Tty (: Bjoterm.Tty)))
(import/extern
(tty-open (: Bjoterm.Tty.Open (-> Tty)
@ -50,15 +57,10 @@
#:raises (System.InvalidOperationException System.ComponentModel.Win32Exception)))
(leave-raw (: Bjoterm.Tty.LeaveRaw (-> Tty void) #:no-raise))
(tty-suspend (: Bjoterm.Tty.Suspend (-> Tty void) #:no-raise))
(tty-read (: Bjoterm.Tty.ReadAsync (-> Tty int NEvent) #:async
#:raises (System.InvalidOperationException System.ComponentModel.Win32Exception)))
(decode-all (: Bjoterm.Decoder.DecodeAll (-> (Array byte) (Array NEvent)) #:no-raise))
(ev-kind (: Bjoterm.TermEvent.Kind (-> NEvent int) #:get #:no-raise))
(ev-key (: Bjoterm.TermEvent.Key (-> NEvent int) #:get #:no-raise))
(ev-value (: Bjoterm.TermEvent.Value (-> NEvent int) #:get #:no-raise))
(ev-value2 (: Bjoterm.TermEvent.Value2 (-> NEvent int) #:get #:no-raise))
(ev-mods (: Bjoterm.TermEvent.Mods (-> NEvent int) #:get #:no-raise))
(ev-text (: Bjoterm.TermEvent.Text (-> NEvent string) #:get #:no-raise)))
(take-resized? (: Bjoterm.Tty.TakeResized (-> Tty bool) #:no-raise))
(tty-read (: Bjoterm.Tty.ReadAsync (-> Tty (Array byte) int int) #:async
#:raises (System.ComponentModel.Win32Exception)))
(now-ms (: System.Environment.TickCount64 (-> long) #:get #:no-raise)))
;; ===========================================================================
;; Types
@ -72,33 +74,6 @@
;; - `NotATerminal`: standard input or standard output is not a terminal.
(type (: TerminalError (Union TerminalUnsupported (: NotATerminal string))))
;; The modifier keys held with a key.
(type (: Mods (Record (: shift? bool) (: alt? bool) (: ctrl? bool))))
;; A key.
;; - `KeyChar`: a character. Ctrl and a letter is the letter with `ctrl?`:
;; Ctrl-A is `(KeyChar #\a)`. Ctrl-J (a line feed) is `(KeyChar #\j)`, not
;; `KeyEnter`.
;; - `KeyBackspace` with `ctrl?` is byte 8, which is Ctrl-H and, on some
;; terminals, Ctrl-Backspace.
;; - `KeyF`: F1 to F12.
;; - `KeyUnknown`: a sequence the decoder does not know, with ESC shown as
;; "^[".
(type (: Key (Union (: KeyChar char) KeyEnter KeyTab KeyBackspace KeyEscape
KeyUp KeyDown KeyLeft KeyRight KeyHome KeyEnd
KeyPageUp KeyPageDown KeyInsert KeyDelete
(: KeyF int) (: KeyUnknown string))))
;; An event read from the terminal.
;; - `TermKey`: a key and its modifiers.
;; - `TermPaste`: text pasted while bracketed paste is on, with line ends
;; made "\n".
;; - `TermResized`: the new size, columns then rows. Also after the program
;; was stopped and continued: draw the screen again.
;; - `TermEnd`: end of input; the terminal hung up.
(type (: TermEvent (Union (: TermKey Key Mods) (: TermPaste string)
(: TermResized int int) TermEnd)))
;; A color.
;; - `Ansi`: 0 to 7 are black, red, green, yellow, blue, magenta, cyan and
;; white; 8 to 15 are their bright forms.
@ -141,7 +116,8 @@
;; - When the process is stopped and continued, raw mode is set again.
;; - Raises InvalidOperationException when the terminal is in raw mode
;; already.
(: (-> Terminal (-> %a) (#:signals? bool) %a))
;; - `body` may be a bjoroutine: `(with-raw-mode term (bjoroutine () ...))`.
(: (-> Terminal (-?-> %a) (#:signals? bool) %a))
(defun (with-raw-mode term body #:signals? #f)
(def tty (record-ref term tty))
(enter-raw tty signals?)
@ -174,8 +150,24 @@
;; Events
;; ===========================================================================
;; The bytes read and not yet decoded. One for the process, as the terminal
;; is.
(: Decoder)
(def input (make-decoder))
;; How long to wait for the rest of a sequence after its first bytes.
(: int)
(def sequence-timeout-ms 50)
;; What `tty-read` returns at end of input, and after a resize.
(: int)
(def end-of-input -1)
(: int)
(def resized -2)
;; Waits for the next event. Flushes `current-output-port` first.
(: (-> Terminal TermEvent) #:sync)
(: (-> Terminal TermEvent))
(defun (read-event term)
(let go ()
(match (read-event/timeout term -1)
@ -184,104 +176,59 @@
;; Waits at most `ms` milliseconds for the next event; below 0, for ever.
;; Returns None at the timeout. Flushes `current-output-port` first.
(: (-> Terminal int (Option TermEvent)) #:sync)
;; - A sequence whose first bytes came is waited for 50 ms more; then what
;; came is decoded alone, so a lone ESC is the Escape key.
;; - A resize, or SIGCONT, comes before the bytes after it.
(: (-> Terminal int (Option TermEvent)))
(defun (read-event/timeout term ms)
(flush-port (parameter-ref current-output-port))
(match (sync/blocking (promise-join (bjo (reading (record-ref term tty) ms))))
((Err e) (raise e))
((Ok ev) (event-of ev))))
(def tty (record-ref term tty))
;; -1 for no deadline.
(def deadline (if (< ms 0) (cast long -1) (+ now-ms (cast long ms))))
(def no-deadline? (< ms 0))
(def buffer (make-array 4096))
(defun (decoded-or ev)
(match (decoder-next! input #t)
((Some e) (Some e))
(None ev)))
(let go ()
(if (take-resized? tty)
(let ((size (tty-size tty)))
(Some (TermResized (array-ref size 0) (array-ref size 1))))
(match (decoder-next! input #f)
((Some ev) (Some ev))
(None
(def partial? (and (decoder-partial? input) (not (decoder-in-paste? input))))
(def wait (cond (partial? sequence-timeout-ms)
(no-deadline? -1)
(else (cast int (max 0 (- deadline now-ms))))))
(def n (read-bytes tty buffer wait))
(cond
((> n 0) (decoder-feed! input buffer n) (go))
((= n end-of-input) (decoded-or (Some TermEnd)))
((= n resized) (go))
(partial?
(match (decoder-next! input #t)
((Some ev) (Some ev))
(None (go))))
((and (not no-deadline?) (>= now-ms deadline)) None)
(else (go))))))))
(: (-> Tty int NEvent))
(defbjo (reading tty ms)
(tty-read tty ms))
;; Reads bytes from the terminal: suspends in a bjoroutine, parks the
;; thread elsewhere. Returns the count, 0 at the timeout, `end-of-input` or
;; `resized`.
(: (-> Tty (Array byte) int int))
(defbjouble (read-bytes tty buffer ms)
(#:sync (read-bytes/blocking tty buffer ms))
(#:bjo (tty-read tty buffer ms)))
(: (-> NEvent (Option TermEvent)))
(defun (event-of ev)
(match (ev-kind ev)
(0 None)
(1 (Some (TermKey (key-of ev) (mods-of (ev-mods ev)))))
(2 (Some (TermPaste (ev-text ev))))
(3 (Some (TermResized (ev-value ev) (ev-value2 ev))))
(_ (Some TermEnd))))
(: (-> NEvent Key))
(defun (key-of ev)
(match (ev-key ev)
(0 (KeyChar (int->char (ev-value ev))))
(1 KeyEnter)
(2 KeyTab)
(3 KeyBackspace)
(4 KeyEscape)
(5 KeyUp)
(6 KeyDown)
(7 KeyLeft)
(8 KeyRight)
(9 KeyHome)
(10 KeyEnd)
(11 KeyPageUp)
(12 KeyPageDown)
(13 KeyInsert)
(14 KeyDelete)
(15 (KeyF (ev-value ev)))
(_ (KeyUnknown (ev-text ev)))))
(: (-> int Mods))
(defun (mods-of bits)
(Mods (shift? (not (= 0 (bitwise-and bits 1))))
(alt? (not (= 0 (bitwise-and bits 2))))
(ctrl? (not (= 0 (bitwise-and bits 4))))))
;; Decodes bytes of terminal input into events, as `read-event` would
;; return them. A partial event at the end is decoded as it is: a lone ESC
;; is `KeyEscape`. For tests, and for input recorded earlier.
(: (-> (Array byte) (Vec TermEvent)))
(defun (decode-input bytes)
(loop (:for ev (decode-all bytes))
(:acc v (vecing (match (event-of ev)
((Some e) e)
(None TermEnd))))))
;; No modifier keys.
(: Mods)
(def no-mods (Mods (shift? #f) (alt? #f) (ctrl? #f)))
;; A key as text, such as "C-a", "M-<up>" or "S-<tab>": modifiers as
;; Emacs writes them (C- Ctrl, M- Alt, S- Shift), and names in brackets.
(: (-> Key Mods string))
(defun (key->string key mods)
(def name
(match key
((KeyChar #\space) "<space>")
((KeyChar c) (char->string c))
(KeyEnter "<enter>")
(KeyTab "<tab>")
(KeyBackspace "<backspace>")
(KeyEscape "<escape>")
(KeyUp "<up>")
(KeyDown "<down>")
(KeyLeft "<left>")
(KeyRight "<right>")
(KeyHome "<home>")
(KeyEnd "<end>")
(KeyPageUp "<pageup>")
(KeyPageDown "<pagedown>")
(KeyInsert "<insert>")
(KeyDelete "<delete>")
((KeyF n) (str "<f" (int->string n) ">"))
((KeyUnknown text) (str "<unknown " text ">"))))
(str (if (record-ref mods ctrl?) "C-" "")
(if (record-ref mods alt?) "M-" "")
(if (record-ref mods shift?) "S-" "")
name))
;; An event as text, for logs and tests.
(: (-> TermEvent string))
(defun (event->string ev)
(match ev
((TermKey key mods) (str "key " (key->string key mods)))
((TermPaste text) (str "paste " (written text)))
((TermResized cols rows) (str "resized " (int->string cols) "x" (int->string rows)))
(TermEnd "end")))
;; The read on a fiber of its own, which the thread waits for. The fiber is
;; in the caller's scope, so cancelling the scope ends the read.
(: (-> Tty (Array byte) int int) #:sync)
(defun (read-bytes/blocking tty buffer ms)
(match (sync/blocking (promise-join (bjo (tty-read tty buffer ms))))
((Ok n) n)
((Err e) (raise e))))
;; ===========================================================================
;; Escape sequences

234
src/text.bjo Normal file
View file

@ -0,0 +1,234 @@
;; 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/.
;; (bjoterm text): text on a terminal, as grapheme clusters and columns.
;;
;; - Clusters are extended grapheme clusters (UAX #29), from
;; (std unicode grapheme): what a reader sees as one character, such as
;; "e" with an accent, or an emoji with a skin tone.
;; - Widths follow `wcwidth`: 2 for East Asian wide and fullwidth
;; characters and for emoji shown as emoji, 0 for combining marks and
;; format characters, 1 otherwise. A terminal's own table can differ for
;; new emoji.
;; - A C0 control or DEL is shown as "^X", 2 columns. A C1 control
;; (U+0080 to U+009F) is shown as U+FFFD.
;; - A prompt can hold escape sequences (CSI, and OSC ended by BEL or ST).
;; `prompt-clusters` keeps each as one item of width 0.
(import (std prelude))
(import (std maths))
(import (std unicode grapheme))
(export
text-clusters prompt-clusters cluster-width cluster-shown text-width
word-cluster? find-clusters common-prefix)
;; The grapheme clusters of `s`. "\r\n" is one.
(: (-> string (Vec string)))
(defun (text-clusters s)
(string->graphemes s))
;; Whether code point `c` takes no columns: a non-spacing or enclosing
;; mark, or a format character other than the soft hyphen.
(: (-> int bool))
(defun (zero-width? c)
(and (not (= c 0xad))
(let ((cat (char-general-category (int->char c))))
(or (= cat 'Mn) (= cat 'Me) (= cat 'Cf)))))
;; Whether code point `c` is a letter or a decimal digit.
(: (-> int bool))
(defun (letter-or-digit? c)
(let ((cat (char-general-category (int->char c))))
(or (= cat 'Lu) (= cat 'Ll) (= cat 'Lt) (= cat 'Lm) (= cat 'Lo) (= cat 'Nd))))
(: (-> string int))
(defun (first-code s)
(char->int (string-cursor-ref s (string-cursor-start s))))
(: (-> string bool))
(defun (escape-sequence? c)
(and (> (string-length c) 1) (= (first-code c) 27)))
;; The columns `c` takes. 0 for an escape sequence from `prompt-clusters`.
(: (-> string int))
(defun (cluster-width c)
(cond
((string-empty? c) 0)
((escape-sequence? c) 0)
(else
(def first (first-code c))
(def width (code-width first))
(cond
((or (< first 32) (= first 127)) 2)
((and (>= first 128) (< first 160)) 1)
((= width 2) 2)
;; Emoji presentation, or a flag of two regional indicators.
((string-contains? c "\u{FE0F}") 2)
((and (>= first 0x1f1e6) (<= first 0x1f1ff) (> (string-length c) 1)) 2)
;; A cluster that starts with a mark: the widest of its parts.
((= width 0)
(let ((chars (string->vec c)))
(let go ((i 0) (w 0))
(if (= i (vec-length chars))
w
(go (+ i 1) (max w (code-width (char->int (vec-ref chars i)))))))))
(else width)))))
;; What is written for `c`: "^X" for a C0 control or DEL, U+FFFD for a C1
;; control, else `c`.
(: (-> string string))
(defun (cluster-shown c)
(cond
((string-empty? c) c)
((escape-sequence? c) c)
(else
(def first (first-code c))
(cond
((< first 32) (str "^" (char->string (int->char (+ first 64)))))
((= first 127) "^?")
((and (>= first 128) (< first 160)) "\u{FFFD}")
(else c)))))
;; The columns of `s`, escape sequences as 0.
(: (-> string int))
(defun (text-width s)
(loop (:for c (in-vec (prompt-clusters s)))
(:acc w (summing (cluster-width c)))))
;; Whether `c` is part of a word: it starts with a letter, a digit or "_".
(: (-> string bool))
(defun (word-cluster? c)
(and (not (string-empty? c))
(let ((first (first-code c)))
(or (= first 95) (letter-or-digit? first)))))
;; The width of one code point, as `wcwidth`.
(: (-> int int))
(defun (code-width c)
(cond
((= c 0) 0)
((or (= c 0x200b) (and (>= c 0x1160) (<= c 0x11ff))) 0)
((zero-width? c) 0)
((wide? c) 2)
(else 1)))
;; Ranges of East Asian Wide and Fullwidth code points, and of emoji with
;; emoji presentation by default (Unicode 15). Sorted pairs, inclusive.
(: (Vec int))
(def wide-ranges
[0x1100 0x115f 0x231a 0x231b 0x2329 0x232a 0x23e9 0x23ec 0x23f0 0x23f0
0x23f3 0x23f3 0x25fd 0x25fe 0x2614 0x2615 0x2648 0x2653 0x267f 0x267f
0x2693 0x2693 0x26a1 0x26a1 0x26aa 0x26ab 0x26bd 0x26be 0x26c4 0x26c5
0x26ce 0x26ce 0x26d4 0x26d4 0x26ea 0x26ea 0x26f2 0x26f3 0x26f5 0x26f5
0x26fa 0x26fa 0x26fd 0x26fd 0x2705 0x2705 0x270a 0x270b 0x2728 0x2728
0x274c 0x274c 0x274e 0x274e 0x2753 0x2755 0x2757 0x2757 0x2795 0x2797
0x27b0 0x27b0 0x27bf 0x27bf 0x2b1b 0x2b1c 0x2b50 0x2b50 0x2b55 0x2b55
0x2e80 0x303e 0x3041 0x33ff 0x3400 0x4dbf 0x4e00 0x9fff 0xa000 0xa4cf
0xa960 0xa97f 0xac00 0xd7a3 0xf900 0xfaff 0xfe10 0xfe19 0xfe30 0xfe6f
0xff00 0xff60 0xffe0 0xffe6 0x16fe0 0x16fe4 0x17000 0x18aff 0x1b000 0x1b2ff
0x1f004 0x1f004 0x1f0cf 0x1f0cf 0x1f18e 0x1f18e 0x1f191 0x1f19a 0x1f200 0x1f202
0x1f210 0x1f23b 0x1f240 0x1f248 0x1f250 0x1f251 0x1f260 0x1f265 0x1f300 0x1f320
0x1f32d 0x1f335 0x1f337 0x1f37c 0x1f37e 0x1f393 0x1f3a0 0x1f3ca 0x1f3cf 0x1f3d3
0x1f3e0 0x1f3f0 0x1f3f4 0x1f3f4 0x1f3f8 0x1f43e 0x1f440 0x1f440 0x1f442 0x1f4fc
0x1f4ff 0x1f53d 0x1f54b 0x1f54e 0x1f550 0x1f567 0x1f57a 0x1f57a 0x1f595 0x1f596
0x1f5a4 0x1f5a4 0x1f5fb 0x1f64f 0x1f680 0x1f6c5 0x1f6cc 0x1f6cc 0x1f6d0 0x1f6d2
0x1f6d5 0x1f6d7 0x1f6dc 0x1f6df 0x1f6eb 0x1f6ec 0x1f6f4 0x1f6fc 0x1f7e0 0x1f7eb
0x1f7f0 0x1f7f0 0x1f90c 0x1f93a 0x1f93c 0x1f945 0x1f947 0x1f9ff 0x1fa70 0x1faff
0x20000 0x2fffd 0x30000 0x3fffd])
(: (-> int bool))
(defun (wide? c)
(and (>= c 0x1100)
(let go ((lo 0) (hi (- (quotient (vec-length wide-ranges) 2) 1)))
(if (> lo hi)
#f
(let ((mid (quotient (+ lo hi) 2)))
(cond
((< c (vec-ref wide-ranges (* mid 2))) (go lo (- mid 1)))
((> c (vec-ref wide-ranges (+ (* mid 2) 1))) (go (+ mid 1) hi))
(else #t)))))))
;; The clusters of a prompt: as `text-clusters`, except that an escape
;; sequence is one item, of width 0.
(: (-> string (Vec string)))
(defun (prompt-clusters s)
(def chars (string->vec s))
(def n (vec-length chars))
(defun (text-of from to)
(string-join (vec-map char->string (vec-slice chars from (- to from))) ""))
(let go ((i 0) (plain 0) (out []))
(cond
((= i n)
(if (> n plain) (vec-append out (text-clusters (text-of plain n))) out))
(else
(def length (escape-length chars i))
(if (= length 0)
(go (+ i 1) plain out)
(let ((before (if (> i plain) (vec-append out (text-clusters (text-of plain i))) out)))
(go (+ i length) (+ i length) (vec-add before (text-of i (+ i length))))))))))
;; The length in characters of an escape sequence at `i`, or 0.
(: (-> (Vec char) int int))
(defun (escape-length chars i)
(def n (vec-length chars))
(defun (code j) (char->int (vec-ref chars j)))
(cond
((or (not (= (code i) 27)) (>= (+ i 1) n)) 0)
((= (code (+ i 1)) 91)
;; CSI: parameters and intermediates, then a final byte.
(let go ((j (+ i 2)))
(cond
((= j n) 0)
((and (>= (code j) 0x20) (<= (code j) 0x3f)) (go (+ j 1)))
((and (>= (code j) 0x40) (<= (code j) 0x7e)) (+ 1 (- j i)))
(else 0))))
((= (code (+ i 1)) 93)
;; OSC: ended by BEL, or by ST ("ESC \").
(let go ((j (+ i 2)))
(cond
((= j n) 0)
((= (code j) 7) (+ 1 (- j i)))
((and (= (code j) 27) (< (+ j 1) n) (= (code (+ j 1)) 92)) (+ 2 (- j i)))
(else (go (+ j 1))))))
(else 0)))
;; The index of the first cluster of `text` where the clusters of `query`
;; follow, or -1. Whole clusters only, case matters.
(: (-> string string int))
(defun (find-clusters text query)
(def hay (text-clusters text))
(def needle (text-clusters query))
(def last (- (vec-length hay) (vec-length needle)))
(defun (matches-at? i)
(let go ((j 0))
(cond
((= j (vec-length needle)) #t)
((= (vec-ref hay (+ i j)) (vec-ref needle j)) (go (+ j 1)))
(else #f))))
(let go ((i 0))
(cond
((> i last) -1)
((matches-at? i) i)
(else (go (+ i 1))))))
;; The longest common prefix of `texts`, whole clusters only. Empty for no
;; texts.
(: (-> (Vec string) string))
(defun (common-prefix texts)
(if (vec-empty? texts)
""
(let ((first (text-clusters (vec-ref texts 0))))
(defun (shared other)
(let go ((k 0))
(if (and (< k (vec-length first)) (< k (vec-length other))
(= (vec-ref first k) (vec-ref other k)))
(go (+ k 1))
k)))
(def length
(let go ((i 0) (n (vec-length first)))
(if (= i (vec-length texts))
n
(go (+ i 1) (min n (shared (text-clusters (vec-ref texts i))))))))
(string-join (vec-slice first 0 length) ""))))