;; 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 line): a line editor for shells and REPLs. ;; ;; (def (Ok term) (terminal-open) :leave-with 1) ;; (def ed (make-line-editor)) ;; (let go () ;; (match (line-read ed term "> ") ;; ((LineText text) (println (str "you wrote " text)) (go)) ;; (LineCancelled (go)) ;; (LineEof 0))) ;; ;; - The keys are those of Emacs and readline. See `line-read`. ;; - The buffer can have several lines. Enter accepts the input unless ;; `#:input-done?` says it is not complete; then Enter starts a new line. ;; Alt-Enter and Ctrl-J always start a new line. ;; - The editor moves and deletes by grapheme cluster, and lays out text by ;; 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. ;; - Input taller than the screen is drawn in part: the rows around the ;; cursor, and a row that says how many rows are hidden above or below. ;; The accepted input is drawn whole. ;; - 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. ;; - `#:suggester` shows a suggestion after the input, dimmed, as fish does. ;; Keys that move right at the end of the input accept it. ;; - `#:command-key?` hands keys to the caller: `line-read` erases the input ;; and returns `LineKey`. ;; - The design is in plan.org, phase 2. (import (std prelude)) (import (std maths)) (import (bjoterm terminal)) (import (bjoterm text)) (export LineEditor LineResult Completion make-line-editor line-read line-history line-history-add! line-history-load! line-history-save simulate-line cursor-row-after-reflow input-window) ;; =========================================================================== ;; Types ;; =========================================================================== ;; What `line-read` returns. ;; - `LineText`: the accepted input. Lines are separated by "\n". ;; - `LineEof`: Ctrl-D on an empty buffer, or the terminal hung up. ;; - `LineCancelled`: Ctrl-C. The input is left on the screen with "^C". ;; - `LineKey`: a key that `#:command-key?` claimed, and the input when it ;; was pressed. The input is erased from the screen, prompt included, so ;; the next `line-read` draws in its place. (type (: LineResult (Union (: LineText string) LineEof LineCancelled (: LineKey TermEvent string)))) ;; What a completer returns for the text before the cursor. ;; - `prefix`: the end of that text that the candidates replace, such as ;; the word being written. It must be a suffix of the text. ;; - `candidates`: each a whole replacement for `prefix`. A candidate can end ;; with a space, to start the next word. (type (: Completion (Record (: prefix string) (: candidates (Vec string))))) ;; A line editor: its options and its history. (type (: LineEditor #:opaque (Record (: completer (Option (-> string Completion))) (: suggester (Option (-> string (Vec string) (Option string)))) (: command-key? (Option (-> TermEvent string bool))) (: input-done? (Option (-> string bool))) (: history-size int) (: reflow? (Option bool)) (: suspend? bool) (: history (Vec string) #:mutable)))) ;; Reverse search through the history. ;; - `at`: the history index of the match, or the history's length before ;; the first match. ;; - `before-text` and `before-cursor`: the buffer when the search began, ;; restored by Ctrl-G. (type (: Search (Record (: query string) (: at int) (: failed? bool) (: before-text (Vec string)) (: before-cursor int)))) ;; The state of one `line-read`. ;; - `text`: grapheme clusters; "\n" separates lines. ;; - `cursor`: an index into `text`, from 0 to its length. ;; - `killing?`: the last key killed text, so the next kill adds to `kill`. ;; - `hist-at`: the history entry shown; the history's length for the ;; input being written, which is kept in `draft` meanwhile. ;; - `tabbed?`: the last key was Tab and completed nothing more, so the next ;; Tab lists the candidates. (type (: State (Record (: text (Vec string)) (: cursor int) (: kill string) (: killing? bool) (: hist-at int) (: draft (Vec string)) (: search (Option Search)) (: tabbed? bool)))) ;; What one key does. (type (: Step (Union (: Edited State) (: Finished State LineResult) (: ShowList State (Vec string)) (: ClearScreen State) (: SuspendNow State) (: Bell State)))) ;; =========================================================================== ;; The editor and its history ;; =========================================================================== ;; Makes a line editor. ;; - `#:completer`: called by Tab with the text before the cursor. ;; - `#:input-done?`: called by Enter with the whole input. #f makes Enter ;; start a new line; a REPL returns #f while brackets are open. ;; - `#:suggester`: called with the whole input and the history, oldest ;; first, while the cursor is at the end of the input. Returns the text to ;; show after the input, or None. Called after each key, so it must be fast. ;; - `#:command-key?`: called with each key and the whole input. #t makes ;; `line-read` return `(LineKey key input)`. ;; - `#:history-size`: the most entries kept; the oldest go first. ;; - `#:suspend?`: whether C-z stops the program. A shell sets #f; C-z ;; then rings the bell. ;; - `#: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))) (#:suggester (Option (-> string (Vec string) (Option string)))) (#:command-key? (Option (-> TermEvent string bool))) (#:input-done? (Option (-> string bool))) (#:history-size int) (#:reflow? (Option bool)) (#:suspend? bool) LineEditor)) (defun (make-line-editor #:completer None #:suggester None #:command-key? None #:input-done? None #:history-size 1000 #:reflow? None #:suspend? #t) (LineEditor (completer completer) (suggester suggester) (command-key? command-key?) (input-done? input-done?) (history-size history-size) (reflow? reflow?) (suspend? suspend?) (history []))) ;; The history, oldest first. (: (-> LineEditor (Vec string))) (defun (line-history ed) (record-ref ed history)) ;; Adds an entry to the history, unless it is empty or the same as the last ;; entry. Drops the oldest entries above the editor's history size. (: (-> LineEditor string void)) (defun (line-history-add! ed text) (def history (record-ref ed history)) (def n (vec-length history)) (unless (or (string-empty? text) (and (> n 0) (= (vec-ref history (- n 1)) text))) (def added (vec-add history text)) (def extra (- (vec-length added) (record-ref ed history-size))) (record-set! ed (history (if (> extra 0) (vec-slice added extra (- (vec-length added) extra)) added))))) ;; Reads a history file written by `line-history-save`, and adds its entries. ;; A file that does not exist adds nothing. Returns the error of a file ;; that cannot be read. (: (-> LineEditor string (Result FsError Unit))) (defun (line-history-load! ed path) (if (not (file-exists? path)) (Ok unit) (match (file-read-text path) ((Err e) (Err e)) ((Ok text) (loop (:for line (in-vec (string-split text "\n"))) (:do (unless (string-empty? line) (line-history-add! ed (history-unescape line))))) (Ok unit))))) ;; Writes the history to a file, one entry per line. "\n" in an entry is ;; written as "\\n", and "\\" as "\\\\". (: (-> LineEditor string (Result FsError Unit))) (defun (line-history-save ed path) (file-write-text path (string-join (vec-map (fun (e) (str (history-escape e) "\n")) (record-ref ed history)) ""))) (: (-> string string)) (defun (history-escape text) (string-replace (string-replace text "\\" "\\\\") "\n" "\\n")) (: (-> string string)) (defun (history-unescape line) (def out (stringbuilder-empty)) (let go ((cs (string->list line))) (match cs (Nil unit) ((Cons #\\ (Cons #\n more)) (stringbuilder-add! out #\newline) (go more)) ((Cons #\\ (Cons #\\ more)) (stringbuilder-add! out #\\) (go more)) ((Cons c more) (stringbuilder-add! out c) (go more)))) (stringbuilder->string out)) ;; =========================================================================== ;; Reading a line ;; =========================================================================== ;; Reads one input from the terminal, with editing. ;; - `prompt` may contain escape sequences, such as colors; they take no ;; columns. It may contain line breaks: the input starts after its last ;; line. `#:continuation` is the prompt of the lines after the first; ;; by default, spaces as wide as the last line of `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 ;; the line), C-u (to its start), C-w and M-Backspace (the word before), ;; M-d (the word after); C-y yanks. C-t swaps two characters. ;; - History: Up and Down on the first and last line, C-p, C-n; C-r ;; searches back, again C-r for an older match, C-g ends the search. ;; - Tab completes with `#:completer`, and a second Tab lists the ;; candidates. Without a completer it inserts a tab. ;; - A suggestion from `#:suggester`: at the end of the input, Right, C-f, ;; End and C-e accept all of it; M-f, C-Right and M-Right one word. ;; - Enter accepts (see `#:input-done?`), M-Enter and C-j start a new line, ;; C-l clears the screen, C-z stops the program (see `#:suspend?`), ;; C-c cancels, and C-d on an empty buffer is end of input. ;; - `#:notices`: a function that `line-read` calls every ;; `notice-poll-ms` while it waits for a key. The lines it returns are ;; written above the input, which is then drawn again below them. For a ;; shell's "[1] Done" lines. It must not write to the terminal itself. ;; - `#:initial`: the input to start with, the cursor at its end. (: (-> LineEditor Terminal string (#:continuation (Option string)) (#:notices (Option (-> (Vec string)))) (#:initial string) LineResult)) (defun (line-read ed term prompt #:continuation None #:notices None #:initial "") (def cont (match continuation ((Some c) c) (None (string-pad-left "" (text-width (last-line prompt)))))) (if (terminal-raw? term) (edit-loop ed term prompt cont notices initial) ;; 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 notices initial)))) (#:bjo (with-raw-mode term (bjoroutine () (edit-loop ed term prompt cont notices initial))))))) ;; How a suggestion is drawn: bright black, which most themes show as grey. (: (Vec Style)) (def ghost-style [(StyleFg (Ansi 8))]) ;; How often `line-read` calls its `#:notices` function, in milliseconds. (: notice-poll-ms int) (def notice-poll-ms 200) ;; The text after the last line break of `s`, or all of it. (: (-> string string)) (defun (last-line s) (let go ((rest s)) (match (string-split-once rest "\n") ((Some (Tuple _ after)) (go after)) (None rest)))) (: (-> LineEditor string State)) (defun (start-state ed initial) (def text (clusters initial)) (State (text text) (cursor (vec-length text)) (kill "") (killing? #f) (hist-at (vec-length (record-ref ed history))) (draft []) (search None) (tabbed? #f))) (: (-> LineEditor Terminal string string (Option (-> (Vec string))) string LineResult)) (defun (edit-loop ed term prompt cont notices initial) (def out (parameter-ref current-output-port)) (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. (: (Option Drawn)) (def/mutable drawn None) (def/mutable drawn-width 0) ;; The first row of the input in the last window drawn. (def/mutable top 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))))) ;; Draws `st`: the rows that fit on the screen, or all when `whole?`. ;; The suggestion is drawn unless `whole?`. (defun (draw st whole?) (def (Tuple width height) (terminal-size term)) (def ghost (if whole? [] (match (suggestion ed st) ((Some s) (clusters s)) (None [])))) (def lay (layout-state st prompt cont width ghost)) (def shown (window-of lay width (if whole? None (Some height)) top)) (write-string out (str "\r" (cursor-up (rows-up width)) clear-below (record-ref shown text) (cursor-up (- (last-row shown) (record-ref shown cursor-row))) "\r" (cursor-forward (record-ref shown cursor-col)))) (set! top (record-ref shown top)) (set! drawn (Some shown)) (set! drawn-width width) shown) (: (-> Drawn int)) (defun (last-row shown) (- (vec-length (record-ref shown rows)) 1)) ;; Moves below the input, for output that follows it. (: (-> Drawn void)) (defun (leave shown) (write-string out (str (cursor-down (- (last-row shown) (record-ref shown cursor-row))) "\n")) (set! drawn None)) ;; The next event. With `notices`, writes their lines above the input ;; while it waits, and draws `st` again below them. (: (-> State TermEvent)) (defun (next-event st) (match notices (None (read-event term)) ((Some f) (let poll () (match (read-event/timeout term notice-poll-ms) ((Some ev) ev) (None (def lines (f)) (unless (vec-empty? lines) (def (Tuple width _) (terminal-size term)) (write-string out (str "\r" (cursor-up (rows-up width)) clear-below (string-join (vec-map (fun (l) (str l "\n")) lines) ""))) (set! drawn None) (ignore (draw st #f))) (poll))))))) (let go ((st (start-state ed initial))) (def lay (draw st #f)) (match (line-step ed st (next-event st)) ((Edited next) (go next)) ((Bell next) (write-string out "\u{7}") (go next)) ((ClearScreen next) (write-string out (str clear-screen (cursor-to 0 0))) (set! drawn None) (go next)) ((SuspendNow next) (leave lay) (terminal-suspend term) (go next)) ((ShowList next items) (leave lay) (write-string out (columns items (fst (terminal-size term)))) (go next)) ((Finished _ (LineKey ev text)) (def (Tuple width _) (terminal-size term)) (write-string out (str "\r" (cursor-up (rows-up width)) clear-below)) (set! drawn None) (flush-port out) (LineKey ev text)) ((Finished last result) (def shown (draw (record-set last (search None) (cursor (vec-length (record-ref last text)))) #t)) (match result (LineCancelled (write-string out "^C")) (_ unit)) (leave shown) (flush-port out) (match result ((LineText text) (line-history-add! ed text)) (_ unit)) result)))) ;; `items` in columns as wide as the widest, filling rows first, each row ;; ended by "\n". (: (-> (Vec string) int string)) (defun (columns items width) (def widest (let go ((i 0) (w 0)) (if (= i (vec-length items)) w (go (+ i 1) (max w (text-width (vec-ref items i))))))) (def cell (+ widest 2)) (def per-row (max 1 (quotient width cell))) (def out (stringbuilder-empty)) (loop (:for item (in-vec items)) (:for i (range 0 (vec-length items))) (:do (stringbuilder-add-string! out item) (if (or (= (remainder (+ i 1) per-row) 0) (= (+ i 1) (vec-length items))) (stringbuilder-add-string! out "\n") (stringbuilder-add-string! out (string-pad-left "" (- cell (text-width item))))))) (stringbuilder->string out)) ;; Runs the editor on `events` without a terminal, as `line-read` would. ;; Returns the result, or None when the events ran out first, and the ;; buffer's text at the end. For tests. (: (-> LineEditor (Vec TermEvent) (#:initial string) (Tuple (Option LineResult) string))) (defun (simulate-line ed events #:initial "") (let go ((st (start-state ed initial)) (i 0)) (if (= i (vec-length events)) (Tuple None (joined (record-ref st text))) (match (line-step ed st (vec-ref events i)) ((Finished last result) (match result ((LineText text) (line-history-add! ed text)) (_ unit)) (Tuple (Some result) (joined (record-ref last text)))) ((Edited next) (go next (+ i 1))) ((Bell next) (go next (+ i 1))) ((ClearScreen next) (go next (+ i 1))) ((SuspendNow next) (go next (+ i 1))) ((ShowList next _) (go next (+ i 1))))))) ;; =========================================================================== ;; Layout ;; =========================================================================== ;; The input in rows, from the start of the prompt. ;; - `texts`: the text of each row. A row ends where a line is full, and ;; after a line that ends exactly at the edge there is an empty row. ;; - `rows`: the widths of the items on each row, for ;; `cursor-row-after-reflow`. ;; - `cursor-row` and `cursor-col`: where the editor's cursor is. ;; `Drawn` is the same for the rows written to the screen, which can be ;; fewer, with marker rows. (type (: Layout (Record (: texts (Vec string)) (: rows (Vec (Vec int))) (: cursor-row int) (: cursor-col int)))) (: (-> State string string int (Vec string) Layout)) (defun (layout-state st prompt cont width ghost) (match (record-ref st search) ((Some s) (def label (str "(" (if (record-ref s failed?) "failed " "") "search `" (record-ref s query) "'): ")) (layout (prompt-clusters label) (prompt-clusters cont) (record-ref st text) (record-ref st cursor) width [])) (None (layout (prompt-clusters prompt) (prompt-clusters cont) (record-ref st text) (record-ref st cursor) width ghost)))) ;; `ghost`: clusters drawn dimmed after `text`, where the cursor does not go. (: (-> (Vec string) (Vec string) (Vec string) int int (Vec string) Layout)) (defun (layout prompt cont text cursor width ghost) (def out (stringbuilder-empty)) (def/mutable texts []) (def/mutable row 0) (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 []) (set! texts (vec-add texts (stringbuilder->string out))) (stringbuilder-clear! out) (set! row (+ row 1)) (set! col 0)) ;; Writes `shown`, `w` columns wide, on this row if it fits. (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!))) ;; A line break in a prompt ends its row, as one in the text does. (defun (put-prompt! items) (loop (:for item (in-vec items)) (:do (if (or (= item "\n") (= item "\r\n")) (break!) (put! (cluster-shown item) (cluster-width item)))))) (put-prompt! prompt) (loop (:for c (in-vec text)) (:for i (range 0 (vec-length text))) (:do (when (= i cursor) (set! cursor-row row) (set! cursor-col col)) (cond ((or (= c "\n") (= c "\r\n")) (break!) (put-prompt! cont)) ((= c "\t") (def w (- 8 (remainder col 8))) (put! (string-pad-left "" w) w)) (else (put! (cluster-shown c) (cluster-width c)))))) (when (= cursor (vec-length text)) (set! cursor-row row) (set! cursor-col col)) (loop (:for c (in-vec ghost)) (:do (cond ((or (= c "\n") (= c "\r\n")) (break!) (put-prompt! cont)) ((= c "\t") (def w (- 8 (remainder col 8))) (put! (string-pad-left "" w) w)) (else (put! (styled (cluster-shown c) ghost-style) (cluster-width c)))))) (Layout (texts (vec-add texts (stringbuilder->string out))) (rows (vec-add rows this-row)) (cursor-row cursor-row) (cursor-col cursor-col))) ;; Which rows of an input `total` rows tall to draw on a screen `height` ;; rows tall. Returns the first row and the number of rows. ;; - All rows when they fit. ;; - Else the window keeps `prev-top`, the first row of the last drawing, ;; when the cursor row is in it, and moves the least it must otherwise. ;; - With 3 or more rows, a row each is left for the markers of hidden ;; rows above and below: one marker at the start and at the end of the ;; input, two between. (: (-> int int int int (Tuple int int))) (defun (input-window total height cursor-row prev-top) (defun (clamp x lo hi) (max lo (min hi x))) (cond ((<= total height) (Tuple 0 total)) ((< height 3) (def h (max height 1)) (Tuple (clamp prev-top (- cursor-row (- h 1)) cursor-row) h)) (else (def top (clamp prev-top (- cursor-row (- height 3)) cursor-row)) (cond ((<= top 0) (Tuple 0 (- height 1))) ((>= (+ top (- height 2)) total) (Tuple (- total (- height 1)) (- height 1))) (else (Tuple top (- height 2))))))) ;; What is on the screen after a drawing. ;; - `text`: what to write from the start of the first row. ;; - `rows`: the widths of the items on each row written. ;; - `cursor-row` and `cursor-col`: the cursor, from the first row written. ;; - `top`: the first row of the input that is written. (type (: Drawn (Record (: text string) (: rows (Vec (Vec int))) (: cursor-row int) (: cursor-col int) (: top int)))) ;; The rows of `lay` to write: those `input-window` chooses with `height`, ;; or all of them when `height` is None. (: (-> Layout int (Option int) int Drawn)) (defun (window-of lay width height prev-top) (def total (vec-length (record-ref lay rows))) (def (Tuple top count) (match height ((Some h) (input-window total h (record-ref lay cursor-row) prev-top)) (None (Tuple 0 total)))) (def hidden-below (- total top count)) (def markers? (and (> total count) (match height ((Some h) (>= h 3)) (None #f)))) ;; A marker row that fits in `width`. (defun (marker arrow n) (def long (str arrow " " (int->string n) (if (= n 1) " more row" " more rows"))) (def text (if (<= (text-width long) width) long arrow)) (Tuple text (vec-map (fun (_) 1) (text-clusters text)))) (def above (if (and markers? (> top 0)) [(marker "\u{2191}" top)] [])) (def below (if (and markers? (> hidden-below 0)) [(marker "\u{2193}" hidden-below)] [])) (defun (around items middle) (vec-append (vec-append (vec-map items above) middle) (vec-map items below))) (Drawn (text (string-join (around fst (vec-slice (record-ref lay texts) top count)) "\n")) (rows (around snd (vec-slice (record-ref lay rows) top count))) (cursor-row (+ (vec-length above) (- (record-ref lay cursor-row) top))) (cursor-col (record-ref lay cursor-col)) (top top))) ;; 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 ;; =========================================================================== ;; The suggestion for `st`: the text after the input, not empty. None during ;; a search, when the cursor is not at the end, or the input is empty. (: (-> LineEditor State (Option string))) (defun (suggestion ed st) (def text (record-ref st text)) (match (record-ref ed suggester) (None None) ((Some f) (if (or (some? (record-ref st search)) (vec-empty? text) (not (= (record-ref st cursor) (vec-length text)))) None (match (f (joined text) (record-ref ed history)) ((Some s) (if (string-empty? s) None (Some s))) (None None)))))) ;; At the end of the input with a suggestion, adds all of it, or with ;; `word?` up to the end of its first word. Else `otherwise`. (: (-> LineEditor State bool (-> Step) Step)) (defun (accept-suggestion ed st word? otherwise) (match (suggestion ed st) (None (otherwise)) ((Some s) (if (not word?) (Edited (insert st s)) (let* ((cs (clusters s)) (n (vec-length cs)) (gap (let go ((i 0)) (if (and (< i n) (not (word-cluster? (vec-ref cs i)))) (go (+ i 1)) i))) (end (let go ((i gap)) (if (and (< i n) (word-cluster? (vec-ref cs i))) (go (+ i 1)) i)))) (Edited (insert st (joined (vec-slice cs 0 end))))))))) (: (-> (Vec string) string)) (defun (joined text) (string-join text "")) (: (-> string (Vec string))) (defun (clusters s) (text-clusters s)) (: (-> State string State)) (defun (insert st s) (def text (record-ref st text)) (def cursor (record-ref st cursor)) (def before (joined (vec-slice text 0 cursor))) (def after (joined (vec-slice text cursor (- (vec-length text) cursor)))) (record-set st (text (clusters (str before s after))) (cursor (vec-length (clusters (str before s)))))) (: (-> State int int string)) (defun (text-between st from to) (joined (vec-slice (record-ref st text) from (- to from)))) ;; Removes the clusters from `from` to `to`, and puts the cursor at `from`. (: (-> State int int State)) (defun (remove st from to) (def text (record-ref st text)) (record-set st (text (vec-append (vec-slice text 0 from) (vec-slice text to (- (vec-length text) to)))) (cursor from))) ;; Removes from `from` to `to` into the kill buffer. After another kill, ;; adds to it: before it when `back?`, else after it. (: (-> State bool int int bool State)) (defun (kill st killing? from to back?) (def taken (text-between st from to)) (def kept (record-ref st kill)) (def removed (remove st from to)) (record-set removed (kill (cond ((not killing?) taken) (back? (str taken kept)) (else (str kept taken)))) (killing? #t))) (: (-> State int string)) (defun (at st i) (vec-ref (record-ref st text) i)) (: (-> string bool)) (defun (newline? c) (or (= c "\n") (= c "\r\n"))) (: (-> State int)) (defun (line-start st) (let go ((i (record-ref st cursor))) (if (or (= i 0) (newline? (at st (- i 1)))) i (go (- i 1))))) (: (-> State int)) (defun (line-end st) (def n (vec-length (record-ref st text))) (let go ((i (record-ref st cursor))) (if (or (= i n) (newline? (at st i))) i (go (+ i 1))))) (: (-> State int)) (defun (word-back st) (def skip-gap (let go ((i (record-ref st cursor))) (if (and (> i 0) (not (word-cluster? (at st (- i 1))))) (go (- i 1)) i))) (let go ((i skip-gap)) (if (and (> i 0) (word-cluster? (at st (- i 1)))) (go (- i 1)) i))) (: (-> State int)) (defun (word-forward st) (def n (vec-length (record-ref st text))) (def skip-gap (let go ((i (record-ref st cursor))) (if (and (< i n) (not (word-cluster? (at st i)))) (go (+ i 1)) i))) (let go ((i skip-gap)) (if (and (< i n) (word-cluster? (at st i))) (go (+ i 1)) i))) (: (-> State int State)) (defun (move st i) (record-set st (cursor i))) ;; The columns from `from` to `to`, by cluster width. (: (-> State int int int)) (defun (columns-between st from to) (loop (:for i (range from to)) (:acc w (summing (cluster-width (at st i)))))) ;; Moves to the line before (`up?`) or after, at the same column as far as ;; that line reaches. None on the first or last line. (: (-> State bool (Option State))) (defun (vertical st up?) (def start (line-start st)) (def end (line-end st)) (def n (vec-length (record-ref st text))) (def col (columns-between st start (record-ref st cursor))) (defun (to-column from) (let go ((i from) (w 0)) (if (or (= i n) (newline? (at st i))) i (let ((next (+ w (cluster-width (at st i))))) (if (> next col) i (go (+ i 1) next)))))) (cond ((and up? (> start 0)) (Some (move st (to-column (line-start (move st (- start 1))))))) ((and (not up?) (< end n)) (Some (move st (to-column (+ end 1))))) (else None))) ;; Shows history entry `i`; the history's length is the draft. (: (-> LineEditor State int State)) (defun (show-history ed st i) (def history (record-ref ed history)) (def n (vec-length history)) (def saved (if (= (record-ref st hist-at) n) (record-set st (draft (record-ref st text))) st)) (def text (if (= i n) (record-ref saved draft) (clusters (vec-ref history i)))) (record-set saved (text text) (cursor (vec-length text)) (hist-at i))) (: (-> LineEditor State Step)) (defun (history-back ed st) (if (> (record-ref st hist-at) 0) (Edited (show-history ed st (- (record-ref st hist-at) 1))) (Bell st))) (: (-> LineEditor State Step)) (defun (history-forward ed st) (if (< (record-ref st hist-at) (vec-length (record-ref ed history))) (Edited (show-history ed st (+ (record-ref st hist-at) 1))) (Bell st))) ;; Enter: accepts the input, or starts a new line when `#:input-done?` ;; says the input is not complete. (: (-> LineEditor State Step)) (defun (enter ed st) (def text (joined (record-ref st text))) (def done? (match (record-ref ed input-done?) ((Some f) (f text)) (None #t))) (if done? (Finished st (LineText text)) (Edited (insert st "\n")))) (: (-> LineEditor State bool Step)) (defun (complete ed st tabbed?) (match (record-ref ed completer) (None (Edited (insert st "\t"))) ((Some completer) (def cursor (record-ref st cursor)) (def before (text-between st 0 cursor)) (def c (completer before)) (def prefix (record-ref c prefix)) (def candidates (record-ref c candidates)) (def k (if (string-ends-with? before prefix) (vec-length (clusters prefix)) 0)) (defun (replace-with s) (insert (remove st (- cursor k) cursor) s)) (cond ((= (vec-length candidates) 0) (Bell st)) ((= (vec-length candidates) 1) (Edited (replace-with (vec-ref candidates 0)))) (else (def common (common-prefix candidates)) (cond ((> (vec-length (clusters common)) k) (Edited (replace-with common))) (tabbed? (ShowList st candidates)) (else (Bell (record-set st (tabbed? #t)))))))))) ;; The next older match of `query` from history index `from` down, or None. (: (-> LineEditor string int (Option (Tuple int int)))) (defun (search-from ed query from) (def history (record-ref ed history)) (let go ((i from)) (if (< i 0) None (let ((found (find-clusters (vec-ref history i) query))) (if (>= found 0) (Some (Tuple i found)) (go (- i 1))))))) ;; Searches from history index `from` down, and shows the match. (: (-> LineEditor State Search int Step)) (defun (search-step ed st s from) (match (search-from ed (record-ref s query) from) ((Some (Tuple i found)) (def text (clusters (vec-ref (record-ref ed history) i))) (Edited (record-set st (text text) (cursor found) (hist-at i) (search (Some (record-set s (at i) (failed? #f))))))) (None (Bell (record-set st (search (Some (record-set s (failed? #t))))))))) (: (-> LineEditor State Search TermEvent Step)) (defun (searching ed st s ev) (def query (record-ref s query)) (def at (record-ref s at)) (def last (- (vec-length (record-ref ed history)) 1)) (match ev ((TermKey (KeyChar c) (Mods (ctrl? #f) (alt? #f))) (search-step ed st (record-set s (query (str query (char->string c)))) (min at last))) ((TermKey KeyBackspace _) (def shorter (clusters query)) (def q (joined (vec-slice shorter 0 (max 0 (- (vec-length shorter) 1))))) (search-step ed st (record-set s (query q)) last)) ((TermKey (KeyChar #\r) (Mods (ctrl? #t))) (search-step ed st s (- at 1))) ((TermKey (KeyChar #\g) (Mods (ctrl? #t))) (Edited (record-set st (text (record-ref s before-text)) (cursor (record-ref s before-cursor)) (search None) (hist-at (+ last 1))))) ((TermKey KeyEscape _) (Edited (record-set st (text (record-ref s before-text)) (cursor (record-ref s before-cursor)) (search None) (hist-at (+ last 1))))) ((TermResized _ _) (Edited st)) ;; Any other key ends the search, keeps the match, and does what it does. (_ (line-step ed (record-set st (search None)) ev)))) ;; What `ev` does to `st`. (: (-> LineEditor State TermEvent Step)) (defun (line-step ed prev ev) (def claimed? (and (none? (record-ref prev search)) (match (record-ref ed command-key?) ((Some f) (f ev (joined (record-ref prev text)))) (None #f)))) (cond (claimed? (Finished prev (LineKey ev (joined (record-ref prev text))))) (else (match (record-ref prev search) ((Some s) (searching ed prev s ev)) (None (editing ed prev ev)))))) (: (-> LineEditor State TermEvent Step)) (defun (editing ed prev ev) ;; The flags hold only for the key after the one that set them. (def st (record-set prev (killing? #f) (tabbed? #f))) (def killing? (record-ref prev killing?)) (def cursor (record-ref st cursor)) (def n (vec-length (record-ref st text))) (match ev (TermEnd (Finished st LineEof)) ((TermResized _ _) (Edited st)) ((TermPaste text) (Edited (insert st text))) ((TermKey key (Mods (shift? _) (alt? alt?) (ctrl? ctrl?))) (match (Tuple key (Tuple ctrl? alt?)) ;; Characters. ((Tuple (KeyChar c) (Tuple #f #f)) (Edited (insert st (char->string c)))) ;; Accepting, new lines and cancelling. ((Tuple KeyEnter (Tuple _ #f)) (enter ed st)) ((Tuple KeyEnter (Tuple _ #t)) (Edited (insert st "\n"))) ((Tuple (KeyChar #\j) (Tuple #t _)) (Edited (insert st "\n"))) ((Tuple (KeyChar #\c) (Tuple #t _)) (Finished st LineCancelled)) ((Tuple (KeyChar #\d) (Tuple #t #f)) (cond ((= n 0) (Finished st LineEof)) ((< cursor n) (Edited (remove st cursor (+ cursor 1)))) (else (Bell st)))) ;; Moving. ((Tuple KeyLeft (Tuple #f #f)) (Edited (move st (max 0 (- cursor 1))))) ((Tuple (KeyChar #\b) (Tuple #t #f)) (Edited (move st (max 0 (- cursor 1))))) ((Tuple KeyRight (Tuple #f #f)) (accept-suggestion ed st #f (fun () (Edited (move st (min n (+ cursor 1))))))) ((Tuple (KeyChar #\f) (Tuple #t #f)) (accept-suggestion ed st #f (fun () (Edited (move st (min n (+ cursor 1))))))) ((Tuple KeyLeft _) (Edited (move st (word-back st)))) ((Tuple (KeyChar #\b) (Tuple #f #t)) (Edited (move st (word-back st)))) ((Tuple KeyRight _) (accept-suggestion ed st #t (fun () (Edited (move st (word-forward st)))))) ((Tuple (KeyChar #\f) (Tuple #f #t)) (accept-suggestion ed st #t (fun () (Edited (move st (word-forward st)))))) ((Tuple KeyHome _) (Edited (move st (line-start st)))) ((Tuple (KeyChar #\a) (Tuple #t #f)) (Edited (move st (line-start st)))) ((Tuple KeyEnd _) (accept-suggestion ed st #f (fun () (Edited (move st (line-end st)))))) ((Tuple (KeyChar #\e) (Tuple #t #f)) (accept-suggestion ed st #f (fun () (Edited (move st (line-end st)))))) ;; Lines, then the history. ((Tuple KeyUp _) (match (vertical st #t) ((Some moved) (Edited moved)) (None (history-back ed st)))) ((Tuple KeyDown _) (match (vertical st #f) ((Some moved) (Edited moved)) (None (history-forward ed st)))) ((Tuple (KeyChar #\p) (Tuple #t #f)) (history-back ed st)) ((Tuple (KeyChar #\n) (Tuple #t #f)) (history-forward ed st)) ((Tuple (KeyChar #\r) (Tuple #t #f)) (def s (Search (query "") (at (vec-length (record-ref ed history))) (failed? #f) (before-text (record-ref st text)) (before-cursor cursor))) (Edited (record-set st (search (Some s))))) ;; Deleting. ((Tuple KeyBackspace (Tuple _ #f)) (if (> cursor 0) (Edited (remove st (- cursor 1) cursor)) (Bell st))) ((Tuple KeyBackspace (Tuple _ #t)) (Edited (kill st killing? (word-back st) cursor #t))) ((Tuple (KeyChar #\h) (Tuple #t #f)) (if (> cursor 0) (Edited (remove st (- cursor 1) cursor)) (Bell st))) ((Tuple KeyDelete _) (if (< cursor n) (Edited (remove st cursor (+ cursor 1))) (Bell st))) ((Tuple (KeyChar #\k) (Tuple #t #f)) (def end (line-end st)) ;; At the end of a line, C-k joins the next line. (Edited (kill st killing? cursor (if (and (= end cursor) (< end n)) (+ end 1) end) #f))) ((Tuple (KeyChar #\u) (Tuple #t #f)) (Edited (kill st killing? (line-start st) cursor #t))) ((Tuple (KeyChar #\w) (Tuple #t #f)) (Edited (kill st killing? (word-back st) cursor #t))) ((Tuple (KeyChar #\d) (Tuple #f #t)) (Edited (kill st killing? cursor (word-forward st) #f))) ((Tuple (KeyChar #\y) (Tuple #t #f)) (Edited (insert st (record-ref st kill)))) ((Tuple (KeyChar #\t) (Tuple #t #f)) (cond ((or (< n 2) (= cursor 0)) (Bell st)) (else ;; At the end, the two before the cursor; else the one before ;; and the one under it, and the cursor moves on. (def i (if (= cursor n) (- cursor 1) cursor)) (def a (at st (- i 1))) (def b (at st i)) (def text (vec-set (vec-set (record-ref st text) (- i 1) b) i a)) (Edited (record-set st (text text) (cursor (+ i 1))))))) ;; Completion, the screen, and the program. ((Tuple KeyTab (Tuple #f #f)) (complete ed st (record-ref prev tabbed?))) ((Tuple (KeyChar #\i) (Tuple #t #f)) (complete ed st (record-ref prev tabbed?))) ((Tuple (KeyChar #\l) (Tuple #t #f)) (ClearScreen st)) ((Tuple (KeyChar #\z) (Tuple #t #f)) (if (record-ref ed suspend?) (SuspendNow st) (Bell st))) (_ (Bell st))))))