diff --git a/AGENTS.md b/AGENTS.md
index 8dd362a..4918a69 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -21,6 +21,11 @@ Examples:
## This package
- `bjo build` builds the library and the glue in `glue/`.
-- `bjo test` runs `tests/keys.bjo` (the decoder, from bytes) and
- `tests/terminal.bjo` (raw mode on a pseudo-terminal, under `script`).
+- `bjo test` runs the tests:
+ - `tests/keys.bjo`: the decoder, from bytes.
+ - `tests/line.bjo`: the line editor's keys, history and completion,
+ through `simulate-line`, without a terminal.
+ - `tests/terminal.bjo` and `tests/line-terminal.bjo`: raw mode and
+ `line-read` on a pseudo-terminal, under `script`.
+- `examples/keys.bjo` prints events; `examples/repl.bjo` is a small REPL.
- `plan.org` has the decisions and the phases.
diff --git a/examples/repl.bjo b/examples/repl.bjo
new file mode 100644
index 0000000..345c670
--- /dev/null
+++ b/examples/repl.bjo
@@ -0,0 +1,43 @@
+;; A small REPL shell: brackets make a new line, Tab completes a few words,
+;; and the history is kept in a file.
+;;
+;; bjo run examples/repl.bjo
+
+(import (std prelude))
+(import (bjoterm terminal))
+(import (bjoterm line))
+
+(: (Vec string))
+(def words ["define" "display" "lambda" "let" "letrec" "vector-ref" "vector-set!"])
+
+;; Completes the word before the cursor from `words`.
+(: (-> string Completion))
+(defun (complete before)
+ (def chars (string->vec before))
+ (def start (let go ((i (vec-length chars)))
+ (if (and (> i 0) (not (string-contains? " ()" (char->string (vec-ref chars (- i 1))))))
+ (go (- i 1))
+ i)))
+ (def word (string-join (vec-map char->string (vec-slice chars start (- (vec-length chars) start))) ""))
+ (Completion (prefix word)
+ (candidates (vec-filter (fun (w) (string-starts-with? w word)) words))))
+
+;; Done when every open bracket is closed.
+(: (-> string bool))
+(defun (balanced? text)
+ (<= (loop (:for c (in-vec (string->vec text)))
+ (:acc d (summing (cond ((= c #\() 1) ((= c #\)) -1) (else 0)))))
+ 0))
+
+(defun (main args)
+ (def (Ok term) (terminal-open) :leave ((Err e) (println (terminal-error-message e)) 1))
+ (def ed (make-line-editor #:completer (Some complete) #:input-done? (Some balanced?)))
+ (def history (path-combine (match (getenv "HOME") ((Some h) h) (None ".")) ".bjoterm-repl-history"))
+ (ignore (line-history-load! ed history))
+ (let go ()
+ (match (line-read ed term (styled "λ> " [(StyleFg (Ansi 2)) StyleBold]) #:continuation (Some ".. "))
+ ((LineText text) (println (str "read: " (written text))) (go))
+ (LineCancelled (go))
+ (LineEof unit)))
+ (ignore (line-history-save ed history))
+ 0)
diff --git a/glue/Text.cs b/glue/Text.cs
new file mode 100644
index 0000000..52c4a2a
--- /dev/null
+++ b/glue/Text.cs
@@ -0,0 +1,208 @@
+/* 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/.
+ */
+
+// Text on a terminal: grapheme clusters and their widths in columns.
+
+using System.Globalization;
+using System.Text;
+
+namespace Bjoterm;
+
+///
+/// Grapheme clusters and display widths.
+///
+///
+///
+/// - Clusters are .NET's extended grapheme clusters (UAX #29). The
+/// line editor moves and deletes by cluster.
+/// - 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, 1 column.
+///
+///
+public static class Text {
+ /// The grapheme clusters of . CR LF is one.
+ public static string[] Clusters(string text) {
+ var result = new List();
+ var e = StringInfo.GetTextElementEnumerator(text);
+ while (e.MoveNext()) result.Add(e.GetTextElement());
+ return result.ToArray();
+ }
+
+ /// The clusters of a prompt: as , except that an
+ /// escape sequence (CSI, or OSC ended by BEL or ST) is one item, of
+ /// width 0.
+ public static string[] PromptClusters(string text) {
+ var result = new List();
+ int i = 0, plain = 0;
+ while (i < text.Length) {
+ int seq = EscapeLength(text, i);
+ if (seq == 0) {
+ i++;
+ continue;
+ }
+ if (i > plain) result.AddRange(Clusters(text[plain..i]));
+ result.Add(text.Substring(i, seq));
+ i += seq;
+ plain = i;
+ }
+ if (text.Length > plain) result.AddRange(Clusters(text[plain..]));
+ return result.ToArray();
+ }
+
+ /// The columns takes. 0 for an escape
+ /// sequence from .
+ public static int Width(string cluster) {
+ if (cluster.Length == 0) return 0;
+ if (cluster.Length > 1 && cluster[0] == '\x1b') return 0;
+ int first = char.ConvertToUtf32(cluster, 0);
+ if (first < 0x20 || first == 0x7f) return 2;
+ if (first >= 0x80 && first < 0xa0) return 1;
+ int width = RuneWidth(first);
+ if (width == 2) return 2;
+ // Emoji presentation, or a flag of two regional indicators.
+ if (cluster.Contains('️')) return 2;
+ if (first >= 0x1f1e6 && first <= 0x1f1ff && cluster.Length >= 4) return 2;
+ if (width == 0) {
+ // A cluster that starts with a mark: the widest of its parts.
+ int widest = 0;
+ foreach (var rune in cluster.EnumerateRunes()) widest = Math.Max(widest, RuneWidth(rune.Value));
+ return widest;
+ }
+ return width;
+ }
+
+ /// The columns of , escape sequences as 0.
+ public static int TextWidth(string text) {
+ int total = 0;
+ foreach (var cluster in PromptClusters(text)) total += Width(cluster);
+ return total;
+ }
+
+ /// What is written for : ^X for a C0
+ /// control or DEL, U+FFFD for a C1 control, else the cluster.
+ public static string Shown(string cluster) {
+ if (cluster.Length == 0) return cluster;
+ if (cluster.Length > 1 && cluster[0] == '\x1b') return cluster;
+ int first = cluster[0];
+ if (first < 0x20) return "^" + (char)(first + 0x40);
+ if (first == 0x7f) return "^?";
+ if (first >= 0x80 && first < 0xa0) return "�";
+ return cluster;
+ }
+
+ /// Whether is part of a word: it starts with
+ /// a letter, a digit or '_'.
+ public static bool IsWord(string cluster) {
+ if (cluster.Length == 0) return false;
+ var rune = Rune.GetRuneAt(cluster, 0);
+ return Rune.IsLetterOrDigit(rune) || rune.Value == '_';
+ }
+
+ /// The cluster index of the first occurrence of
+ /// in that starts and
+ /// ends on cluster boundaries, or -1. Ordinal; case matters.
+ public static int Find(string text, string query) {
+ var clusters = Clusters(text);
+ var starts = new int[clusters.Length + 1];
+ for (int i = 0; i < clusters.Length; i++) starts[i + 1] = starts[i] + clusters[i].Length;
+ int from = 0;
+ while (from <= text.Length) {
+ int at = text.IndexOf(query, from, StringComparison.Ordinal);
+ if (at < 0) return -1;
+ int index = Array.BinarySearch(starts, at);
+ if (index >= 0 && Array.BinarySearch(starts, at + query.Length) >= 0) return index;
+ from = at + 1;
+ }
+ return -1;
+ }
+
+ /// The longest common prefix of , whole
+ /// clusters only. Empty for no texts.
+ public static string CommonPrefix(string[] texts) {
+ if (texts.Length == 0) return "";
+ var first = Clusters(texts[0]);
+ int length = first.Length;
+ foreach (var text in texts.AsSpan(1)) {
+ var other = Clusters(text);
+ int same = 0;
+ while (same < length && same < other.Length && first[same] == other[same]) same++;
+ length = same;
+ }
+ return string.Concat(first.AsSpan(0, length));
+ }
+
+ /// The width of one code point, as wcwidth.
+ public static int RuneWidth(int c) {
+ if (c == 0) return 0;
+ if (c == 0x200b || (c >= 0x1160 && c <= 0x11ff)) return 0;
+ if (!Rune.IsValid(c)) return 1;
+ switch (Rune.GetUnicodeCategory(new Rune(c))) {
+ case UnicodeCategory.NonSpacingMark:
+ case UnicodeCategory.EnclosingMark:
+ case UnicodeCategory.Format:
+ return c == 0xad ? 1 : 0;
+ }
+ return IsWide(c) ? 2 : 1;
+ }
+
+ private static bool IsWide(int c) {
+ if (c < 0x1100) return false;
+ int lo = 0, hi = Wide.Length / 2 - 1;
+ while (lo <= hi) {
+ int mid = (lo + hi) / 2;
+ if (c < Wide[mid * 2]) hi = mid - 1;
+ else if (c > Wide[mid * 2 + 1]) lo = mid + 1;
+ else return true;
+ }
+ return false;
+ }
+
+ // Ranges of East Asian Wide and Fullwidth code points, and of emoji
+ // with emoji presentation by default (Unicode 15). Sorted, inclusive.
+ private static readonly int[] Wide = [
+ 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,
+ ];
+
+ // The length of an escape sequence at `i`, or 0.
+ private static int EscapeLength(string text, int i) {
+ if (text[i] != '\x1b' || i + 1 >= text.Length) return 0;
+ char kind = text[i + 1];
+ if (kind == '[') {
+ int j = i + 2;
+ while (j < text.Length && text[j] >= 0x20 && text[j] <= 0x3f) j++;
+ return j < text.Length && text[j] >= 0x40 && text[j] <= 0x7e ? j + 1 - i : 0;
+ }
+ if (kind == ']') {
+ for (int j = i + 2; j < text.Length; j++) {
+ if (text[j] == '\a') return j + 1 - i;
+ if (text[j] == '\x1b' && j + 1 < text.Length && text[j + 1] == '\\') return j + 2 - i;
+ }
+ return 0;
+ }
+ return 0;
+ }
+}
diff --git a/plan.org b/plan.org
index 6f1a091..7c517a0 100644
--- a/plan.org
+++ b/plan.org
@@ -23,6 +23,25 @@ is in raw mode, and gives it back as it found it.
- Under ~script~, a child that stops makes ~script~ stop itself; the test
of stop and continue sends SIGCONT to both.
+*Phase 2 implemented (2026-11-30): (bjoterm line).*
+- ~line-read~ returns ~(LineText text)~, ~LineEof~ or ~LineCancelled~.
+ Options of ~make-line-editor~: ~#:completer~, ~#:input-done?~,
+ ~#:history-size~; of ~line-read~: ~#:continuation~.
+- The keys are those of Emacs and readline, listed at ~line-read~. Up and
+ Down move between the lines of the input, and reach the history only
+ on its first and last line.
+- The buffer is a vector of grapheme clusters (glue/Text.cs). Widths
+ follow ~wcwidth~ with a table of wide ranges; a C0 control shows as
+ ~^X~, a tab as spaces to the next multiple of 8.
+- The editor breaks lines itself: a line break where the next cluster does
+ not fit, and after a line that ends at the edge. The whole input is
+ drawn again after each key, from the prompt's row.
+- Each key is a pure step from one state to the next (~line-step~), so
+ ~simulate-line~ tests the keys without a terminal.
+- History files have one entry per line, with "\n" and "\\" escaped.
+- Not done: an async ~line-read~ for a fiber (it is ~#:sync~), and
+ redrawing after a terminal reflows lines when it narrows.
+
* Decisions
1. *Linux only, for now.* The termios layout, ~TIOCGWINSZ~ and the flag
diff --git a/src/line.bjo b/src/line.bjo
new file mode 100644
index 0000000..74aea23
--- /dev/null
+++ b/src/line.bjo
@@ -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))))))
diff --git a/tests/line-terminal.bjo b/tests/line-terminal.bjo
new file mode 100644
index 0000000..b154a0e
--- /dev/null
+++ b/tests/line-terminal.bjo
@@ -0,0 +1,74 @@
+;; This Source Code Form is subject to the terms of the Mozilla Public
+;; License, v. 2.0. If a copy of the MPL was not distributed with this
+;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+;; `line-read` on a real terminal: what it returns, and what it leaves on
+;; the screen.
+;;
+;; bjo test tests/line-terminal.bjo
+;;
+;; The test runs itself again under `script`, and writes keys to it with
+;; pauses between them, as tests/terminal.bjo does.
+
+(import (std prelude))
+(import (std simpletest))
+(import (std run))
+(import (bjoterm terminal))
+(import (bjoterm line))
+
+(import/extern
+ (command-line (: System.Environment.GetCommandLineArgs (-> (Array string)) #:no-raise)))
+
+(: (-> string bool))
+(defun (balanced? text)
+ (<= (loop (:for c (in-vec (string->vec text)))
+ (:acc d (summing (cond ((= c #\() 1) ((= c #\)) -1) (else 0)))))
+ 0))
+
+(: (-> void))
+(defun (child)
+ (match (terminal-open)
+ ((Err e) (println (str "open: " (terminal-error-message e))))
+ ((Ok term)
+ (def ed (make-line-editor #:input-done? (Some balanced?)))
+ (let go ()
+ (match (line-read ed term "> ")
+ ((LineText text) (println (str "read: " (written text))) (go))
+ (LineCancelled (println "cancelled") (go))
+ (LineEof (println (str "eof, raw: " (if (terminal-raw? term) "yes" "no")))))))))
+
+(: (-> void))
+(defun (parent)
+ (def self (str "dotnet " (array-ref (command-line) 0)))
+ ;; Each step waits, so that the child reads each key on its own.
+ (def keys (string-join ["sleep 2" "printf 'one\\r'" "sleep 0.3"
+ "printf '(a'" "sleep 0.2" "printf '\\r'" "sleep 0.2" "printf 'b)\\r'" "sleep 0.3"
+ "printf 'gone'" "sleep 0.2" "printf '\\003'" "sleep 0.3"
+ "printf '\\020'" "sleep 0.2" "printf '\\020'" "sleep 0.2" "printf '!\\r'" "sleep 0.3"
+ "printf '\\004'" "sleep 1"]
+ "; "))
+ (def command (str "(" keys ") | script -qec 'stty cols 40 rows 20; " self " child' /dev/null"))
+ (def out (match (run/output '(sh "-c" ,command))
+ ((Ok (Tuple _ text)) (string-replace text "\r" ""))
+ ((Err e) (run-error-message e))))
+ (expect-true "the terminal opens" (not (string-contains? out "open:")))
+ (expect-true "a line" (string-contains? out "read: \"one\""))
+ (expect-true "Enter in open brackets starts a new line" (string-contains? out "read: \"(a\\nb)\""))
+ (expect-true "the continuation prompt is as wide as the prompt" (string-contains? out "\n b)"))
+ (expect-true "C-c cancels" (string-contains? out "cancelled"))
+ ;; The cursor goes to the end of the input with an escape sequence, so
+ ;; "gone" and "^C" are not next to each other in the output.
+ (expect-true "and leaves the input with ^C" (string-contains? out "^C\ncancelled"))
+ ;; C-p, not Up: Up in the two lines of the newer entry moves up a line.
+ (expect-true "C-p twice shows an older entry" (string-contains? out "read: \"one!\""))
+ (expect-true "C-d on an empty line is end of input, and raw mode is over"
+ (string-contains? out "eof, raw: no"))
+ (unless (string-contains? out "eof, raw: no")
+ (println out)))
+
+(defun (main args)
+ (cond
+ ((= args ["child"]) (child))
+ ((file-exists? "/usr/bin/script") (parent))
+ (else (println "skipped: no script command")))
+ 0)
diff --git a/tests/line.bjo b/tests/line.bjo
new file mode 100644
index 0000000..1950648
--- /dev/null
+++ b/tests/line.bjo
@@ -0,0 +1,219 @@
+;; 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/.
+
+;; The line editor's keys, history and completion, without a terminal.
+;;
+;; bjo test tests/line.bjo
+
+(import (std prelude))
+(import (std simpletest))
+(import (bjoterm terminal))
+(import (bjoterm line))
+
+(import/extern (temp-dir (: System.IO.Path.GetTempPath (-> string))))
+
+;; ---- events ----------------------------------------------------------------
+
+(: (-> string (Vec TermEvent)))
+(defun (typed s)
+ (vec-map (fun (c) (TermKey (KeyChar c) no-mods)) (string->vec s)))
+
+(: (-> 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))))
+
+(: (-> Key TermEvent))
+(defun (key k)
+ (TermKey k no-mods))
+
+(: TermEvent)
+(def enter (key KeyEnter))
+
+;; The events, one after the other.
+(: (-> (Vec (Vec TermEvent)) (Vec TermEvent)))
+(defun (keys parts)
+ (let go ((i 0) (out []))
+ (if (= i (vec-length parts))
+ out
+ (go (+ i 1) (vec-append out (vec-ref parts i))))))
+
+;; ---- running the editor ----------------------------------------------------
+
+(: (-> (Option LineResult) string))
+(defun (result-text r)
+ (match r
+ ((Some (LineText text)) (str "text " (written text)))
+ ((Some LineEof) "eof")
+ ((Some LineCancelled) "cancelled")
+ (None "not finished")))
+
+;; The result, or the buffer when the events end first.
+(: (-> LineEditor (Vec TermEvent) string))
+(defun (run-on ed events)
+ (match (simulate-line ed events)
+ ((Tuple None buffer) (str "buffer " (written buffer)))
+ ((Tuple r _) (result-text r))))
+
+(: (-> (Vec TermEvent) string))
+(defun (run-fresh events)
+ (run-on (make-line-editor) events))
+
+(: (-> string (Vec (Vec TermEvent)) string void))
+(defun (expect-line name parts wanted)
+ (expect name (run-fresh (keys parts)) wanted))
+
+;; Open brackets make the input incomplete, as in a Lisp REPL.
+(: (-> string bool))
+(defun (balanced? text)
+ (def depth (loop (:for c (in-vec (string->vec text)))
+ (:acc d (summing (cond ((= c #\() 1) ((= c #\)) -1) (else 0))))))
+ (<= depth 0))
+
+(: (Vec string))
+(def words ["vec-map" "vec-add" "vector" "display"])
+
+;; Completes the last word from `words`.
+(: (-> string Completion))
+(defun (complete-word before)
+ (def parts (string-split before " "))
+ (def word (if (vec-empty? parts) "" (vec-ref parts (- (vec-length parts) 1))))
+ (Completion (prefix word)
+ (candidates (vec-map (fun (w) (str w " "))
+ (vec-filter (fun (w) (string-starts-with? w word)) words)))))
+
+(defun (main args)
+ ;; Typing and accepting.
+ (expect-line "typing and Enter" [(typed "hello") [enter]] "text \"hello\"")
+ (expect-line "the events end first" [(typed "hel")] "buffer \"hel\"")
+ (expect-line "C-d on an empty buffer" [[(ctrl #\d)]] "eof")
+ (expect-line "C-d deletes under the cursor" [(typed "ab") [(ctrl #\a) (ctrl #\d)] [enter]] "text \"b\"")
+ (expect-line "C-c cancels" [(typed "abc") [(ctrl #\c)]] "cancelled")
+ (expect-line "the terminal hangs up" [(typed "abc") [TermEnd]] "eof")
+ (expect-line "a paste is inserted" [(typed "a") [(TermPaste "x\ny")] (typed "b") [enter]] "text \"ax\\nyb\"")
+
+ ;; Moving.
+ (expect-line "Left and insert" [(typed "helo") [(key KeyLeft)] (typed "l") [enter]] "text \"hello\"")
+ (expect-line "C-a and C-e" [(typed "bc") [(ctrl #\a)] (typed "a") [(ctrl #\e)] (typed "d") [enter]]
+ "text \"abcd\"")
+ (expect-line "M-b and M-f" [(typed "one two") [(alt #\b) (alt #\b) (alt #\f)] (typed "!") [enter]]
+ "text \"one! two\"")
+ (expect-line "C-Left by word"
+ [(typed "one two") [(TermKey KeyLeft (Mods (shift? #f) (alt? #f) (ctrl? #t)))] (typed "_") [enter]]
+ "text \"one _two\"")
+
+ ;; Deleting and the kill buffer.
+ (expect-line "Backspace" [(typed "abc") [(key KeyBackspace)] [enter]] "text \"ab\"")
+ (expect-line "Delete" [(typed "abc") [(ctrl #\a) (key KeyDelete)] [enter]] "text \"bc\"")
+ (expect-line "C-k and C-y" [(typed "abcd") [(ctrl #\a) (ctrl #\f) (ctrl #\k)] [(ctrl #\a) (ctrl #\y)] [enter]]
+ "text \"bcda\"")
+ (expect-line "C-u kills to the start" [(typed "abcd") [(ctrl #\b) (ctrl #\u)] [enter]] "text \"d\"")
+ (expect-line "C-w kills a word" [(typed "foo bar") [(ctrl #\w)] [enter]] "text \"foo \"")
+ (expect-line "kills one after another add up" [(typed "a b c") [(ctrl #\w) (ctrl #\w) (ctrl #\y)] [enter]]
+ "text \"a b c\"")
+ ;; The second C-w takes only "b": the cursor is before the space.
+ (expect-line "a key between kills starts a new kill"
+ [(typed "a b c") [(ctrl #\w) (key KeyLeft) (ctrl #\w) (ctrl #\e) (ctrl #\y)] [enter]]
+ "text \"a b\"")
+ (expect-line "M-d kills the next word" [(typed "one two") [(ctrl #\a) (alt #\d)] [enter]] "text \" two\"")
+ (expect-line "C-t swaps at the end" [(typed "ab") [(ctrl #\t)] [enter]] "text \"ba\"")
+ (expect-line "C-t swaps in the middle" [(typed "abc") [(ctrl #\a) (ctrl #\f) (ctrl #\t)] [enter]]
+ "text \"bac\"")
+
+ ;; Grapheme clusters.
+ (expect-line "a combining mark joins the letter before it"
+ [(typed "e") [(TermKey (KeyChar (int->char 769)) no-mods) (key KeyBackspace)] [enter]]
+ "text \"\"")
+ (expect-line "an emoji with a modifier is one cluster"
+ [[(TermPaste "a👍🏽b")] [(key KeyLeft) (key KeyLeft) (key KeyBackspace)] [enter]]
+ "text \"👍🏽b\"")
+
+ ;; Several lines.
+ (expect-line "M-Enter starts a new line" [(typed "a") [(TermKey KeyEnter (Mods (shift? #f) (alt? #t) (ctrl? #f)))]
+ (typed "b") [enter]]
+ "text \"a\\nb\"")
+ (expect-line "C-j starts a new line" [(typed "a") [(ctrl #\j)] (typed "b") [enter]] "text \"a\\nb\"")
+ (expect "Enter in incomplete input starts a new line"
+ (run-on (make-line-editor #:input-done? (Some balanced?))
+ (keys [(typed "(+ 1") [enter] (typed "2)") [enter]]))
+ "text \"(+ 1\\n2)\"")
+ (expect-line "Up moves to the line above, at the same column"
+ [(typed "abc") [(ctrl #\j)] (typed "de") [(key KeyUp)] (typed "X") [enter]]
+ "text \"abXc\\nde\"")
+ (expect-line "Down moves to the line below, as far as it reaches"
+ [(typed "abcdef") [(ctrl #\j)] (typed "x") [(key KeyUp) (ctrl #\e) (key KeyDown)] (typed "Y") [enter]]
+ "text \"abcdef\\nxY\"")
+ (expect-line "C-a goes to the start of the line" [(typed "ab") [(ctrl #\j)] (typed "cd") [(ctrl #\a)] (typed "X") [enter]]
+ "text \"ab\\nXcd\"")
+ (expect-line "C-k at the end of a line joins the next"
+ [(typed "ab") [(ctrl #\j)] (typed "cd") [(key KeyUp) (ctrl #\e) (ctrl #\k)] [enter]]
+ "text \"abcd\"")
+
+ ;; History.
+ (def ed (make-line-editor #:history-size 3))
+ (ignore (run-on ed (keys [(typed "one") [enter]])))
+ (ignore (run-on ed (keys [(typed "two") [enter]])))
+ (ignore (run-on ed (keys [(typed "two") [enter]])))
+ (ignore (run-on ed (keys [[enter]])))
+ (expect "accepted lines go to the history, not repeats or empty ones" (line-history ed) ["one" "two"])
+ (expect "Up shows the last entry" (run-on ed (keys [[(key KeyUp)] [enter]])) "text \"two\"")
+ (expect "Up twice, and Down" (run-on ed (keys [[(key KeyUp) (key KeyUp) (key KeyUp) (key KeyDown)] [enter]]))
+ "text \"two\"")
+ (expect "Down past the newest shows the draft"
+ (run-on ed (keys [(typed "draft") [(ctrl #\p) (ctrl #\p) (ctrl #\n) (ctrl #\n) (ctrl #\n)]]))
+ "buffer \"draft\"")
+ (line-history-add! ed "three")
+ (line-history-add! ed "four")
+ (expect "the oldest entry goes above the size" (line-history ed) ["two" "three" "four"])
+
+ ;; Search.
+ (def searched (make-line-editor))
+ (loop (:for e (in-vec ["make build" "make test" "git status" "make install"]))
+ (:do (line-history-add! searched e)))
+ (expect "C-r finds the newest match" (run-on searched (keys [[(ctrl #\r)] (typed "make") [enter]]))
+ "text \"make install\"")
+ (expect "C-r again finds an older one" (run-on searched (keys [[(ctrl #\r)] (typed "make") [(ctrl #\r)] [enter]]))
+ "text \"make test\"")
+ (expect "a longer query narrows the match" (run-on searched (keys [[(ctrl #\r)] (typed "make b") [enter]]))
+ "text \"make build\"")
+ (expect "C-g ends the search and restores the input"
+ (run-on searched (keys [(typed "x") [(ctrl #\r)] (typed "git") [(ctrl #\g)]]))
+ "buffer \"x\"")
+ (expect "another key keeps the match and does what it does"
+ (run-on searched (keys [[(ctrl #\r)] (typed "status") [(ctrl #\e)] (typed "!") [enter]]))
+ "text \"git status!\"")
+ ;; The test before added "git status!" to the history.
+ (expect "no match keeps the last one"
+ (run-on searched (keys [[(ctrl #\r)] (typed "gitx") [(key KeyRight)]]))
+ "buffer \"git status!\"")
+
+ ;; Completion.
+ (def completing (make-line-editor #:completer (Some complete-word)))
+ (expect "Tab inserts the common prefix" (run-on completing (keys [(typed "x ve") [(key KeyTab)]]))
+ "buffer \"x vec\"")
+ (expect "one candidate is inserted whole" (run-on completing (keys [(typed "x vec-m") [(key KeyTab)]]))
+ "buffer \"x vec-map \"")
+ (expect "no candidate changes nothing" (run-on completing (keys [(typed "zz") [(key KeyTab) (key KeyTab)]]))
+ "buffer \"zz\"")
+ (expect "Tab without a completer inserts a tab" (run-fresh (keys [(typed "a") [(key KeyTab)] [enter]]))
+ "text \"a\\t\"")
+
+ ;; The history file.
+ (def path (path-combine (temp-dir) "bjoterm-history-test.txt"))
+ (def saved (make-line-editor))
+ (line-history-add! saved "plain")
+ (line-history-add! saved "two\nlines")
+ (line-history-add! saved "a \\ backslash and \\n")
+ (expect "the history is saved" (line-history-save saved path) (Ok unit))
+ (def loaded (make-line-editor))
+ (expect "and loaded" (line-history-load! loaded path) (Ok unit))
+ (expect "with lines and backslashes as they were" (line-history loaded) (line-history saved))
+ (ignore (file-delete path))
+ (expect "a history file that does not exist is empty"
+ (line-history-load! (make-line-editor) (path-combine (temp-dir) "bjoterm-no-such-history.txt"))
+ (Ok unit))
+ (println "line ok"))