Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987//! Prompt editor model: a text buffer with a grapheme-aligned cursor and word wrapping.
const std = @import("std");const vaxis = @import("vaxis");
/// Maximum number of visible prompt rows.pub const max_rows = 8;
/// Maximum number of pasted lines before using a paste marker.pub const max_paste_lines = 10;
/// Maximum number of bytes in a paste before using a paste marker.pub const max_paste_chars = 1000;
pub const Row = struct { /// Byte range of the row in the text buffer; the newline is not included. start: usize, end: usize,};
pub const Paste = struct { id: usize, label: []const u8, content: []const u8,};
pub const Editor = struct { gpa: std.mem.Allocator, /// Scratch space for the wrapping done while a key moves the cursor; reset per key. arena: std.heap.ArenaAllocator, text: std.ArrayList(u8) = .empty, pastes: std.ArrayList(Paste) = .empty, next_paste_id: usize = 1, /// Byte offset of the cursor; always on a grapheme boundary. cursor: usize = 0, /// First visible row when the wrapped text is taller than `max_rows`. scroll: usize = 0, /// How the terminal measures the display width of a grapheme. width_method: vaxis.gwidth.Method = .wcwidth,
pub fn init(gpa: std.mem.Allocator) Editor { return .{ .gpa = gpa, .arena = std.heap.ArenaAllocator.init(gpa) }; }
pub fn deinit(self: *Editor) void { self.arena.deinit(); self.text.deinit(self.gpa); for (self.pastes.items) |paste| { self.gpa.free(paste.label); self.gpa.free(paste.content); } self.pastes.deinit(self.gpa); }
pub fn pasteCount(self: *const Editor) usize { return self.pastes.items.len; }
pub fn handleKey(self: *Editor, key: vaxis.Key, width: u16) !void { _ = self.arena.reset(.retain_capacity); const arena = self.arena.allocator();
if (key.matches(vaxis.Key.backspace, .{})) { return self.backspace(); }
if (key.matches(vaxis.Key.delete, .{}) or key.matches('d', .{ .ctrl = true })) { return self.delete(); }
if (key.matches(vaxis.Key.left, .{}) or key.matches('b', .{ .ctrl = true })) { return self.left(); }
if (key.matches(vaxis.Key.right, .{}) or key.matches('f', .{ .ctrl = true })) { return self.right(); }
if (key.matches(vaxis.Key.home, .{}) or key.matches('a', .{ .ctrl = true })) { return self.home(arena, width); }
if (key.matches(vaxis.Key.end, .{}) or key.matches('e', .{ .ctrl = true })) { return self.endOfLine(arena, width); }
if (key.matches('b', .{ .alt = true }) or key.matches(vaxis.Key.left, .{ .alt = true })) { self.cursor = wordStart(self.text.items, self.cursor); return self.leavePaste(false); }
if (key.matches('f', .{ .alt = true }) or key.matches(vaxis.Key.right, .{ .alt = true })) { self.cursor = wordEnd(self.text.items, self.cursor); return self.leavePaste(true); }
if (key.matches(vaxis.Key.backspace, .{ .alt = true })) { return self.deleteRange(wordStart(self.text.items, self.cursor), self.cursor); }
if (key.matches('w', .{ .ctrl = true })) { return self.deleteRange(spacedWordStart(self.text.items, self.cursor), self.cursor); }
if (key.matches('d', .{ .alt = true })) { return self.deleteRange(self.cursor, wordEnd(self.text.items, self.cursor)); }
if (key.matches('u', .{ .ctrl = true })) { const start = lineStart(self.text.items, self.cursor); return self.deleteRange(if (start == self.cursor) self.cursor -| 1 else start, self.cursor); }
if (key.matches('k', .{ .ctrl = true })) { const end = lineEnd(self.text.items, self.cursor); const joined = end == self.cursor and end < self.text.items.len; return self.deleteRange(self.cursor, if (joined) end + 1 else end); }
if (key.matches(vaxis.Key.up, .{})) { return self.up(arena, width); }
if (key.matches(vaxis.Key.down, .{})) { return self.down(arena, width); }
if (key.text) |text| { try self.insert(text); } }
/// Inserts pasted text: normalizes newlines and tabs, and stores large pastes /// behind a marker that behaves as one unit. pub fn insertPaste(self: *Editor, raw: []const u8) !void { var normalized: std.ArrayList(u8) = .empty; defer normalized.deinit(self.gpa); var index: usize = 0; while (index < raw.len) : (index += 1) { switch (raw[index]) { '\r' => { try normalized.append(self.gpa, '\n'); if (index + 1 < raw.len and raw[index + 1] == '\n') { index += 1; } }, '\t' => try normalized.appendSlice(self.gpa, " "), else => try normalized.append(self.gpa, raw[index]), } } const text = normalized.items; const lines = std.mem.countScalar(u8, text, '\n') + @intFromBool(!std.mem.endsWith(u8, text, "\n")); if (lines <= max_paste_lines and text.len <= max_paste_chars) { return self.insert(text); } const id = self.next_paste_id; const label = if (lines > max_paste_lines) try std.fmt.allocPrint(self.gpa, "[paste #{d} +{d} lines]", .{ id, lines }) else try std.fmt.allocPrint(self.gpa, "[paste #{d} {d} chars]", .{ id, text.len }); errdefer self.gpa.free(label); try self.pastes.ensureUnusedCapacity(self.gpa, 1); try self.text.ensureUnusedCapacity(self.gpa, label.len); const content = try normalized.toOwnedSlice(self.gpa); self.pastes.appendAssumeCapacity(.{ .id = id, .label = label, .content = content }); self.text.insertSliceAssumeCapacity(self.cursor, label); self.cursor += label.len; self.next_paste_id += 1; }
/// Like `expand`, then clears the buffer. pub fn take(self: *Editor) ![]const u8 { const owned = try self.expand(); self.clear(); return owned; }
/// The text with each paste label replaced by its content. The caller owns it. pub fn expand(self: *const Editor) ![]const u8 { var out: std.ArrayList(u8) = .empty; errdefer out.deinit(self.gpa); const text = self.text.items; var offset: usize = 0; while (offset < text.len) { if (self.pasteStartingAt(offset)) |paste| { try out.appendSlice(self.gpa, paste.content); offset += paste.label.len; } else { const next = self.nextPasteOffset(offset); try out.appendSlice(self.gpa, text[offset..next]); offset = next; } } return out.toOwnedSlice(self.gpa); }
/// Byte offset of the first live paste label at or after `offset`. fn nextPasteOffset(self: *const Editor, offset: usize) usize { var next = self.text.items.len; for (self.pastes.items) |paste| { if (std.mem.indexOfPos(u8, self.text.items, offset, paste.label)) |index| { next = @min(next, index); } } return next; }
fn pasteStartingAt(self: *const Editor, offset: usize) ?Paste { for (self.pastes.items) |paste| { if (std.mem.startsWith(u8, self.text.items[offset..], paste.label)) { return paste; } } return null; }
/// Deletes the bytes from `start` to `end`, widened to whole markers, and moves /// the cursor to the start. Drops each paste whose marker is gone. fn deleteRange(self: *Editor, start: usize, end: usize) void { const from = if (self.markerAround(start)) |marker| marker.start else start; const to = if (self.markerAround(end)) |marker| marker.end else end; self.text.replaceRangeAssumeCapacity(from, to - from, &.{}); self.cursor = from; var index = self.pastes.items.len; while (index > 0) { index -= 1; const paste = self.pastes.items[index]; if (std.mem.indexOf(u8, self.text.items, paste.label) == null) { self.gpa.free(paste.label); self.gpa.free(paste.content); _ = self.pastes.orderedRemove(index); } } }
pub fn slice(self: *const Editor) []const u8 { return self.text.items; }
pub fn isEmpty(self: *const Editor) bool { return self.text.items.len == 0; }
pub fn clear(self: *Editor) void { self.text.clearRetainingCapacity(); for (self.pastes.items) |paste| { self.gpa.free(paste.label); self.gpa.free(paste.content); } self.pastes.clearRetainingCapacity(); self.next_paste_id = 1; self.cursor = 0; self.scroll = 0; }
/// Inserts text at the cursor and moves the cursor after it. pub fn insert(self: *Editor, bytes: []const u8) !void { try self.text.insertSlice(self.gpa, self.cursor, bytes); self.cursor += bytes.len; }
pub fn newline(self: *Editor) !void { try self.insert("\n"); }
pub fn backspace(self: *Editor) void { self.deleteRange(previousBoundary(self.text.items, self.cursor), self.cursor); }
pub fn delete(self: *Editor) void { self.deleteRange(self.cursor, nextBoundary(self.text.items, self.cursor)); }
pub fn left(self: *Editor) void { self.cursor = previousBoundary(self.text.items, self.cursor); self.leavePaste(false); }
pub fn right(self: *Editor) void { self.cursor = nextBoundary(self.text.items, self.cursor); self.leavePaste(true); }
pub fn home(self: *Editor, arena: std.mem.Allocator, width: usize) !void { const wrapped = try self.rows(arena, width); const row = rowOf(wrapped, self.cursor); self.cursor = wrapped[row].start; self.leavePaste(false); }
pub fn endOfLine(self: *Editor, arena: std.mem.Allocator, width: usize) !void { const wrapped = try self.rows(arena, width); const row = rowOf(wrapped, self.cursor); const line = wrapped[row]; // A soft-wrapped row ends where the next row starts, so stop on its last grapheme. const soft = row + 1 < wrapped.len and wrapped[row + 1].start == line.end; self.cursor = if (soft) previousBoundary(self.text.items, line.end) else line.end; self.leavePaste(true); }
pub fn up(self: *Editor, arena: std.mem.Allocator, width: usize) !void { try self.moveRow(arena, width, -1); self.leavePaste(false); }
pub fn down(self: *Editor, arena: std.mem.Allocator, width: usize) !void { try self.moveRow(arena, width, 1); self.leavePaste(true); }
/// Moves a cursor inside a live paste label to the label's end, or to its start when not `forward`. fn leavePaste(self: *Editor, forward: bool) void { const marker = self.markerAround(self.cursor) orelse return; self.cursor = if (forward) marker.end else marker.start; }
const Range = struct { start: usize, end: usize };
/// The live paste label that has `offset` strictly inside it. fn markerAround(self: *const Editor, offset: usize) ?Range { const text = self.text.items; for (self.pastes.items) |paste| { var start = std.mem.indexOf(u8, text, paste.label); while (start) |index| : (start = std.mem.indexOfPos(u8, text, index + 1, paste.label)) { const end = index + paste.label.len; if (offset > index and offset < end) { return .{ .start = index, .end = end }; } } } return null; }
/// Wrapped rows of the buffer at `width` columns. pub fn rows(self: *const Editor, arena: std.mem.Allocator, width: usize) ![]Row { return wrap(arena, self.text.items, width, self.width_method); }
/// Visible height, 1 to `max_rows`, keeping the cursor row in view. pub fn height(self: *Editor, arena: std.mem.Allocator, width: usize) !usize { const wrapped = try self.rows(arena, width); const rows_count = wrapped.len; const cursor_row = rowOf(wrapped, self.cursor); if (cursor_row < self.scroll) { self.scroll = cursor_row; } if (cursor_row >= self.scroll + max_rows) { self.scroll = cursor_row + 1 - max_rows; } const visible = @min(rows_count, max_rows); if (self.scroll > rows_count -| visible) { self.scroll = rows_count -| visible; } return visible; }
fn moveRow(self: *Editor, arena: std.mem.Allocator, width: usize, delta: i8) !void { const wrapped = try self.rows(arena, width); const current = rowOf(wrapped, self.cursor); const column = vaxis.gwidth.gwidth(self.text.items[wrapped[current].start..self.cursor], self.width_method); const target: isize = @as(isize, @intCast(current)) + delta; if (target < 0 or target >= @as(isize, @intCast(wrapped.len))) { return; } const row = wrapped[@intCast(target)]; self.cursor = offsetAtColumn(self.text.items[row.start..row.end], column, self.width_method) + row.start; }};
/// Wrapped rows of `text` at `width` columns: newlines, spaces, and hard breaks.pub fn wrap(arena: std.mem.Allocator, text: []const u8, width: usize, method: vaxis.gwidth.Method) ![]Row { var list: std.ArrayList(Row) = .empty; const columns = @max(width, 1); var start: usize = 0; while (true) { const limit = rowEnd(text, start, columns, method); try list.append(arena, .{ .start = start, .end = limit }); if (limit >= text.len) { // The cursor after a full row would sit past the right edge. if (limit > start and vaxis.gwidth.gwidth(text[start..limit], method) >= columns) { try list.append(arena, .{ .start = text.len, .end = text.len }); } break; } start = if (text[limit] == 0x0a) limit + 1 else limit; if (start >= text.len) { try list.append(arena, .{ .start = text.len, .end = text.len }); break; } } return list.items;}
pub fn rowOf(wrapped: []const Row, cursor: usize) usize { var index: usize = 0; for (wrapped, 0..) |row, i| { if (cursor >= row.start) { index = i; } } return index;}
/// Byte offset in `text` whose column is closest to `column` without passing it.fn offsetAtColumn(text: []const u8, column: usize, method: vaxis.gwidth.Method) usize { var columns: usize = 0; var offset: usize = 0; var iter = vaxis.unicode.graphemeIterator(text); while (iter.next()) |grapheme| { const bytes = grapheme.bytes(text); const width = vaxis.gwidth.gwidth(bytes, method); if (columns + width > column) { return offset; } columns += width; offset += bytes.len; } return offset;}
/// End of the row that starts at `start`: the next newline, the last space that/// fits, or a hard break when a single grapheme is wider than the row.fn rowEnd(text: []const u8, start: usize, width: usize, method: vaxis.gwidth.Method) usize { var columns: usize = 0; var offset = start; var break_at: ?usize = null; var iter = vaxis.unicode.graphemeIterator(text[start..]); while (iter.next()) |grapheme| { const bytes = grapheme.bytes(text[start..]); if (std.mem.eql(u8, bytes, "\n")) { return offset; } const glyph_width = vaxis.gwidth.gwidth(bytes, method); if (columns + glyph_width > width) { return break_at orelse if (offset == start) offset + bytes.len else offset; } columns += glyph_width; offset += bytes.len; if (std.mem.eql(u8, bytes, " ")) { break_at = offset; } } return offset;}
/// Readline word characters. Every non-ASCII byte counts as part of a word.fn isWordByte(byte: u8) bool { return byte == '_' or byte >= 0x80 or std.ascii.isAlphanumeric(byte);}
/// Start of the word before `from`, as readline's backward-word finds it.fn wordStart(text: []const u8, from: usize) usize { var index = from; while (index > 0 and !isWordByte(text[index - 1])) : (index -= 1) {} while (index > 0 and isWordByte(text[index - 1])) : (index -= 1) {} return alignToGrapheme(text, index, false);}
/// End of the word after `from`, as readline's forward-word finds it.fn wordEnd(text: []const u8, from: usize) usize { var index = from; while (index < text.len and !isWordByte(text[index])) : (index += 1) {} while (index < text.len and isWordByte(text[index])) : (index += 1) {} return alignToGrapheme(text, index, true);}
/// Start of the whitespace-delimited word before `from`, as readline's unix-word-rubout finds it.fn spacedWordStart(text: []const u8, from: usize) usize { var index = from; while (index > 0 and std.ascii.isWhitespace(text[index - 1])) : (index -= 1) {} while (index > 0 and !std.ascii.isWhitespace(text[index - 1])) : (index -= 1) {} return alignToGrapheme(text, index, false);}
/// Moves `offset` to the start of the grapheme that contains it, or to its end when `forward`.fn alignToGrapheme(text: []const u8, offset: usize, forward: bool) usize { var iter = vaxis.unicode.graphemeIterator(text); while (iter.next()) |grapheme| { const end = grapheme.start + grapheme.len; if (offset < end) { return if (forward and offset > grapheme.start) end else grapheme.start; } } return text.len;}
fn lineStart(text: []const u8, from: usize) usize { const newline = std.mem.lastIndexOfScalar(u8, text[0..from], '\n') orelse return 0; return newline + 1;}
fn lineEnd(text: []const u8, from: usize) usize { return std.mem.indexOfScalarPos(u8, text, from, '\n') orelse text.len;}
fn previousBoundary(text: []const u8, from: usize) usize { if (from == 0) { return 0; } var last_start: usize = 0; var offset: usize = 0; var iter = vaxis.unicode.graphemeIterator(text[0..from]); while (iter.next()) |grapheme| { last_start = offset; offset += grapheme.bytes(text[0..from]).len; } return last_start;}
fn nextBoundary(text: []const u8, from: usize) usize { if (from >= text.len) { return text.len; } var iter = vaxis.unicode.graphemeIterator(text[from..]); const grapheme = iter.next() orelse return text.len; return from + grapheme.bytes(text[from..]).len;}
const testing = std.testing;
test "typing inserts at the cursor" { var editor = Editor.init(testing.allocator); defer editor.deinit();
try editor.insert("ab"); try editor.insert("c"); try testing.expectEqualStrings("abc", editor.slice()); try testing.expectEqual(@as(usize, 3), editor.cursor); try editor.newline(); try editor.insert("d"); try testing.expectEqualStrings("abc\nd", editor.slice());}
test "backspace and delete remove one grapheme" { var editor = Editor.init(testing.allocator); defer editor.deinit();
try editor.insert("a\u{e9}b"); editor.backspace(); try testing.expectEqualStrings("a\u{e9}", editor.slice()); editor.backspace(); try testing.expectEqualStrings("a", editor.slice()); try testing.expectEqual(@as(usize, 1), editor.cursor);
editor.cursor = 0; editor.delete(); try testing.expectEqualStrings("", editor.slice());}
test "arrow keys move by grapheme" { var editor = Editor.init(testing.allocator); defer editor.deinit(); try editor.insert("a\u{e9}b");
editor.left(); try testing.expectEqual(@as(usize, 3), editor.cursor); editor.left(); try testing.expectEqual(@as(usize, 1), editor.cursor); editor.right(); try testing.expectEqual(@as(usize, 3), editor.cursor); editor.left(); editor.left(); editor.left(); try testing.expectEqual(@as(usize, 0), editor.cursor);}
fn press(editor: *Editor, codepoint: u21, mods: vaxis.Key.Modifiers) !void { try editor.handleKey(.{ .codepoint = codepoint, .mods = mods }, 80);}
test "alt+b and alt+f move by word, as do alt+left and alt+right" { var editor = Editor.init(testing.allocator); defer editor.deinit(); try editor.insert("foo bar_baz, qux");
try press(&editor, 'b', .{ .alt = true }); try testing.expectEqual(@as(usize, 13), editor.cursor); try press(&editor, vaxis.Key.left, .{ .alt = true }); try testing.expectEqual(@as(usize, 4), editor.cursor); try press(&editor, 'f', .{ .alt = true }); try testing.expectEqual(@as(usize, 11), editor.cursor); try press(&editor, vaxis.Key.right, .{ .alt = true }); try testing.expectEqual(@as(usize, 16), editor.cursor);}
test "word keys never split a grapheme" { var editor = Editor.init(testing.allocator); defer editor.deinit(); try editor.insert("a #\u{fe0f}\u{20e3}");
try press(&editor, 'b', .{ .alt = true }); try testing.expectEqual(@as(usize, 2), editor.cursor); try press(&editor, 'd', .{ .alt = true }); try testing.expectEqualStrings("a ", editor.slice());
try editor.insert("#\u{fe0f}\u{20e3}"); try press(&editor, vaxis.Key.backspace, .{ .alt = true }); try testing.expectEqualStrings("a ", editor.slice());}
test "word and line keys change nothing at the buffer edges" { var editor = Editor.init(testing.allocator); defer editor.deinit(); try editor.insert("ab");
try press(&editor, 'f', .{ .alt = true }); try press(&editor, 'd', .{ .alt = true }); try press(&editor, 'k', .{ .ctrl = true }); try testing.expectEqualStrings("ab", editor.slice()); try testing.expectEqual(@as(usize, 2), editor.cursor);
editor.cursor = 0; try press(&editor, 'b', .{ .alt = true }); try press(&editor, 'u', .{ .ctrl = true }); try press(&editor, 'w', .{ .ctrl = true }); try testing.expectEqualStrings("ab", editor.slice()); try testing.expectEqual(@as(usize, 0), editor.cursor);}
test "ctrl+a, ctrl+e, ctrl+b, ctrl+f and ctrl+d act as home, end, left, right and delete" { var editor = Editor.init(testing.allocator); defer editor.deinit(); try editor.insert("abc");
try press(&editor, 'a', .{ .ctrl = true }); try testing.expectEqual(@as(usize, 0), editor.cursor); try press(&editor, 'f', .{ .ctrl = true }); try testing.expectEqual(@as(usize, 1), editor.cursor); try press(&editor, 'd', .{ .ctrl = true }); try testing.expectEqualStrings("ac", editor.slice()); try press(&editor, 'e', .{ .ctrl = true }); try testing.expectEqual(@as(usize, 2), editor.cursor); try press(&editor, 'b', .{ .ctrl = true }); try testing.expectEqual(@as(usize, 1), editor.cursor);}
test "ctrl+w deletes back to a space, alt+backspace and alt+d delete a word" { var editor = Editor.init(testing.allocator); defer editor.deinit();
try editor.insert("foo bar.baz "); try press(&editor, 'w', .{ .ctrl = true }); try testing.expectEqualStrings("foo ", editor.slice());
try editor.insert("bar.baz"); try press(&editor, vaxis.Key.backspace, .{ .alt = true }); try testing.expectEqualStrings("foo bar.", editor.slice()); try testing.expectEqual(@as(usize, 8), editor.cursor);
editor.cursor = 3; try press(&editor, 'd', .{ .alt = true }); try testing.expectEqualStrings("foo.", editor.slice()); try testing.expectEqual(@as(usize, 3), editor.cursor);}
test "ctrl+k and ctrl+u delete to the line edge, and join lines at the edge" { var editor = Editor.init(testing.allocator); defer editor.deinit(); try editor.insert("one\ntwo three\nfour");
editor.cursor = 8; try press(&editor, 'k', .{ .ctrl = true }); try testing.expectEqualStrings("one\ntwo \nfour", editor.slice()); try press(&editor, 'k', .{ .ctrl = true }); try testing.expectEqualStrings("one\ntwo four", editor.slice()); try testing.expectEqual(@as(usize, 8), editor.cursor);
try press(&editor, 'u', .{ .ctrl = true }); try testing.expectEqualStrings("one\nfour", editor.slice()); try testing.expectEqual(@as(usize, 4), editor.cursor); try press(&editor, 'u', .{ .ctrl = true }); try testing.expectEqualStrings("onefour", editor.slice()); try testing.expectEqual(@as(usize, 3), editor.cursor);}
test "word and line keys treat a marker as one word" { var editor = Editor.init(testing.allocator); defer editor.deinit(); try editor.insert("ab "); try editor.insertPaste("a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk"); try editor.insert(" cd"); const marker_end = editor.slice().len - 3;
try press(&editor, 'b', .{ .alt = true }); try press(&editor, 'b', .{ .alt = true }); try testing.expectEqual(@as(usize, 3), editor.cursor); try press(&editor, 'f', .{ .alt = true }); try testing.expectEqual(marker_end, editor.cursor);
try press(&editor, 'w', .{ .ctrl = true }); try testing.expectEqualStrings("ab cd", editor.slice()); try testing.expectEqual(@as(usize, 0), editor.pasteCount());
try editor.insertPaste("a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk"); editor.cursor = 3; try press(&editor, 'd', .{ .alt = true }); try testing.expectEqualStrings("ab cd", editor.slice()); try testing.expectEqual(@as(usize, 0), editor.pasteCount());
try editor.insertPaste("a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk"); try press(&editor, 'u', .{ .ctrl = true }); try testing.expectEqualStrings(" cd", editor.slice()); try testing.expectEqual(@as(usize, 0), editor.pasteCount());}
test "a deletion next to a marker keeps its paste" { var editor = Editor.init(testing.allocator); defer editor.deinit(); try editor.insertPaste("a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk"); try editor.insert(" cd");
try press(&editor, 'w', .{ .ctrl = true }); editor.backspace(); try testing.expectEqual(@as(usize, 1), editor.pasteCount());
const taken = try editor.take(); defer testing.allocator.free(taken); try testing.expectEqualStrings("a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk", taken);}
test "home and end move within the wrapped row" { var arena_state = std.heap.ArenaAllocator.init(testing.allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); var editor = Editor.init(testing.allocator); defer editor.deinit(); try editor.insert("one two three");
try editor.home(arena, 7); try testing.expectEqual(@as(usize, 8), editor.cursor); try editor.endOfLine(arena, 7); try testing.expectEqual(@as(usize, 13), editor.cursor);}
test "up and down move between wrapped rows" { var arena_state = std.heap.ArenaAllocator.init(testing.allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); var editor = Editor.init(testing.allocator); defer editor.deinit(); try editor.insert("one two three");
editor.cursor = 2; try editor.down(arena, 7); try testing.expectEqual(@as(usize, 6), editor.cursor); try editor.up(arena, 7); try testing.expectEqual(@as(usize, 2), editor.cursor);}
test "the editor wraps by display width and grows to eight rows" { var arena_state = std.heap.ArenaAllocator.init(testing.allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); var editor = Editor.init(testing.allocator); defer editor.deinit(); try editor.insert("aaaa bbbb cccc");
try testing.expectEqual(@as(usize, 2), (try editor.rows(arena, 10)).len); try testing.expectEqual(@as(usize, 2), try editor.height(arena, 10));
try editor.insert("\n1\n2\n3\n4\n5\n6\n7"); try testing.expectEqual(@as(usize, 8), try editor.height(arena, 10)); try testing.expect(editor.scroll > 0);}
test "take returns the text and clears the buffer" { var editor = Editor.init(testing.allocator); defer editor.deinit(); try editor.insert("hello"); const taken = try editor.take(); defer testing.allocator.free(taken);
try testing.expectEqualStrings("hello", taken); try testing.expect(editor.isEmpty()); try testing.expectEqual(@as(usize, 0), editor.cursor);}
test "take expands the paste markers so the agent and the user see the same text" { var editor = Editor.init(testing.allocator); defer editor.deinit();
try editor.insertPaste("a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\nl"); try editor.insert("!");
const taken = try editor.take(); defer testing.allocator.free(taken);
try testing.expectEqualStrings("a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\nl!", taken); try testing.expect(editor.isEmpty()); try testing.expectEqual(@as(usize, 0), editor.pasteCount());}
test "end stops at the last grapheme of a soft-wrapped row" { var arena_state = std.heap.ArenaAllocator.init(testing.allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); var editor = Editor.init(testing.allocator); defer editor.deinit(); try editor.insert("one two three");
editor.cursor = 2; try editor.endOfLine(arena, 7); try testing.expectEqual(@as(usize, 3), editor.cursor);
editor.clear(); try editor.insert("abcd"); editor.cursor = 0; try editor.endOfLine(arena, 4); try testing.expectEqual(@as(usize, 3), editor.cursor);}
test "a twenty line prompt keeps eight visible rows and follows the cursor" { var arena_state = std.heap.ArenaAllocator.init(testing.allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); var editor = Editor.init(testing.allocator); defer editor.deinit(); for (0..20) |line| { try editor.insert("l"); try editor.insert(try std.fmt.allocPrint(arena, "{d}", .{line})); if (line < 19) { try editor.newline(); } }
try testing.expectEqual(@as(usize, 8), try editor.height(arena, 20)); // The cursor sits on the last row, so the window shows the last eight rows. try testing.expectEqual(@as(usize, 12), editor.scroll);
editor.cursor = 0; try testing.expectEqual(@as(usize, 8), try editor.height(arena, 20)); try testing.expectEqual(@as(usize, 0), editor.scroll);}
test "take expands adjacent markers" { var editor = Editor.init(testing.allocator); defer editor.deinit();
try editor.insertPaste("a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk"); try editor.insertPaste("0\n1\n2\n3\n4\n5\n6\n7\n8\n9\nX");
const taken = try editor.take(); defer testing.allocator.free(taken); try testing.expectEqualStrings("a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk0\n1\n2\n3\n4\n5\n6\n7\n8\n9\nX", taken);}
test "take keeps marker look-alikes that are not live pastes" { var editor = Editor.init(testing.allocator); defer editor.deinit();
try editor.insertPaste("a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk"); try editor.insert("[paste #9 +11 lines]");
const taken = try editor.take(); defer testing.allocator.free(taken); try testing.expectEqualStrings("a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk[paste #9 +11 lines]", taken);}
test "a large paste becomes one marker and expands on submit" { var editor = Editor.init(testing.allocator); defer editor.deinit();
try editor.insertPaste("a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\nl"); try testing.expectEqualStrings("[paste #1 +12 lines]", editor.slice()); try testing.expectEqual(@as(usize, 1), editor.pasteCount());
const taken = try editor.take(); defer testing.allocator.free(taken); try testing.expectEqualStrings("a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\nl", taken); try testing.expectEqual(@as(usize, 0), editor.pasteCount());}
test "a trailing newline does not count as a pasted line" { var editor = Editor.init(testing.allocator); defer editor.deinit();
try editor.insertPaste("a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\nl\n"); try testing.expectEqualStrings("[paste #1 +12 lines]", editor.slice());}
test "a small paste is inserted literally with normalized newlines and tabs" { var editor = Editor.init(testing.allocator); defer editor.deinit();
try editor.insertPaste("a\r\nb\rc\td"); try testing.expectEqualStrings("a\nb\nc d", editor.slice()); try testing.expectEqual(@as(usize, 0), editor.pasteCount());}
test "a long single line paste uses a character marker" { var editor = Editor.init(testing.allocator); defer editor.deinit();
const long = try testing.allocator.alloc(u8, 1001); defer testing.allocator.free(long); @memset(long, 'x'); try editor.insertPaste(long); try testing.expectEqualStrings("[paste #1 1001 chars]", editor.slice());}
test "backspace removes a marker and its paste as one unit" { var editor = Editor.init(testing.allocator); defer editor.deinit();
try editor.insertPaste("a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk"); editor.backspace(); try testing.expectEqualStrings("", editor.slice()); try testing.expectEqual(@as(usize, 0), editor.pasteCount());
const taken = try editor.take(); defer testing.allocator.free(taken); try testing.expectEqualStrings("", taken);}
test "the cursor jumps over a marker" { var editor = Editor.init(testing.allocator); defer editor.deinit();
try editor.insertPaste("a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk"); editor.left(); try testing.expectEqual(@as(usize, 0), editor.cursor); editor.right(); try testing.expectEqualStrings("[paste #1 +11 lines]", editor.slice()); try testing.expectEqual(@as(usize, 20), editor.cursor);}
test "home, end, up and down never stop inside a marker" { var arena_state = std.heap.ArenaAllocator.init(testing.allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); var editor = Editor.init(testing.allocator); defer editor.deinit(); try editor.insert("ab"); try editor.insertPaste("a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk"); // At ten columns the marker wraps over three rows: "ab[paste ", "#1 +11 ", "lines]". const start = 2; const end = editor.slice().len;
try editor.home(arena, 10); try testing.expectEqual(@as(usize, start), editor.cursor);
editor.cursor = end; try editor.up(arena, 10); try testing.expectEqual(@as(usize, start), editor.cursor);
editor.cursor = 0; try editor.endOfLine(arena, 10); try testing.expectEqual(end, editor.cursor);
editor.cursor = 0; try editor.down(arena, 10); try testing.expectEqual(end, editor.cursor);
try editor.insert("!"); const taken = try editor.take(); defer testing.allocator.free(taken); try testing.expectEqualStrings("aba\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk!", taken);}
test "paste ids count up and restart after submit" { var editor = Editor.init(testing.allocator); defer editor.deinit();
try editor.insertPaste("a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk"); const second = try testing.allocator.dupe(u8, "[paste #2 +11 lines]"); defer testing.allocator.free(second); try editor.insertPaste("0\n1\n2\n3\n4\n5\n6\n7\n8\n9\nX"); try testing.expect(std.mem.indexOf(u8, editor.slice(), "[paste #1 +11 lines]") != null); try testing.expect(std.mem.indexOf(u8, editor.slice(), second) != null);
const display = try editor.take(); testing.allocator.free(display); try editor.insertPaste("a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk"); try testing.expectEqualStrings("[paste #1 +11 lines]", editor.slice());}
fn pasteTwice(gpa: std.mem.Allocator) !void { var editor = Editor.init(gpa); defer editor.deinit(); try editor.insertPaste("a\nb"); try editor.insertPaste("a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk");}
test "a paste that runs out of memory frees what it allocated" { try testing.checkAllAllocationFailures(testing.allocator, pasteTwice, .{});}