bjoterm: the line editor, (bjoterm line)
- line-read with the keys of Emacs and readline: moving by character, word and line, a kill buffer, history with C-r search, Tab completion through #:completer, and input of several lines with #:input-done?. - Grapheme clusters and display widths in glue/Text.cs: the editor moves and deletes by cluster, and wraps lines by width. - Each key is a pure step, so tests/line.bjo runs the keys without a terminal through simulate-line. tests/line-terminal.bjo runs line-read on a pseudo-terminal. - History files, line-history-save and line-history-load!. - examples/repl.bjo: a small REPL. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
fe42387a4c
commit
6863503fa7
7 changed files with 1235 additions and 2 deletions
665
src/line.bjo
Normal file
665
src/line.bjo
Normal file
|
|
@ -0,0 +1,665 @@
|
|||
;; 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.
|
||||
;; - 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.
|
||||
|
||||
(import (std prelude))
|
||||
(import (std maths))
|
||||
(import (bjoterm terminal))
|
||||
|
||||
(export
|
||||
LineEditor LineResult Completion
|
||||
make-line-editor line-read
|
||||
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
|
||||
;; ===========================================================================
|
||||
|
||||
;; 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".
|
||||
(type (: LineResult (Union (: LineText string) LineEof LineCancelled)))
|
||||
|
||||
;; 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)))
|
||||
(: input-done? (Option (-> string bool)))
|
||||
(: history-size int)
|
||||
(: 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.
|
||||
;; - `#:history-size`: the most entries kept; the oldest go first.
|
||||
(: (-> (#:completer (Option (-> string Completion)))
|
||||
(#:input-done? (Option (-> string bool)))
|
||||
(#:history-size int)
|
||||
LineEditor))
|
||||
(defun (make-line-editor #:completer None #:input-done? None #:history-size 1000)
|
||||
(LineEditor (completer completer) (input-done? input-done?)
|
||||
(history-size history-size) (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. `#:continuation` is the prompt of the lines after the first;
|
||||
;; by default, spaces as wide as `prompt`.
|
||||
;; - Sets raw mode for the time it reads, unless the terminal is in raw
|
||||
;; mode already.
|
||||
;; - 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.
|
||||
;; - 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)
|
||||
(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)))))
|
||||
|
||||
(: (-> LineEditor State))
|
||||
(defun (start-state ed)
|
||||
(State (text []) (cursor 0) (kill "") (killing? #f)
|
||||
(hist-at (vec-length (record-ref ed history))) (draft [])
|
||||
(search None) (tabbed? #f)))
|
||||
|
||||
(: (-> LineEditor Terminal string string LineResult) #:sync)
|
||||
(defun (edit-loop ed term prompt cont)
|
||||
(def out (parameter-ref current-output-port))
|
||||
(def/mutable row 0)
|
||||
(defun (draw st)
|
||||
(def lay (layout-state st prompt cont (fst (terminal-size term))))
|
||||
(write-string out (str "\r" (cursor-up row) 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))
|
||||
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))
|
||||
(let go ((st (start-state ed)))
|
||||
(def lay (draw st))
|
||||
(match (line-step ed st (read-event term))
|
||||
((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! row 0)
|
||||
(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 last result)
|
||||
(def shown (draw (record-set last (search None) (cursor (vec-length (record-ref last text))))))
|
||||
(when (= result LineCancelled) (write-string out "^C"))
|
||||
(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) (Tuple (Option LineResult) string)))
|
||||
(defun (simulate-line ed events)
|
||||
(let go ((st (start-state ed))
|
||||
(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 as written to the terminal from the start of the prompt.
|
||||
;; - `shown`: the text, with a line break where a line is full and after a
|
||||
;; 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))))
|
||||
|
||||
(: (-> State string string int Layout))
|
||||
(defun (layout-state st prompt cont width)
|
||||
(match (record-ref st search)
|
||||
((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))
|
||||
(record-ref st text) (record-ref st cursor) width))
|
||||
(None
|
||||
(layout (array->vec (prompt-clusters prompt)) (array->vec (prompt-clusters cont))
|
||||
(record-ref st text) (record-ref st cursor) width))))
|
||||
|
||||
(: (-> (Vec string) (Vec string) (Vec string) int int Layout))
|
||||
(defun (layout prompt cont text cursor width)
|
||||
(def out (stringbuilder-empty))
|
||||
(def/mutable row 0)
|
||||
(def/mutable col 0)
|
||||
(def/mutable cursor-row 0)
|
||||
(def/mutable cursor-col 0)
|
||||
(defun (break!)
|
||||
(stringbuilder-add-string! out "\n")
|
||||
(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! col (+ col w))
|
||||
(when (>= col width) (break!)))
|
||||
(defun (put-prompt! items)
|
||||
(loop (:for item (in-vec items))
|
||||
(:do (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))
|
||||
(Layout (shown (stringbuilder->string out)) (end-row row)
|
||||
(cursor-row cursor-row) (cursor-col cursor-col)))
|
||||
|
||||
;; ===========================================================================
|
||||
;; Editing
|
||||
;; ===========================================================================
|
||||
|
||||
(: (-> (Vec string) string))
|
||||
(defun (joined text)
|
||||
(string-join text ""))
|
||||
|
||||
(: (-> string (Vec string)))
|
||||
(defun (clusters s)
|
||||
(array->vec (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 (vec->array 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)
|
||||
(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)) (Edited (move st (min n (+ cursor 1)))))
|
||||
((Tuple (KeyChar #\f) (Tuple #t #f)) (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 _) (Edited (move st (word-forward st))))
|
||||
((Tuple (KeyChar #\f) (Tuple #f #t)) (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 _) (Edited (move st (line-end st))))
|
||||
((Tuple (KeyChar #\e) (Tuple #t #f)) (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)) (SuspendNow st))
|
||||
(_ (Bell st))))))
|
||||
Loading…
Add table
Add a link
Reference in a new issue