diff --git a/AGENTS.md b/AGENTS.md
index 4918a69..bd1af77 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -21,11 +21,19 @@ Examples:
## This package
- `bjo build` builds the library and the glue in `glue/`.
+- Keep logic in Bjolang. The glue is for what Bjolang cannot call: termios,
+ signals and `poll`/`read`. For Unicode, use `(std unicode ...)`.
+- Modules: `(bjoterm keys)` decodes input, `(bjoterm text)` measures text,
+ `(bjoterm terminal)` reads events and has the escape sequences,
+ `(bjoterm line)` is the line editor.
- `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`.
+ - `tests/text.bjo`: clusters and widths.
+ - `tests/async.bjo`: `line-read` in a bjoroutine, and cancelled by a
+ deadline.
- `examples/keys.bjo` prints events; `examples/repl.bjo` is a small REPL.
- `plan.org` has the decisions and the phases.
diff --git a/glue/Keys.cs b/glue/Keys.cs
deleted file mode 100644
index f5b8a71..0000000
--- a/glue/Keys.cs
+++ /dev/null
@@ -1,301 +0,0 @@
-/* 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 decoder of terminal input: bytes in, events out.
-
-using System.Text;
-
-namespace Bjoterm;
-
-///
-/// One event read from the terminal, as flat fields. (bjoterm terminal)
-/// maps it to its union.
-///
-public sealed class TermEvent {
- public const int TimeoutKind = 0, KeyKind = 1, PasteKind = 2, ResizedKind = 3, EndKind = 4;
-
- // The keys. Char carries the code point in Value, F the number in Value.
- public const int Char = 0, Enter = 1, Tab = 2, Backspace = 3, Escape = 4,
- Up = 5, Down = 6, Left = 7, Right = 8, Home = 9, End_ = 10,
- PageUp = 11, PageDown = 12, Insert = 13, Delete = 14, F = 15, Unknown = 16;
-
- public const int Shift = 1, Alt = 2, Ctrl = 4;
-
- internal static readonly TermEvent TimedOut = new(TimeoutKind, 0, 0, 0, 0, "");
- internal static readonly TermEvent End = new(EndKind, 0, 0, 0, 0, "");
-
- private TermEvent(int kind, int key, int value, int value2, int mods, string text) {
- Kind = kind;
- Key = key;
- Value = value;
- Value2 = value2;
- Mods = mods;
- Text = text;
- }
-
- internal static TermEvent KeyOf(int key, int mods, int value = 0) => new(KeyKind, key, value, 0, mods, "");
-
- internal static TermEvent UnknownOf(string text) => new(KeyKind, Unknown, 0, 0, 0, text);
-
- internal static TermEvent Paste(string text) => new(PasteKind, 0, 0, 0, 0, text);
-
- internal static TermEvent Resized(int cols, int rows) => new(ResizedKind, 0, cols, rows, 0, "");
-
- public int Kind { get; }
-
- public int Key { get; }
-
- /// The code point of a key, the number of an
- /// key, or the columns of a resize.
- public int Value { get; }
-
- /// The rows of a resize.
- public int Value2 { get; }
-
- /// , and .
- public int Mods { get; }
-
- /// The text of a paste, or the bytes of an unknown sequence (ESC as
- /// "^[").
- public string Text { get; }
-}
-
-///
-/// Decodes terminal input into events.
-///
-///
-///
-/// - adds bytes; returns the next
-/// complete event, or null when the bytes so far are a partial one.
-/// - Next(final: true) decodes a partial event as it is: a lone
-/// ESC is the Escape key, ESC and one key is Alt and that key, a cut UTF-8
-/// character is U+FFFD, and a cut sequence is .
-/// The reader calls it when no more bytes came within the sequence
-/// timeout.
-/// - Keys: CSI and SS3 sequences of xterm, with the modifier parameter
-/// (ESC [ 1 ; 5 A is Ctrl-Up), the ~ keys, F1 to F12, and
-/// Shift-Tab (ESC [ Z).
-/// - Bracketed paste: the bytes between ESC [ 200 ~ and
-/// ESC [ 201 ~ are one paste, decoded as UTF-8 with CR LF and CR
-/// made LF. A paste is not cut by the timeout.
-///
-///
-public sealed class Decoder {
- private static readonly byte[] PasteEnd = "\x1b[201~"u8.ToArray();
-
- private byte[] buffer = new byte[256];
- private int start, end;
- private bool inPaste;
-
- public bool HasPartial => end > start;
-
- public bool InPaste => inPaste;
-
- public void Reset() {
- start = end = 0;
- inPaste = false;
- }
-
- public void Feed(byte[] data, int count) {
- if (start > 0 && end == start) start = end = 0;
- if (end + count > buffer.Length) {
- int live = end - start;
- var grown = live + count > buffer.Length ? new byte[Math.Max(buffer.Length * 2, live + count)] : buffer;
- Array.Copy(buffer, start, grown, 0, live);
- buffer = grown;
- start = 0;
- end = live;
- }
- Array.Copy(data, 0, buffer, end, count);
- end += count;
- }
-
- /// Decodes all of as input that ends there: a
- /// partial event at the end is decoded as it is.
- public static TermEvent[] DecodeAll(byte[] data) {
- var decoder = new Decoder();
- decoder.Feed(data, data.Length);
- var events = new List();
- while (decoder.Next(final: false) is { } ev) events.Add(ev);
- while (decoder.Next(final: true) is { } last) events.Add(last);
- return events.ToArray();
- }
-
- public TermEvent? Next(bool final) {
- if (inPaste) return NextPaste();
- if (end == start) return null;
- var (ev, used) = Decode(start, final);
- if (ev is null) return null;
- start += used;
- if (ev == PasteStart) {
- inPaste = true;
- return NextPaste();
- }
- return ev;
- }
-
- // A marker for ESC [ 200 ~; never returned.
- private static readonly TermEvent PasteStart = TermEvent.UnknownOf("paste");
-
- private TermEvent? NextPaste() {
- var span = buffer.AsSpan(start, end - start);
- int at = span.IndexOf(PasteEnd);
- if (at < 0) return null;
- string text = Encoding.UTF8.GetString(span[..at]).Replace("\r\n", "\n").Replace('\r', '\n');
- start += at + PasteEnd.Length;
- inPaste = false;
- return TermEvent.Paste(text);
- }
-
- // Decodes one event at `at`. Returns (null, 0) when more bytes are
- // needed and `final` is false.
- private (TermEvent?, int) Decode(int at, bool final) {
- int avail = end - at;
- byte b = buffer[at];
- if (b == 0x1b) {
- if (avail == 1) return final ? (TermEvent.KeyOf(TermEvent.Escape, 0), 1) : (null, 0);
- byte next = buffer[at + 1];
- if (next == (byte)'[') return Csi(at, final);
- if (next == (byte)'O') return Ss3(at, final);
- // ESC and a key is Alt and that key.
- var (key, used) = Decode(at + 1, final);
- if (key is null) return (null, 0);
- if (key.Kind != TermEvent.KeyKind || key.Key == TermEvent.Unknown) {
- return (TermEvent.UnknownOf(Shown(at, 1 + used)), 1 + used);
- }
- return (TermEvent.KeyOf(key.Key, key.Mods | TermEvent.Alt, key.Value), 1 + used);
- }
- if (b < 0x80) return (Ascii(b), 1);
- return Utf8(at, final);
- }
-
- private static TermEvent Ascii(byte b) => b switch {
- 0x0d => TermEvent.KeyOf(TermEvent.Enter, 0),
- 0x09 => TermEvent.KeyOf(TermEvent.Tab, 0),
- 0x7f => TermEvent.KeyOf(TermEvent.Backspace, 0),
- 0x08 => TermEvent.KeyOf(TermEvent.Backspace, TermEvent.Ctrl),
- 0x00 => TermEvent.KeyOf(TermEvent.Char, TermEvent.Ctrl, ' '),
- < 0x1b => TermEvent.KeyOf(TermEvent.Char, TermEvent.Ctrl, 0x60 + b),
- < 0x20 => TermEvent.KeyOf(TermEvent.Char, TermEvent.Ctrl, 0x40 + b),
- _ => TermEvent.KeyOf(TermEvent.Char, 0, b),
- };
-
- private (TermEvent?, int) Utf8(int at, bool final) {
- byte b = buffer[at];
- int length = b >= 0xf0 && b < 0xf8 ? 4 : b >= 0xe0 ? 3 : b >= 0xc2 && b < 0xe0 ? 2 : 0;
- if (length == 0) return (TermEvent.KeyOf(TermEvent.Char, 0, 0xfffd), 1);
- int have = 1;
- while (have < length && at + have < end && (buffer[at + have] & 0xc0) == 0x80) have++;
- if (have < length) {
- // Cut: wait for the rest, unless a byte that cannot continue it
- // came, or no more will come.
- if (at + have == end && !final) return (null, 0);
- return (TermEvent.KeyOf(TermEvent.Char, 0, 0xfffd), have);
- }
- var status = System.Text.Rune.DecodeFromUtf8(buffer.AsSpan(at, length), out var rune, out _);
- int value = status == System.Buffers.OperationStatus.Done ? rune.Value : 0xfffd;
- return (TermEvent.KeyOf(TermEvent.Char, 0, value), length);
- }
-
- // ESC [ parameters intermediates final.
- private (TermEvent?, int) Csi(int at, bool final) {
- int i = at + 2;
- while (i < end && buffer[i] >= 0x30 && buffer[i] <= 0x3f) i++;
- while (i < end && buffer[i] >= 0x20 && buffer[i] <= 0x2f) i++;
- if (i == end) {
- if (!final) return (null, 0);
- // ESC [ alone is Alt-[.
- if (end - at == 2) return (TermEvent.KeyOf(TermEvent.Char, TermEvent.Alt, '['), 2);
- return (TermEvent.UnknownOf(Shown(at, end - at)), end - at);
- }
- byte last = buffer[i];
- int used = i + 1 - at;
- if (last < 0x40 || last > 0x7e) return (TermEvent.UnknownOf(Shown(at, used)), used);
-
- var parameters = Encoding.ASCII.GetString(buffer, at + 2, i - at - 2).Split(';');
- int first = Number(parameters, 0, 1);
- int mods = Modifiers(Number(parameters, 1, 1));
- int key = last switch {
- (byte)'A' => TermEvent.Up,
- (byte)'B' => TermEvent.Down,
- (byte)'C' => TermEvent.Right,
- (byte)'D' => TermEvent.Left,
- (byte)'H' => TermEvent.Home,
- (byte)'F' => TermEvent.End_,
- (byte)'P' or (byte)'Q' or (byte)'R' or (byte)'S' => TermEvent.F,
- (byte)'Z' => TermEvent.Tab,
- (byte)'~' => Tilde(first),
- _ => TermEvent.Unknown,
- };
- if (last == (byte)'~' && first == 200) return (PasteStart, used);
- if (key == TermEvent.Unknown) return (TermEvent.UnknownOf(Shown(at, used)), used);
- if (last == (byte)'Z') return (TermEvent.KeyOf(TermEvent.Tab, TermEvent.Shift), used);
- int number = key != TermEvent.F ? 0 : last == (byte)'~' ? FunctionNumber(first) : last - (byte)'P' + 1;
- return (TermEvent.KeyOf(key, mods, number), used);
- }
-
- // ESC O key: the keys of application cursor mode, and F1 to F4.
- private (TermEvent?, int) Ss3(int at, bool final) {
- if (end - at < 3) {
- if (!final) return (null, 0);
- return (TermEvent.KeyOf(TermEvent.Char, TermEvent.Alt, 'O'), 2);
- }
- byte k = buffer[at + 2];
- var ev = k switch {
- (byte)'A' => TermEvent.KeyOf(TermEvent.Up, 0),
- (byte)'B' => TermEvent.KeyOf(TermEvent.Down, 0),
- (byte)'C' => TermEvent.KeyOf(TermEvent.Right, 0),
- (byte)'D' => TermEvent.KeyOf(TermEvent.Left, 0),
- (byte)'H' => TermEvent.KeyOf(TermEvent.Home, 0),
- (byte)'F' => TermEvent.KeyOf(TermEvent.End_, 0),
- (byte)'M' => TermEvent.KeyOf(TermEvent.Enter, 0),
- >= (byte)'P' and <= (byte)'S' => TermEvent.KeyOf(TermEvent.F, 0, k - 'P' + 1),
- _ => TermEvent.UnknownOf(Shown(at, 3)),
- };
- return (ev, 3);
- }
-
- private static int Tilde(int n) => n switch {
- 1 or 7 => TermEvent.Home,
- 2 => TermEvent.Insert,
- 3 => TermEvent.Delete,
- 4 or 8 => TermEvent.End_,
- 5 => TermEvent.PageUp,
- 6 => TermEvent.PageDown,
- >= 11 and <= 15 or >= 17 and <= 21 or 23 or 24 => TermEvent.F,
- _ => TermEvent.Unknown,
- };
-
- private static int FunctionNumber(int n) => n switch {
- <= 15 => n - 10,
- <= 21 => n - 11,
- _ => n - 12,
- };
-
- // xterm's modifier parameter is 1 plus the bits shift 1, alt 2, ctrl 4,
- // meta 8. Meta is reported as Alt.
- private static int Modifiers(int parameter) {
- int bits = Math.Max(0, parameter - 1);
- int mods = 0;
- if ((bits & 1) != 0) mods |= TermEvent.Shift;
- if ((bits & 2) != 0 || (bits & 8) != 0) mods |= TermEvent.Alt;
- if ((bits & 4) != 0) mods |= TermEvent.Ctrl;
- return mods;
- }
-
- private static int Number(string[] parameters, int index, int missing) =>
- index < parameters.Length && int.TryParse(parameters[index], out int n) ? n : missing;
-
- private string Shown(int at, int count) {
- var text = new StringBuilder();
- for (int i = at; i < at + count; i++) {
- byte b = buffer[i];
- if (b == 0x1b) text.Append("^[");
- else if (b < 0x20 || b >= 0x7f) text.Append($"\\x{b:x2}");
- else text.Append((char)b);
- }
- return text.ToString();
- }
-}
diff --git a/glue/Text.cs b/glue/Text.cs
deleted file mode 100644
index 52c4a2a..0000000
--- a/glue/Text.cs
+++ /dev/null
@@ -1,208 +0,0 @@
-/* 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/glue/Tty.cs b/glue/Tty.cs
index 784b532..2f507ad 100644
--- a/glue/Tty.cs
+++ b/glue/Tty.cs
@@ -4,7 +4,8 @@
*/
// The terminal on fd 0 and fd 1: raw mode, the size, signals, and reading
-// events. (bjoterm terminal) is the Bjolang side.
+// bytes. (bjoterm terminal) is the Bjolang side: it decodes the bytes, and
+// waits for the rest of a sequence.
using System.ComponentModel;
using System.Runtime.InteropServices;
@@ -23,18 +24,17 @@ namespace Bjoterm;
/// mode; restores the saved modes. They are also
/// restored at process exit.
/// - Signals, registered at the first open:
-/// - SIGWINCH: the next read returns a resize.
-/// - SIGCONT in raw mode: raw mode is set again, the next read returns a
-/// resize, and .NET's own handling (which sets .NET's modes) is
-/// cancelled.
+/// - SIGWINCH: returns true once, and a read
+/// that waits returns .
+/// - SIGCONT in raw mode: raw mode is set again, it counts as a resize,
+/// and .NET's own handling (which sets .NET's modes) is cancelled.
/// - SIGTSTP in raw mode (only with ISIG on): the saved modes are restored
/// and the process stops with SIGSTOP. SIGCONT then sets raw mode
/// again.
/// - SIGTERM, SIGHUP and SIGQUIT in raw mode: the saved modes are
/// restored, and the signal is not cancelled. A program that cancels one of
/// them to go on running is in cooked mode after it.
-/// - One read at a time. A second concurrent
-/// raises .
+/// - Reads run one at a time.
///
///
[SupportedOSPlatform("linux")]
@@ -53,8 +53,11 @@ public sealed unsafe class Tty {
private const int EINTR = 4, EAGAIN = 11;
private const int SIGTSTP = 20, SIGSTOP = 19;
- /// The time to wait for the rest of a sequence after its first bytes.
- public const int SequenceTimeoutMs = 50;
+ /// What returns at end of input.
+ public const int EndOfInput = -1;
+
+ /// What returns after a resize.
+ public const int Resized = -2;
private static readonly object openGate = new();
private static Tty? opened;
@@ -62,7 +65,6 @@ public sealed unsafe class Tty {
private readonly object gate = new();
private readonly byte[] saved = new byte[TermiosSize];
private readonly byte[] raw = new byte[TermiosSize];
- private readonly Decoder decoder = new();
private readonly List registrations = new();
private readonly int wakeRead, wakeWrite;
// Inside EnterRaw ... LeaveRaw.
@@ -70,7 +72,7 @@ public sealed unsafe class Tty {
// The raw modes are set on the terminal now.
private bool rawSet;
private int resized;
- private int reading;
+ private readonly object readGate = new();
private Tty(int wakeRead, int wakeWrite) {
this.wakeRead = wakeRead;
@@ -135,7 +137,6 @@ public sealed unsafe class Tty {
raw[CcOffset + VTIME] = 0;
ApplyRaw();
rawWanted = true;
- decoder.Reset();
}
}
@@ -164,56 +165,40 @@ public sealed unsafe class Tty {
}
}
- /// Reads the next event.
+ /// Whether the terminal was resized, or the process continued, since
+ /// the last call.
+ public bool TakeResized() => Interlocked.Exchange(ref resized, 0) != 0;
+
+ /// Reads bytes into .
///
- /// - below 0 waits for ever. A timeout
- /// returns an event of kind .
- /// - The rest of a sequence is waited for
- /// ; then what came is decoded alone (a
- /// lone ESC is the Escape key).
+ /// - Returns the count read; 0 after
+ /// (below 0 waits for ever); ; or
+ /// when a resize came first.
/// - Cancelling the token raises
- /// . Bytes read before that stay
- /// for the next read.
+ /// . Nothing has been read
+ /// then.
+ /// - Reads run one at a time: a read waits for the one before it.
+ /// A cancelled read ends soon after, as its wait is woken.
///
- public Task ReadAsync(int timeoutMs, CancellationToken cancel) {
- if (Interlocked.Exchange(ref reading, 1) != 0) {
- throw new InvalidOperationException("Another read of the terminal is in progress.");
- }
+ public Task ReadAsync(byte[] buffer, int timeoutMs, CancellationToken cancel) {
// poll blocks the thread, so the read runs on a thread of its own.
return Task.Factory.StartNew(() => {
- try {
+ lock (readGate) {
using var wake = cancel.Register(Wake);
- return Read(timeoutMs, cancel);
- } finally {
- Volatile.Write(ref reading, 0);
+ return Read(buffer, timeoutMs, cancel);
}
- // Not the caller's token: a task cancelled before it starts would
- // never clear `reading`.
+ // Not the caller's token: the task always runs, and raises from
+ // Read when the token is cancelled.
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
- private TermEvent Read(int timeoutMs, CancellationToken cancel) {
+ private int Read(byte[] buffer, int timeoutMs, CancellationToken cancel) {
long deadline = timeoutMs < 0 ? long.MaxValue : Environment.TickCount64 + timeoutMs;
- var buffer = new byte[4096];
pollfd* fds = stackalloc pollfd[2];
while (true) {
- if (Interlocked.Exchange(ref resized, 0) != 0) {
- var size = Size();
- return TermEvent.Resized(size[0], size[1]);
- }
- var ready = decoder.Next(final: false);
- if (ready is not null) return ready;
cancel.ThrowIfCancellationRequested();
-
- int wait;
- if (decoder.HasPartial && !decoder.InPaste) {
- wait = SequenceTimeoutMs;
- } else if (deadline == long.MaxValue) {
- wait = -1;
- } else {
- wait = (int)Math.Max(0, deadline - Environment.TickCount64);
- }
-
+ if (Volatile.Read(ref resized) != 0) return Resized;
+ int wait = deadline == long.MaxValue ? -1 : (int)Math.Max(0, deadline - Environment.TickCount64);
fds[0] = new pollfd { fd = 0, events = POLLIN };
fds[1] = new pollfd { fd = wakeRead, events = POLLIN };
int n = poll(fds, 2, wait);
@@ -221,31 +206,22 @@ public sealed unsafe class Tty {
if (Marshal.GetLastPInvokeError() == EINTR) continue;
throw LastError();
}
- if ((fds[1].revents & POLLIN) != 0) DrainWake();
+ if ((fds[1].revents & POLLIN) != 0) {
+ DrainWake();
+ continue;
+ }
if ((fds[0].revents & (POLLIN | POLLHUP | POLLERR)) != 0) {
long got;
fixed (byte* b = buffer) {
got = read(0, b, buffer.Length);
}
- if (got < 0) {
- int errno = Marshal.GetLastPInvokeError();
- if (errno == EINTR || errno == EAGAIN) continue;
- throw LastError(errno);
- }
- if (got == 0) {
- return decoder.Next(final: true) ?? TermEvent.End;
- }
- decoder.Feed(buffer, (int)got);
- continue;
- }
- if (n == 0) {
- if (decoder.HasPartial && !decoder.InPaste) {
- var last = decoder.Next(final: true);
- if (last is not null) return last;
- continue;
- }
- if (Environment.TickCount64 >= deadline) return TermEvent.TimedOut;
+ if (got > 0) return (int)got;
+ if (got == 0) return EndOfInput;
+ int errno = Marshal.GetLastPInvokeError();
+ if (errno == EINTR || errno == EAGAIN) continue;
+ throw LastError(errno);
}
+ if (n == 0) return 0;
}
}
diff --git a/plan.org b/plan.org
index 7c517a0..dac4acf 100644
--- a/plan.org
+++ b/plan.org
@@ -30,7 +30,7 @@ is in raw mode, and gives it back as it found it.
- 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
+- The buffer is a vector of grapheme clusters ((std unicode grapheme)). 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
@@ -39,8 +39,26 @@ is in raw mode, and gives it back as it found it.
- 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.
+- Not done: redrawing after a terminal reflows lines when it narrows.
+
+*Async, and less C# (2026-11-30).*
+- ~read-event~ and everything above it work in both colours. The one leaf
+ is ~read-bytes~, a ~defbjouble~: in a bjoroutine it awaits the glue's
+ read, elsewhere it parks the thread on a fiber of the caller's scope.
+ The compiler makes the suspending copies of ~read-event~, ~line-read~
+ and the editor loop. ~with-raw-mode~ takes a body of either colour
+ (~-?->~), and ~line-read~ passes it a bjoroutine in its suspending copy.
+- Cancelling the scope around a waiting ~line-read~ ends it, and the
+ modes come back.
+- Moved to Bjolang: the decoder (~(bjoterm keys)~), the wait for the rest
+ of a sequence, the widths and prompt escapes (~(bjoterm text)~), search
+ and common prefixes. Clusters and the Unicode categories come from
+ ~(std unicode grapheme)~ and ~(std unicode chars)~; only the East Asian
+ wide ranges are a table of our own. The glue is termios, the signals,
+ and ~poll~ and ~read~ of bytes.
+- Reads of the glue run one at a time: a read waits for the one before
+ it, which ends soon after it is cancelled.
+- Decision 11 (a C# decoder) is replaced by this.
* Decisions
diff --git a/src/keys.bjo b/src/keys.bjo
new file mode 100644
index 0000000..63273cf
--- /dev/null
+++ b/src/keys.bjo
@@ -0,0 +1,430 @@
+;; This Source Code Form is subject to the terms of the Mozilla Public
+;; License, v. 2.0. If a copy of the MPL was not distributed with this
+;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+;; (bjoterm keys): terminal input as events. Bytes in, keys, pastes and
+;; resizes out.
+;;
+;; - Keys: CSI and SS3 sequences of xterm with the modifier parameter
+;; ("ESC [ 1 ; 5 A" is Ctrl-Up), the "~" keys, F1 to F12, Shift-Tab
+;; ("ESC [ Z"), ESC before a key as Alt, and UTF-8.
+;; - Bracketed paste: the bytes between "ESC [ 200 ~" and "ESC [ 201 ~" are
+;; one paste, decoded as UTF-8 with CR LF and CR made LF.
+;; - A `Decoder` holds bytes until they make a whole event. The reader in
+;; (bjoterm terminal) asks for a partial event with `final? #t` when no
+;; more bytes came within its timeout: a lone ESC is then Escape.
+;; - (bjoterm terminal) re-exports the types, so a program imports this
+;; module only to decode bytes it has itself.
+
+(import (std prelude))
+
+(export
+ Key Mods TermEvent Decoder
+ no-mods key->string event->string decode-input
+ make-decoder decoder-feed! decoder-next! decoder-partial? decoder-in-paste?)
+
+;; ===========================================================================
+;; Types
+;; ===========================================================================
+
+;; The modifier keys held with a key.
+(type (: Mods (Record (: shift? bool) (: alt? bool) (: ctrl? bool))))
+
+;; A key.
+;; - `KeyChar`: a character. Ctrl and a letter is the letter with `ctrl?`:
+;; Ctrl-A is `(KeyChar #\a)`. Ctrl-J (a line feed) is `(KeyChar #\j)`, not
+;; `KeyEnter`.
+;; - `KeyBackspace` with `ctrl?` is byte 8, which is Ctrl-H and, on some
+;; terminals, Ctrl-Backspace.
+;; - `KeyF`: F1 to F12.
+;; - `KeyUnknown`: a sequence the decoder does not know, with ESC shown as
+;; "^[".
+(type (: Key (Union (: KeyChar char) KeyEnter KeyTab KeyBackspace KeyEscape
+ KeyUp KeyDown KeyLeft KeyRight KeyHome KeyEnd
+ KeyPageUp KeyPageDown KeyInsert KeyDelete
+ (: KeyF int) (: KeyUnknown string))))
+
+;; An event read from the terminal.
+;; - `TermKey`: a key and its modifiers.
+;; - `TermPaste`: text pasted while bracketed paste is on, with line ends
+;; made "\n".
+;; - `TermResized`: the new size, columns then rows. Also after the program
+;; was stopped and continued: draw the screen again.
+;; - `TermEnd`: end of input; the terminal hung up.
+(type (: TermEvent (Union (: TermKey Key Mods) (: TermPaste string)
+ (: TermResized int int) TermEnd)))
+
+;; Bytes not yet decoded: `buf` from `start` to `end`.
+;; - `paste?`: inside a bracketed paste.
+;; - `scanned`: how far a paste has been searched for its end, so that a
+;; long paste is searched once.
+(type (: Decoder #:opaque
+ (Record (: buf (Array byte) #:mutable)
+ (: start int #:mutable)
+ (: end int #:mutable)
+ (: paste? bool #:mutable)
+ (: scanned int #:mutable))))
+
+;; What decoding at one place found.
+;; - `NeedMore`: a partial event; wait for more bytes.
+;; - `Got`: an event, and how many bytes it took.
+;; - `PasteBegins`: "ESC [ 200 ~", and how many bytes it took.
+(type (: Decoded (Union NeedMore (: Got TermEvent int) (: PasteBegins int))))
+
+;; ===========================================================================
+;; Events as text
+;; ===========================================================================
+
+;; No modifier keys.
+(: Mods)
+(def no-mods (Mods (shift? #f) (alt? #f) (ctrl? #f)))
+
+;; A key as text, such as "C-a", "M-" or "S-": modifiers as
+;; Emacs writes them (C- Ctrl, M- Alt, S- Shift), and names in brackets.
+(: (-> Key Mods string))
+(defun (key->string key mods)
+ (def name
+ (match key
+ ((KeyChar #\space) "")
+ ((KeyChar c) (char->string c))
+ (KeyEnter "")
+ (KeyTab "")
+ (KeyBackspace "")
+ (KeyEscape "")
+ (KeyUp "")
+ (KeyDown "")
+ (KeyLeft "")
+ (KeyRight "")
+ (KeyHome "")
+ (KeyEnd "")
+ (KeyPageUp "")
+ (KeyPageDown "")
+ (KeyInsert "")
+ (KeyDelete "")
+ ((KeyF n) (str "string n) ">"))
+ ((KeyUnknown text) (str ""))))
+ (str (if (record-ref mods ctrl?) "C-" "")
+ (if (record-ref mods alt?) "M-" "")
+ (if (record-ref mods shift?) "S-" "")
+ name))
+
+;; An event as text, for logs and tests.
+(: (-> TermEvent string))
+(defun (event->string ev)
+ (match ev
+ ((TermKey key mods) (str "key " (key->string key mods)))
+ ((TermPaste text) (str "paste " (written text)))
+ ((TermResized cols rows) (str "resized " (int->string cols) "x" (int->string rows)))
+ (TermEnd "end")))
+
+;; ===========================================================================
+;; The decoder
+;; ===========================================================================
+
+;; A decoder with no bytes.
+(: (-> Decoder))
+(defun (make-decoder)
+ (Decoder (buf (make-array 256)) (start 0) (end 0) (paste? #f) (scanned 0)))
+
+;; Whether the decoder holds bytes of an event not yet complete.
+(: (-> Decoder bool))
+(defun (decoder-partial? d)
+ (> (record-ref d end) (record-ref d start)))
+
+;; Whether the decoder is inside a bracketed paste. A paste waits for its
+;; end however long it takes.
+(: (-> Decoder bool))
+(defun (decoder-in-paste? d)
+ (record-ref d paste?))
+
+;; Adds the first `count` bytes of `bytes`.
+(: (-> Decoder (Array byte) int void))
+(defun (decoder-feed! d bytes count)
+ (when (= (record-ref d start) (record-ref d end))
+ (record-set! d (start 0) (end 0) (scanned 0)))
+ (def buf (record-ref d buf))
+ (def start (record-ref d start))
+ (def end (record-ref d end))
+ (def live (- end start))
+ (when (> (+ end count) (array-length buf))
+ ;; Move the live bytes to the front, into a larger array if they do
+ ;; not fit.
+ (def target (if (> (+ live count) (array-length buf))
+ (make-array (max (* 2 (array-length buf)) (+ live count)))
+ buf))
+ (array-copy! buf start target 0 live)
+ (record-set! d (buf target) (start 0) (end live)
+ (scanned (- (record-ref d scanned) start))))
+ (array-copy! bytes 0 (record-ref d buf) (record-ref d end) count)
+ (record-set! d (end (+ (record-ref d end) count))))
+
+;; The next whole event, or None when the bytes so far are part of one.
+;; With `final?`, a partial event is decoded as it is: a lone ESC is
+;; Escape, ESC and one byte is Alt and that key, a cut UTF-8 character is
+;; U+FFFD, and a cut sequence is `KeyUnknown`. A paste is never cut.
+(: (-> Decoder bool (Option TermEvent)))
+(defun (decoder-next! d final?)
+ (cond
+ ((record-ref d paste?) (next-paste! d))
+ ((not (decoder-partial? d)) None)
+ (else
+ (match (decode d (record-ref d start) final?)
+ (NeedMore None)
+ ((Got ev used)
+ (record-set! d (start (+ (record-ref d start) used)))
+ (Some ev))
+ ((PasteBegins used)
+ (def start (+ (record-ref d start) used))
+ (record-set! d (start start) (paste? #t) (scanned start))
+ (next-paste! d))))))
+
+;; Decodes all of `bytes` as input that ends there: a partial event at the
+;; end is decoded as it is. For tests, and for input recorded earlier.
+(: (-> (Array byte) (Vec TermEvent)))
+(defun (decode-input bytes)
+ (def d (make-decoder))
+ (decoder-feed! d bytes (array-length bytes))
+ (let go ((out []))
+ (match (decoder-next! d #f)
+ ((Some ev) (go (vec-add out ev)))
+ (None
+ (match (decoder-next! d #t)
+ ((Some ev) (go (vec-add out ev)))
+ (None out))))))
+
+;; ---------------------------------------------------------------------------
+;; Bracketed paste
+;; ---------------------------------------------------------------------------
+
+;; The paste, when its end has come.
+(: (-> Decoder (Option TermEvent)))
+(defun (next-paste! d)
+ (def start (record-ref d start))
+ (def end (record-ref d end))
+ ;; The end marker can start up to 5 bytes before what was searched.
+ (let go ((i (max start (- (record-ref d scanned) 5))))
+ (cond
+ ((> (+ i 6) end)
+ (record-set! d (scanned (max start (- end 5))))
+ None)
+ ((paste-end-at? d i)
+ (def text (bytes->string/lossy (record-ref d buf) #:start start #:end i))
+ (record-set! d (start (+ i 6)) (paste? #f) (scanned 0))
+ (Some (TermPaste (string-replace (string-replace text "\r\n" "\n") "\r" "\n"))))
+ (else (go (+ i 1))))))
+
+;; Whether "ESC [ 2 0 1 ~" starts at `i`.
+(: (-> Decoder int bool))
+(defun (paste-end-at? d i)
+ (and (= (byte-at d i) 27) (= (byte-at d (+ i 1)) 91) (= (byte-at d (+ i 2)) 50)
+ (= (byte-at d (+ i 3)) 48) (= (byte-at d (+ i 4)) 49) (= (byte-at d (+ i 5)) 126)))
+
+;; ---------------------------------------------------------------------------
+;; Keys
+;; ---------------------------------------------------------------------------
+
+(: (-> Decoder int int))
+(defun (byte-at d i)
+ (cast int (array-ref (record-ref d buf) i)))
+
+(: (-> Key TermEvent))
+(defun (plain k)
+ (TermKey k no-mods))
+
+(: (-> char TermEvent))
+(defun (ctrl c)
+ (TermKey (KeyChar c) (Mods (shift? #f) (alt? #f) (ctrl? #t))))
+
+(: (-> char TermEvent))
+(defun (alt c)
+ (TermKey (KeyChar c) (Mods (shift? #f) (alt? #t) (ctrl? #f))))
+
+;; The event at `at`.
+(: (-> Decoder int bool Decoded))
+(defun (decode d at final?)
+ (def avail (- (record-ref d end) at))
+ (def b (byte-at d at))
+ (cond
+ ((= b 27)
+ (cond
+ ((= avail 1) (if final? (Got (plain KeyEscape) 1) NeedMore))
+ ((= (byte-at d (+ at 1)) 91) (csi d at final?))
+ ((= (byte-at d (+ at 1)) 79) (ss3 d at final?))
+ (else
+ ;; ESC and a key is Alt and that key.
+ (match (decode d (+ at 1) final?)
+ (NeedMore NeedMore)
+ ((Got (TermKey key mods) used)
+ (if (unknown? key)
+ (Got (plain (KeyUnknown (shown d at (+ 1 used)))) (+ 1 used))
+ (Got (TermKey key (record-set mods (alt? #t))) (+ 1 used))))
+ ((Got _ used) (Got (plain (KeyUnknown (shown d at (+ 1 used)))) (+ 1 used)))
+ ((PasteBegins used) (Got (plain (KeyUnknown (shown d at (+ 1 used)))) (+ 1 used)))))))
+ ((< b 128) (Got (ascii b) 1))
+ (else (utf8 d at final?))))
+
+(: (-> Key bool))
+(defun (unknown? key)
+ (match key
+ ((KeyUnknown _) #t)
+ (_ #f)))
+
+(: (-> int TermEvent))
+(defun (ascii b)
+ (cond
+ ((= b 13) (plain KeyEnter))
+ ((= b 9) (plain KeyTab))
+ ((= b 127) (plain KeyBackspace))
+ ((= b 8) (TermKey KeyBackspace (Mods (shift? #f) (alt? #f) (ctrl? #t))))
+ ((= b 0) (ctrl #\space))
+ ((< b 27) (ctrl (int->char (+ 96 b))))
+ ((< b 32) (ctrl (int->char (+ 64 b))))
+ (else (plain (KeyChar (int->char b))))))
+
+(: TermEvent)
+(def replacement (plain (KeyChar (int->char 65533))))
+
+;; A UTF-8 character at `at`, whose first byte is 128 or more.
+(: (-> Decoder int bool Decoded))
+(defun (utf8 d at final?)
+ (def b (byte-at d at))
+ (def end (record-ref d end))
+ (def length (cond ((and (>= b 0xc2) (< b 0xe0)) 2)
+ ((and (>= b 0xe0) (< b 0xf0)) 3)
+ ((and (>= b 0xf0) (< b 0xf5)) 4)
+ (else 0)))
+ (def have (let go ((n 1))
+ (if (and (< n length) (< (+ at n) end)
+ (= (bitwise-and (byte-at d (+ at n)) 0xc0) 0x80))
+ (go (+ n 1))
+ n)))
+ (cond
+ ((= length 0) (Got replacement 1))
+ ((< have length)
+ ;; Cut: wait for the rest, unless a byte that cannot continue it came,
+ ;; or no more will come.
+ (if (and (= (+ at have) end) (not final?)) NeedMore (Got replacement have)))
+ (else
+ (def first-bits (bitwise-and b (cond ((= length 2) 0x1f) ((= length 3) 0x0f) (else 0x07))))
+ (def code (let go ((n 1) (c first-bits))
+ (if (= n length)
+ c
+ (go (+ n 1) (bitwise-ior (shift-left c 6) (bitwise-and (byte-at d (+ at n)) 0x3f))))))
+ (def valid? (cond ((= length 3) (and (>= code 0x800) (or (< code 0xd800) (> code 0xdfff))))
+ ((= length 4) (and (>= code 0x10000) (<= code 0x10ffff)))
+ (else #t)))
+ (Got (if valid? (plain (KeyChar (int->char code))) replacement) length))))
+
+;; "ESC [", parameters, intermediates and a final byte.
+(: (-> Decoder int bool Decoded))
+(defun (csi d at final?)
+ (def end (record-ref d end))
+ (def after-params (let go ((i (+ at 2)))
+ (if (and (< i end) (>= (byte-at d i) 0x30) (<= (byte-at d i) 0x3f)) (go (+ i 1)) i)))
+ (def last-at (let go ((i after-params))
+ (if (and (< i end) (>= (byte-at d i) 0x20) (<= (byte-at d i) 0x2f)) (go (+ i 1)) i)))
+ (cond
+ ((= last-at end)
+ (cond
+ ((not final?) NeedMore)
+ ;; "ESC [" alone is Alt-[.
+ ((= (- end at) 2) (Got (alt #\[) 2))
+ (else (Got (plain (KeyUnknown (shown d at (- end at)))) (- end at)))))
+ (else
+ (def last (byte-at d last-at))
+ (def used (+ 1 (- last-at at)))
+ (def params (csi-params d (+ at 2) after-params))
+ (def first (param params 0 1))
+ (def mods (mods-of (param params 1 1)))
+ (defun (key k) (Got (TermKey k mods) used))
+ (cond
+ ((or (< last 0x40) (> last 0x7e)) (Got (plain (KeyUnknown (shown d at used))) used))
+ ((= last 65) (key KeyUp))
+ ((= last 66) (key KeyDown))
+ ((= last 67) (key KeyRight))
+ ((= last 68) (key KeyLeft))
+ ((= last 72) (key KeyHome))
+ ((= last 70) (key KeyEnd))
+ ((and (>= last 80) (<= last 83)) (key (KeyF (- last 79))))
+ ((= last 90) (Got (TermKey KeyTab (Mods (shift? #t) (alt? #f) (ctrl? #f))) used))
+ ((and (= last 126) (= first 200)) (PasteBegins used))
+ ((= last 126)
+ (match (tilde-key first)
+ ((Some k) (key k))
+ (None (Got (plain (KeyUnknown (shown d at used))) used))))
+ (else (Got (plain (KeyUnknown (shown d at used))) used))))))
+
+;; The numbers of a parameter list "1;5": -1 for one left out.
+(: (-> Decoder int int (Vec int)))
+(defun (csi-params d from to)
+ (let go ((i from) (n -1) (out []))
+ (cond
+ ((= i to) (vec-add out n))
+ ((= (byte-at d i) 59) (go (+ i 1) -1 (vec-add out n)))
+ ((and (>= (byte-at d i) 48) (<= (byte-at d i) 57))
+ (go (+ i 1) (+ (* (max n 0) 10) (- (byte-at d i) 48)) out))
+ (else (go (+ i 1) n out)))))
+
+(: (-> (Vec int) int int int))
+(defun (param params i missing)
+ (if (and (< i (vec-length params)) (>= (vec-ref params i) 0))
+ (vec-ref params i)
+ missing))
+
+;; xterm's modifier parameter is 1 plus the bits shift 1, alt 2, ctrl 4,
+;; meta 8. Meta is Alt here.
+(: (-> int Mods))
+(defun (mods-of parameter)
+ (def bits (max 0 (- parameter 1)))
+ (Mods (shift? (not (= 0 (bitwise-and bits 1))))
+ (alt? (not (= 0 (bitwise-and bits 10))))
+ (ctrl? (not (= 0 (bitwise-and bits 4))))))
+
+;; The keys "ESC [ n ~".
+(: (-> int (Option Key)))
+(defun (tilde-key n)
+ (cond
+ ((or (= n 1) (= n 7)) (Some KeyHome))
+ ((= n 2) (Some KeyInsert))
+ ((= n 3) (Some KeyDelete))
+ ((or (= n 4) (= n 8)) (Some KeyEnd))
+ ((= n 5) (Some KeyPageUp))
+ ((= n 6) (Some KeyPageDown))
+ ((and (>= n 11) (<= n 15)) (Some (KeyF (- n 10))))
+ ((and (>= n 17) (<= n 21)) (Some (KeyF (- n 11))))
+ ((or (= n 23) (= n 24)) (Some (KeyF (- n 12))))
+ (else None)))
+
+;; "ESC O" and a key: the keys of application cursor mode, and F1 to F4.
+(: (-> Decoder int bool Decoded))
+(defun (ss3 d at final?)
+ (cond
+ ((< (- (record-ref d end) at) 3)
+ (if final? (Got (alt #\O) 2) NeedMore))
+ (else
+ (def k (byte-at d (+ at 2)))
+ (Got (cond
+ ((= k 65) (plain KeyUp))
+ ((= k 66) (plain KeyDown))
+ ((= k 67) (plain KeyRight))
+ ((= k 68) (plain KeyLeft))
+ ((= k 72) (plain KeyHome))
+ ((= k 70) (plain KeyEnd))
+ ((= k 77) (plain KeyEnter))
+ ((and (>= k 80) (<= k 83)) (plain (KeyF (- k 79))))
+ (else (plain (KeyUnknown (shown d at 3)))))
+ 3))))
+
+;; `count` bytes from `at` as text: ESC as "^[", other controls and bytes
+;; above 126 as "\xNN".
+(: (-> Decoder int int string))
+(defun (shown d at count)
+ (def out (stringbuilder-empty))
+ (loop (:for i (range at (+ at count)))
+ (:do (def b (byte-at d i))
+ (cond
+ ((= b 27) (stringbuilder-add-string! out "^["))
+ ((or (< b 32) (> b 126))
+ (stringbuilder-add-string! out (str "\\x" (string-pad-left (int->string b #:radix 16) 2 #:with #\0))))
+ (else (stringbuilder-add! out (int->char b))))))
+ (stringbuilder->string out))
diff --git a/src/line.bjo b/src/line.bjo
index 74aea23..091150b 100644
--- a/src/line.bjo
+++ b/src/line.bjo
@@ -27,6 +27,7 @@
(import (std prelude))
(import (std maths))
(import (bjoterm terminal))
+(import (bjoterm text))
(export
LineEditor LineResult Completion
@@ -34,16 +35,6 @@
line-history line-history-add! line-history-load! line-history-save
simulate-line)
-(import/extern
- (text-clusters (: Bjoterm.Text.Clusters (-> string (Array string)) #:no-raise))
- (prompt-clusters (: Bjoterm.Text.PromptClusters (-> string (Array string)) #:no-raise))
- (cluster-width (: Bjoterm.Text.Width (-> string int) #:no-raise))
- (cluster-shown (: Bjoterm.Text.Shown (-> string string) #:no-raise))
- (text-width (: Bjoterm.Text.TextWidth (-> string int) #:no-raise))
- (word-cluster? (: Bjoterm.Text.IsWord (-> string bool) #:no-raise))
- (common-prefix (: Bjoterm.Text.CommonPrefix (-> (Array string) string) #:no-raise))
- (find-clusters (: Bjoterm.Text.Find (-> string string int) #:no-raise)))
-
;; ===========================================================================
;; Types
;; ===========================================================================
@@ -183,6 +174,9 @@
;; by default, spaces as wide as `prompt`.
;; - Sets raw mode for the time it reads, unless the terminal is in raw
;; mode already.
+;; - In a bjoroutine it suspends while it waits for keys; elsewhere it parks
+;; the thread. Cancelling the scope around it ends it with the modes
+;; restored.
;; - Moving: Left, Right, C-b, C-f; by word M-b, M-f, C-Left, C-Right; to
;; the line's start and end Home, End, C-a, C-e; between lines Up, Down.
;; - Deleting: Backspace, Delete, C-d; to the kill buffer C-k (to the end of
@@ -195,14 +189,17 @@
;; - Enter accepts (see `#:input-done?`), M-Enter and C-j start a new line,
;; C-l clears the screen, C-z stops the program, C-c cancels, and C-d on
;; an empty buffer is end of input.
-(: (-> LineEditor Terminal string (#:continuation (Option string)) LineResult) #:sync)
+(: (-> LineEditor Terminal string (#:continuation (Option string)) LineResult))
(defun (line-read ed term prompt #:continuation None)
(def cont (match continuation
((Some c) c)
(None (string-pad-left "" (text-width prompt)))))
(if (terminal-raw? term)
(edit-loop ed term prompt cont)
- (with-raw-mode term (fun () (edit-loop ed term prompt cont)))))
+ ;; A `fun` is ordinary code, so the suspending copy passes a
+ ;; bjoroutine.
+ (by-colour (#:sync (with-raw-mode term (fun () (edit-loop ed term prompt cont))))
+ (#:bjo (with-raw-mode term (bjoroutine () (edit-loop ed term prompt cont)))))))
(: (-> LineEditor State))
(defun (start-state ed)
@@ -210,7 +207,7 @@
(hist-at (vec-length (record-ref ed history))) (draft [])
(search None) (tabbed? #f)))
-(: (-> LineEditor Terminal string string LineResult) #:sync)
+(: (-> LineEditor Terminal string string LineResult))
(defun (edit-loop ed term prompt cont)
(def out (parameter-ref current-output-port))
(def/mutable row 0)
@@ -310,10 +307,10 @@
((Some s)
(def label (str "(" (if (record-ref s failed?) "failed " "")
"search `" (record-ref s query) "'): "))
- (layout (array->vec (prompt-clusters label)) (array->vec (prompt-clusters cont))
+ (layout (prompt-clusters label) (prompt-clusters cont)
(record-ref st text) (record-ref st cursor) width))
(None
- (layout (array->vec (prompt-clusters prompt)) (array->vec (prompt-clusters cont))
+ (layout (prompt-clusters prompt) (prompt-clusters cont)
(record-ref st text) (record-ref st cursor) width))))
(: (-> (Vec string) (Vec string) (Vec string) int int Layout))
@@ -366,7 +363,7 @@
(: (-> string (Vec string)))
(defun (clusters s)
- (array->vec (text-clusters s)))
+ (text-clusters s))
(: (-> State string State))
(defun (insert st s)
@@ -521,7 +518,7 @@
((= (vec-length candidates) 0) (Bell st))
((= (vec-length candidates) 1) (Edited (replace-with (vec-ref candidates 0))))
(else
- (def common (common-prefix (vec->array candidates)))
+ (def common (common-prefix candidates))
(cond
((> (vec-length (clusters common)) k) (Edited (replace-with common)))
(tabbed? (ShowList st candidates))
diff --git a/src/terminal.bjo b/src/terminal.bjo
index 7ac7a93..701e1e9 100644
--- a/src/terminal.bjo
+++ b/src/terminal.bjo
@@ -19,16 +19,22 @@
;; module: .NET then sets its own terminal modes.
;; - Output is strings: write them to standard output. `read-event` flushes
;; `current-output-port` before it waits.
-;; - See glue/Tty.cs and glue/Keys.cs for the C# side.
+;; - `read-event` and the functions that call it work in both colours: in a
+;; bjoroutine they suspend while they wait, elsewhere they park the
+;; thread.
+;; - Read events from one fiber at a time. The bytes not yet decoded are
+;; kept for the whole process, as there is one terminal.
+;; - The event types and the decoder are (bjoterm keys), re-exported here.
+;; glue/Tty.cs has termios, the signals, and the reading of bytes.
(import (std prelude))
+(import (bjoterm keys))
(export
- Terminal TerminalError Key Mods TermEvent Color Style
+ Terminal TerminalError Color Style
terminal-open terminal-error-message with-raw-mode terminal-raw?
terminal-size terminal-suspend
read-event read-event/timeout
- no-mods key->string event->string decode-input
;; Escape sequences.
cursor-to cursor-up cursor-down cursor-forward cursor-back cursor-column
cursor-save cursor-restore cursor-hide cursor-show
@@ -36,9 +42,10 @@
alt-screen-on alt-screen-off bracketed-paste-on bracketed-paste-off
styled style-start style-reset)
+(re-export Key Mods TermEvent no-mods key->string event->string decode-input)
+
(import/class
- (Tty (: Bjoterm.Tty))
- (NEvent (: Bjoterm.TermEvent)))
+ (Tty (: Bjoterm.Tty)))
(import/extern
(tty-open (: Bjoterm.Tty.Open (-> Tty)
@@ -50,15 +57,10 @@
#:raises (System.InvalidOperationException System.ComponentModel.Win32Exception)))
(leave-raw (: Bjoterm.Tty.LeaveRaw (-> Tty void) #:no-raise))
(tty-suspend (: Bjoterm.Tty.Suspend (-> Tty void) #:no-raise))
- (tty-read (: Bjoterm.Tty.ReadAsync (-> Tty int NEvent) #:async
- #:raises (System.InvalidOperationException System.ComponentModel.Win32Exception)))
- (decode-all (: Bjoterm.Decoder.DecodeAll (-> (Array byte) (Array NEvent)) #:no-raise))
- (ev-kind (: Bjoterm.TermEvent.Kind (-> NEvent int) #:get #:no-raise))
- (ev-key (: Bjoterm.TermEvent.Key (-> NEvent int) #:get #:no-raise))
- (ev-value (: Bjoterm.TermEvent.Value (-> NEvent int) #:get #:no-raise))
- (ev-value2 (: Bjoterm.TermEvent.Value2 (-> NEvent int) #:get #:no-raise))
- (ev-mods (: Bjoterm.TermEvent.Mods (-> NEvent int) #:get #:no-raise))
- (ev-text (: Bjoterm.TermEvent.Text (-> NEvent string) #:get #:no-raise)))
+ (take-resized? (: Bjoterm.Tty.TakeResized (-> Tty bool) #:no-raise))
+ (tty-read (: Bjoterm.Tty.ReadAsync (-> Tty (Array byte) int int) #:async
+ #:raises (System.ComponentModel.Win32Exception)))
+ (now-ms (: System.Environment.TickCount64 (-> long) #:get #:no-raise)))
;; ===========================================================================
;; Types
@@ -72,33 +74,6 @@
;; - `NotATerminal`: standard input or standard output is not a terminal.
(type (: TerminalError (Union TerminalUnsupported (: NotATerminal string))))
-;; The modifier keys held with a key.
-(type (: Mods (Record (: shift? bool) (: alt? bool) (: ctrl? bool))))
-
-;; A key.
-;; - `KeyChar`: a character. Ctrl and a letter is the letter with `ctrl?`:
-;; Ctrl-A is `(KeyChar #\a)`. Ctrl-J (a line feed) is `(KeyChar #\j)`, not
-;; `KeyEnter`.
-;; - `KeyBackspace` with `ctrl?` is byte 8, which is Ctrl-H and, on some
-;; terminals, Ctrl-Backspace.
-;; - `KeyF`: F1 to F12.
-;; - `KeyUnknown`: a sequence the decoder does not know, with ESC shown as
-;; "^[".
-(type (: Key (Union (: KeyChar char) KeyEnter KeyTab KeyBackspace KeyEscape
- KeyUp KeyDown KeyLeft KeyRight KeyHome KeyEnd
- KeyPageUp KeyPageDown KeyInsert KeyDelete
- (: KeyF int) (: KeyUnknown string))))
-
-;; An event read from the terminal.
-;; - `TermKey`: a key and its modifiers.
-;; - `TermPaste`: text pasted while bracketed paste is on, with line ends
-;; made "\n".
-;; - `TermResized`: the new size, columns then rows. Also after the program
-;; was stopped and continued: draw the screen again.
-;; - `TermEnd`: end of input; the terminal hung up.
-(type (: TermEvent (Union (: TermKey Key Mods) (: TermPaste string)
- (: TermResized int int) TermEnd)))
-
;; A color.
;; - `Ansi`: 0 to 7 are black, red, green, yellow, blue, magenta, cyan and
;; white; 8 to 15 are their bright forms.
@@ -141,7 +116,8 @@
;; - When the process is stopped and continued, raw mode is set again.
;; - Raises InvalidOperationException when the terminal is in raw mode
;; already.
-(: (-> Terminal (-> %a) (#:signals? bool) %a))
+;; - `body` may be a bjoroutine: `(with-raw-mode term (bjoroutine () ...))`.
+(: (-> Terminal (-?-> %a) (#:signals? bool) %a))
(defun (with-raw-mode term body #:signals? #f)
(def tty (record-ref term tty))
(enter-raw tty signals?)
@@ -174,8 +150,24 @@
;; Events
;; ===========================================================================
+;; The bytes read and not yet decoded. One for the process, as the terminal
+;; is.
+(: Decoder)
+(def input (make-decoder))
+
+;; How long to wait for the rest of a sequence after its first bytes.
+(: int)
+(def sequence-timeout-ms 50)
+
+;; What `tty-read` returns at end of input, and after a resize.
+(: int)
+(def end-of-input -1)
+
+(: int)
+(def resized -2)
+
;; Waits for the next event. Flushes `current-output-port` first.
-(: (-> Terminal TermEvent) #:sync)
+(: (-> Terminal TermEvent))
(defun (read-event term)
(let go ()
(match (read-event/timeout term -1)
@@ -184,104 +176,59 @@
;; Waits at most `ms` milliseconds for the next event; below 0, for ever.
;; Returns None at the timeout. Flushes `current-output-port` first.
-(: (-> Terminal int (Option TermEvent)) #:sync)
+;; - A sequence whose first bytes came is waited for 50 ms more; then what
+;; came is decoded alone, so a lone ESC is the Escape key.
+;; - A resize, or SIGCONT, comes before the bytes after it.
+(: (-> Terminal int (Option TermEvent)))
(defun (read-event/timeout term ms)
(flush-port (parameter-ref current-output-port))
- (match (sync/blocking (promise-join (bjo (reading (record-ref term tty) ms))))
- ((Err e) (raise e))
- ((Ok ev) (event-of ev))))
+ (def tty (record-ref term tty))
+ ;; -1 for no deadline.
+ (def deadline (if (< ms 0) (cast long -1) (+ now-ms (cast long ms))))
+ (def no-deadline? (< ms 0))
+ (def buffer (make-array 4096))
+ (defun (decoded-or ev)
+ (match (decoder-next! input #t)
+ ((Some e) (Some e))
+ (None ev)))
+ (let go ()
+ (if (take-resized? tty)
+ (let ((size (tty-size tty)))
+ (Some (TermResized (array-ref size 0) (array-ref size 1))))
+ (match (decoder-next! input #f)
+ ((Some ev) (Some ev))
+ (None
+ (def partial? (and (decoder-partial? input) (not (decoder-in-paste? input))))
+ (def wait (cond (partial? sequence-timeout-ms)
+ (no-deadline? -1)
+ (else (cast int (max 0 (- deadline now-ms))))))
+ (def n (read-bytes tty buffer wait))
+ (cond
+ ((> n 0) (decoder-feed! input buffer n) (go))
+ ((= n end-of-input) (decoded-or (Some TermEnd)))
+ ((= n resized) (go))
+ (partial?
+ (match (decoder-next! input #t)
+ ((Some ev) (Some ev))
+ (None (go))))
+ ((and (not no-deadline?) (>= now-ms deadline)) None)
+ (else (go))))))))
-(: (-> Tty int NEvent))
-(defbjo (reading tty ms)
- (tty-read tty ms))
+;; Reads bytes from the terminal: suspends in a bjoroutine, parks the
+;; thread elsewhere. Returns the count, 0 at the timeout, `end-of-input` or
+;; `resized`.
+(: (-> Tty (Array byte) int int))
+(defbjouble (read-bytes tty buffer ms)
+ (#:sync (read-bytes/blocking tty buffer ms))
+ (#:bjo (tty-read tty buffer ms)))
-(: (-> NEvent (Option TermEvent)))
-(defun (event-of ev)
- (match (ev-kind ev)
- (0 None)
- (1 (Some (TermKey (key-of ev) (mods-of (ev-mods ev)))))
- (2 (Some (TermPaste (ev-text ev))))
- (3 (Some (TermResized (ev-value ev) (ev-value2 ev))))
- (_ (Some TermEnd))))
-
-(: (-> NEvent Key))
-(defun (key-of ev)
- (match (ev-key ev)
- (0 (KeyChar (int->char (ev-value ev))))
- (1 KeyEnter)
- (2 KeyTab)
- (3 KeyBackspace)
- (4 KeyEscape)
- (5 KeyUp)
- (6 KeyDown)
- (7 KeyLeft)
- (8 KeyRight)
- (9 KeyHome)
- (10 KeyEnd)
- (11 KeyPageUp)
- (12 KeyPageDown)
- (13 KeyInsert)
- (14 KeyDelete)
- (15 (KeyF (ev-value ev)))
- (_ (KeyUnknown (ev-text ev)))))
-
-(: (-> int Mods))
-(defun (mods-of bits)
- (Mods (shift? (not (= 0 (bitwise-and bits 1))))
- (alt? (not (= 0 (bitwise-and bits 2))))
- (ctrl? (not (= 0 (bitwise-and bits 4))))))
-
-;; Decodes bytes of terminal input into events, as `read-event` would
-;; return them. A partial event at the end is decoded as it is: a lone ESC
-;; is `KeyEscape`. For tests, and for input recorded earlier.
-(: (-> (Array byte) (Vec TermEvent)))
-(defun (decode-input bytes)
- (loop (:for ev (decode-all bytes))
- (:acc v (vecing (match (event-of ev)
- ((Some e) e)
- (None TermEnd))))))
-
-;; No modifier keys.
-(: Mods)
-(def no-mods (Mods (shift? #f) (alt? #f) (ctrl? #f)))
-
-;; A key as text, such as "C-a", "M-" or "S-": modifiers as
-;; Emacs writes them (C- Ctrl, M- Alt, S- Shift), and names in brackets.
-(: (-> Key Mods string))
-(defun (key->string key mods)
- (def name
- (match key
- ((KeyChar #\space) "")
- ((KeyChar c) (char->string c))
- (KeyEnter "")
- (KeyTab "")
- (KeyBackspace "")
- (KeyEscape "")
- (KeyUp "")
- (KeyDown "")
- (KeyLeft "")
- (KeyRight "")
- (KeyHome "")
- (KeyEnd "")
- (KeyPageUp "")
- (KeyPageDown "")
- (KeyInsert "")
- (KeyDelete "")
- ((KeyF n) (str "string n) ">"))
- ((KeyUnknown text) (str ""))))
- (str (if (record-ref mods ctrl?) "C-" "")
- (if (record-ref mods alt?) "M-" "")
- (if (record-ref mods shift?) "S-" "")
- name))
-
-;; An event as text, for logs and tests.
-(: (-> TermEvent string))
-(defun (event->string ev)
- (match ev
- ((TermKey key mods) (str "key " (key->string key mods)))
- ((TermPaste text) (str "paste " (written text)))
- ((TermResized cols rows) (str "resized " (int->string cols) "x" (int->string rows)))
- (TermEnd "end")))
+;; The read on a fiber of its own, which the thread waits for. The fiber is
+;; in the caller's scope, so cancelling the scope ends the read.
+(: (-> Tty (Array byte) int int) #:sync)
+(defun (read-bytes/blocking tty buffer ms)
+ (match (sync/blocking (promise-join (bjo (tty-read tty buffer ms))))
+ ((Ok n) n)
+ ((Err e) (raise e))))
;; ===========================================================================
;; Escape sequences
diff --git a/src/text.bjo b/src/text.bjo
new file mode 100644
index 0000000..d78dc55
--- /dev/null
+++ b/src/text.bjo
@@ -0,0 +1,234 @@
+;; This Source Code Form is subject to the terms of the Mozilla Public
+;; License, v. 2.0. If a copy of the MPL was not distributed with this
+;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+;; (bjoterm text): text on a terminal, as grapheme clusters and columns.
+;;
+;; - Clusters are extended grapheme clusters (UAX #29), from
+;; (std unicode grapheme): what a reader sees as one character, such as
+;; "e" with an accent, or an emoji with a skin tone.
+;; - Widths follow `wcwidth`: 2 for East Asian wide and fullwidth
+;; characters and for emoji shown as emoji, 0 for combining marks and
+;; format characters, 1 otherwise. A terminal's own table can differ for
+;; new emoji.
+;; - A C0 control or DEL is shown as "^X", 2 columns. A C1 control
+;; (U+0080 to U+009F) is shown as U+FFFD.
+;; - A prompt can hold escape sequences (CSI, and OSC ended by BEL or ST).
+;; `prompt-clusters` keeps each as one item of width 0.
+
+(import (std prelude))
+(import (std maths))
+(import (std unicode grapheme))
+
+(export
+ text-clusters prompt-clusters cluster-width cluster-shown text-width
+ word-cluster? find-clusters common-prefix)
+
+;; The grapheme clusters of `s`. "\r\n" is one.
+(: (-> string (Vec string)))
+(defun (text-clusters s)
+ (string->graphemes s))
+
+;; Whether code point `c` takes no columns: a non-spacing or enclosing
+;; mark, or a format character other than the soft hyphen.
+(: (-> int bool))
+(defun (zero-width? c)
+ (and (not (= c 0xad))
+ (let ((cat (char-general-category (int->char c))))
+ (or (= cat 'Mn) (= cat 'Me) (= cat 'Cf)))))
+
+;; Whether code point `c` is a letter or a decimal digit.
+(: (-> int bool))
+(defun (letter-or-digit? c)
+ (let ((cat (char-general-category (int->char c))))
+ (or (= cat 'Lu) (= cat 'Ll) (= cat 'Lt) (= cat 'Lm) (= cat 'Lo) (= cat 'Nd))))
+
+(: (-> string int))
+(defun (first-code s)
+ (char->int (string-cursor-ref s (string-cursor-start s))))
+
+(: (-> string bool))
+(defun (escape-sequence? c)
+ (and (> (string-length c) 1) (= (first-code c) 27)))
+
+;; The columns `c` takes. 0 for an escape sequence from `prompt-clusters`.
+(: (-> string int))
+(defun (cluster-width c)
+ (cond
+ ((string-empty? c) 0)
+ ((escape-sequence? c) 0)
+ (else
+ (def first (first-code c))
+ (def width (code-width first))
+ (cond
+ ((or (< first 32) (= first 127)) 2)
+ ((and (>= first 128) (< first 160)) 1)
+ ((= width 2) 2)
+ ;; Emoji presentation, or a flag of two regional indicators.
+ ((string-contains? c "\u{FE0F}") 2)
+ ((and (>= first 0x1f1e6) (<= first 0x1f1ff) (> (string-length c) 1)) 2)
+ ;; A cluster that starts with a mark: the widest of its parts.
+ ((= width 0)
+ (let ((chars (string->vec c)))
+ (let go ((i 0) (w 0))
+ (if (= i (vec-length chars))
+ w
+ (go (+ i 1) (max w (code-width (char->int (vec-ref chars i)))))))))
+ (else width)))))
+
+;; What is written for `c`: "^X" for a C0 control or DEL, U+FFFD for a C1
+;; control, else `c`.
+(: (-> string string))
+(defun (cluster-shown c)
+ (cond
+ ((string-empty? c) c)
+ ((escape-sequence? c) c)
+ (else
+ (def first (first-code c))
+ (cond
+ ((< first 32) (str "^" (char->string (int->char (+ first 64)))))
+ ((= first 127) "^?")
+ ((and (>= first 128) (< first 160)) "\u{FFFD}")
+ (else c)))))
+
+;; The columns of `s`, escape sequences as 0.
+(: (-> string int))
+(defun (text-width s)
+ (loop (:for c (in-vec (prompt-clusters s)))
+ (:acc w (summing (cluster-width c)))))
+
+;; Whether `c` is part of a word: it starts with a letter, a digit or "_".
+(: (-> string bool))
+(defun (word-cluster? c)
+ (and (not (string-empty? c))
+ (let ((first (first-code c)))
+ (or (= first 95) (letter-or-digit? first)))))
+
+;; The width of one code point, as `wcwidth`.
+(: (-> int int))
+(defun (code-width c)
+ (cond
+ ((= c 0) 0)
+ ((or (= c 0x200b) (and (>= c 0x1160) (<= c 0x11ff))) 0)
+ ((zero-width? c) 0)
+ ((wide? c) 2)
+ (else 1)))
+
+;; Ranges of East Asian Wide and Fullwidth code points, and of emoji with
+;; emoji presentation by default (Unicode 15). Sorted pairs, inclusive.
+(: (Vec int))
+(def wide-ranges
+ [0x1100 0x115f 0x231a 0x231b 0x2329 0x232a 0x23e9 0x23ec 0x23f0 0x23f0
+ 0x23f3 0x23f3 0x25fd 0x25fe 0x2614 0x2615 0x2648 0x2653 0x267f 0x267f
+ 0x2693 0x2693 0x26a1 0x26a1 0x26aa 0x26ab 0x26bd 0x26be 0x26c4 0x26c5
+ 0x26ce 0x26ce 0x26d4 0x26d4 0x26ea 0x26ea 0x26f2 0x26f3 0x26f5 0x26f5
+ 0x26fa 0x26fa 0x26fd 0x26fd 0x2705 0x2705 0x270a 0x270b 0x2728 0x2728
+ 0x274c 0x274c 0x274e 0x274e 0x2753 0x2755 0x2757 0x2757 0x2795 0x2797
+ 0x27b0 0x27b0 0x27bf 0x27bf 0x2b1b 0x2b1c 0x2b50 0x2b50 0x2b55 0x2b55
+ 0x2e80 0x303e 0x3041 0x33ff 0x3400 0x4dbf 0x4e00 0x9fff 0xa000 0xa4cf
+ 0xa960 0xa97f 0xac00 0xd7a3 0xf900 0xfaff 0xfe10 0xfe19 0xfe30 0xfe6f
+ 0xff00 0xff60 0xffe0 0xffe6 0x16fe0 0x16fe4 0x17000 0x18aff 0x1b000 0x1b2ff
+ 0x1f004 0x1f004 0x1f0cf 0x1f0cf 0x1f18e 0x1f18e 0x1f191 0x1f19a 0x1f200 0x1f202
+ 0x1f210 0x1f23b 0x1f240 0x1f248 0x1f250 0x1f251 0x1f260 0x1f265 0x1f300 0x1f320
+ 0x1f32d 0x1f335 0x1f337 0x1f37c 0x1f37e 0x1f393 0x1f3a0 0x1f3ca 0x1f3cf 0x1f3d3
+ 0x1f3e0 0x1f3f0 0x1f3f4 0x1f3f4 0x1f3f8 0x1f43e 0x1f440 0x1f440 0x1f442 0x1f4fc
+ 0x1f4ff 0x1f53d 0x1f54b 0x1f54e 0x1f550 0x1f567 0x1f57a 0x1f57a 0x1f595 0x1f596
+ 0x1f5a4 0x1f5a4 0x1f5fb 0x1f64f 0x1f680 0x1f6c5 0x1f6cc 0x1f6cc 0x1f6d0 0x1f6d2
+ 0x1f6d5 0x1f6d7 0x1f6dc 0x1f6df 0x1f6eb 0x1f6ec 0x1f6f4 0x1f6fc 0x1f7e0 0x1f7eb
+ 0x1f7f0 0x1f7f0 0x1f90c 0x1f93a 0x1f93c 0x1f945 0x1f947 0x1f9ff 0x1fa70 0x1faff
+ 0x20000 0x2fffd 0x30000 0x3fffd])
+
+(: (-> int bool))
+(defun (wide? c)
+ (and (>= c 0x1100)
+ (let go ((lo 0) (hi (- (quotient (vec-length wide-ranges) 2) 1)))
+ (if (> lo hi)
+ #f
+ (let ((mid (quotient (+ lo hi) 2)))
+ (cond
+ ((< c (vec-ref wide-ranges (* mid 2))) (go lo (- mid 1)))
+ ((> c (vec-ref wide-ranges (+ (* mid 2) 1))) (go (+ mid 1) hi))
+ (else #t)))))))
+
+;; The clusters of a prompt: as `text-clusters`, except that an escape
+;; sequence is one item, of width 0.
+(: (-> string (Vec string)))
+(defun (prompt-clusters s)
+ (def chars (string->vec s))
+ (def n (vec-length chars))
+ (defun (text-of from to)
+ (string-join (vec-map char->string (vec-slice chars from (- to from))) ""))
+ (let go ((i 0) (plain 0) (out []))
+ (cond
+ ((= i n)
+ (if (> n plain) (vec-append out (text-clusters (text-of plain n))) out))
+ (else
+ (def length (escape-length chars i))
+ (if (= length 0)
+ (go (+ i 1) plain out)
+ (let ((before (if (> i plain) (vec-append out (text-clusters (text-of plain i))) out)))
+ (go (+ i length) (+ i length) (vec-add before (text-of i (+ i length))))))))))
+
+;; The length in characters of an escape sequence at `i`, or 0.
+(: (-> (Vec char) int int))
+(defun (escape-length chars i)
+ (def n (vec-length chars))
+ (defun (code j) (char->int (vec-ref chars j)))
+ (cond
+ ((or (not (= (code i) 27)) (>= (+ i 1) n)) 0)
+ ((= (code (+ i 1)) 91)
+ ;; CSI: parameters and intermediates, then a final byte.
+ (let go ((j (+ i 2)))
+ (cond
+ ((= j n) 0)
+ ((and (>= (code j) 0x20) (<= (code j) 0x3f)) (go (+ j 1)))
+ ((and (>= (code j) 0x40) (<= (code j) 0x7e)) (+ 1 (- j i)))
+ (else 0))))
+ ((= (code (+ i 1)) 93)
+ ;; OSC: ended by BEL, or by ST ("ESC \").
+ (let go ((j (+ i 2)))
+ (cond
+ ((= j n) 0)
+ ((= (code j) 7) (+ 1 (- j i)))
+ ((and (= (code j) 27) (< (+ j 1) n) (= (code (+ j 1)) 92)) (+ 2 (- j i)))
+ (else (go (+ j 1))))))
+ (else 0)))
+
+;; The index of the first cluster of `text` where the clusters of `query`
+;; follow, or -1. Whole clusters only, case matters.
+(: (-> string string int))
+(defun (find-clusters text query)
+ (def hay (text-clusters text))
+ (def needle (text-clusters query))
+ (def last (- (vec-length hay) (vec-length needle)))
+ (defun (matches-at? i)
+ (let go ((j 0))
+ (cond
+ ((= j (vec-length needle)) #t)
+ ((= (vec-ref hay (+ i j)) (vec-ref needle j)) (go (+ j 1)))
+ (else #f))))
+ (let go ((i 0))
+ (cond
+ ((> i last) -1)
+ ((matches-at? i) i)
+ (else (go (+ i 1))))))
+
+;; The longest common prefix of `texts`, whole clusters only. Empty for no
+;; texts.
+(: (-> (Vec string) string))
+(defun (common-prefix texts)
+ (if (vec-empty? texts)
+ ""
+ (let ((first (text-clusters (vec-ref texts 0))))
+ (defun (shared other)
+ (let go ((k 0))
+ (if (and (< k (vec-length first)) (< k (vec-length other))
+ (= (vec-ref first k) (vec-ref other k)))
+ (go (+ k 1))
+ k)))
+ (def length
+ (let go ((i 0) (n (vec-length first)))
+ (if (= i (vec-length texts))
+ n
+ (go (+ i 1) (min n (shared (text-clusters (vec-ref texts i))))))))
+ (string-join (vec-slice first 0 length) ""))))
diff --git a/tests/async.bjo b/tests/async.bjo
new file mode 100644
index 0000000..a3e370b
--- /dev/null
+++ b/tests/async.bjo
@@ -0,0 +1,104 @@
+;; 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` in a bjoroutine: it suspends while it waits, other fibers
+;; run, and a deadline cancels it with the modes restored.
+;;
+;; bjo test tests/async.bjo
+;;
+;; The test runs itself again under `script`, 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)))
+
+;; ---- the child -------------------------------------------------------------
+
+(: (-> string))
+(defun (modes)
+ (match (run/output '(sh "-c" "stty -a (Box bool) int))
+(defbjo (ticks stop)
+ (let go ((n 0))
+ (if (box-ref stop)
+ n
+ (begin
+ (sync (timeout (milliseconds 50)))
+ (go (+ n 1))))))
+
+(: (-> LineEditor Terminal string))
+(defbjo (read-with-ticks ed term)
+ (def stop (make-box #f))
+ (def counter (bjo (ticks stop)))
+ (def result (line-read ed term "> "))
+ (box-set! stop #t)
+ (def n (match (sync (promise-join counter))
+ ((Ok n) n)
+ ((Err _) -1)))
+ (str (match result
+ ((LineText text) (str "read " (written text)))
+ (LineEof "eof")
+ (LineCancelled "cancelled"))
+ (if (> n 5) ", ticks ran" ", no ticks")))
+
+(: (-> LineEditor Terminal string))
+(defbjo (read-with-deadline ed term)
+ (match (try (with-deadline (milliseconds 400) (line-read ed term "> "))
+ #:catch (System.Exception))
+ ((Ok _) "not cancelled")
+ ((Err _) "cancelled")))
+
+(: (-> (Promise string) string))
+(defun (joined p)
+ (match (sync/blocking (promise-join p))
+ ((Ok text) text)
+ ((Err e) (str "raised " (.-Message e)))))
+
+(: (-> void))
+(defun (child)
+ (match (terminal-open)
+ ((Err e) (println (str "open: " (terminal-error-message e))))
+ ((Ok term)
+ (def ed (make-line-editor))
+ (println (str "first: " (joined (bjo (read-with-ticks ed term)))))
+ (println (str "deadline: " (joined (bjo (read-with-deadline ed term)))))
+ (println (str "after deadline: " (modes) ", raw? " (if (terminal-raw? term) "yes" "no")))
+ (println (str "next: " (joined (bjo (read-with-ticks ed term))))))))
+
+;; ---- the parent ------------------------------------------------------------
+
+(: (-> void))
+(defun (parent)
+ (def self (str "dotnet " (array-ref (command-line) 0)))
+ ;; The first line comes after 1.5 s of ticks. Nothing comes during the
+ ;; deadline. The last line comes after it.
+ (def keys "sleep 2.5; printf 'hello\\r'; sleep 2.5; printf 'again\\r'; sleep 1")
+ (def command (str "(" keys ") | script -qec '" 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 "line-read in a bjoroutine reads, and another fiber runs meanwhile"
+ (string-contains? out "first: read \"hello\", ticks ran"))
+ (expect-true "a deadline cancels line-read" (string-contains? out "deadline: cancelled"))
+ (expect-true "and the modes are restored" (string-contains? out "after deadline: cooked, raw? no"))
+ (expect-true "the next line-read works" (string-contains? out "next: read \"again\", ticks ran"))
+ (unless (string-contains? out "next: read")
+ (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/text.bjo b/tests/text.bjo
new file mode 100644
index 0000000..350dc74
--- /dev/null
+++ b/tests/text.bjo
@@ -0,0 +1,32 @@
+;; 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/.
+
+;; Clusters and widths of (bjoterm text).
+;;
+;; bjo test tests/text.bjo
+
+(import (std prelude))
+(import (std simpletest))
+(import (bjoterm text))
+
+(defun (main args)
+ (expect "e and a combining accent is one cluster" (vec-length (text-clusters "e\u{301}x")) 2)
+ (expect "an emoji with a skin tone is one cluster" (vec-length (text-clusters "👍🏽")) 1)
+ (expect "CR LF is one cluster" (vec-length (text-clusters "\r\n")) 1)
+ (expect "ASCII is 1 column" (text-width "abc") 3)
+ (expect "CJK is 2 columns" (text-width "中文") 4)
+ (expect "a combining accent is 0 columns" (text-width "e\u{301}") 1)
+ (expect "a zero-width joiner is 0 columns" (cluster-width "\u{200D}") 0)
+ (expect "the soft hyphen is 1 column" (cluster-width "\u{AD}") 1)
+ (expect "an emoji is 2 columns" (text-width "👍🏽") 2)
+ (expect "a flag is 2 columns" (text-width "🇸🇪") 2)
+ (expect "a control is ^X, 2 columns" (cluster-width "\u{1}") 2)
+ (expect "escape sequences in a prompt are 0 columns" (text-width "\u{1B}[1mλ>\u{1B}[0m ") 3)
+ (expect-true "a letter is part of a word" (word-cluster? "ä"))
+ (expect-true "a digit is part of a word" (word-cluster? "7"))
+ (expect-true "_ is part of a word" (word-cluster? "_"))
+ (expect-true "a bracket is not" (not (word-cluster? "(")))
+ (expect "find-clusters does not match inside a cluster" (find-clusters "e\u{301}" "e") -1)
+ (expect "common-prefix keeps whole clusters" (common-prefix ["e\u{301}a" "e\u{301}b"]) "e\u{301}")
+ 0)