diff options
| author | Gabriel Schneider <[email protected]> | 2026-10-24 13:59:21 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-10-24 15:56:58 -0300 |
| commit | ce6ba3d8a9e1f5c1e31892639049317f6a27b1bc (patch) | |
| tree | 939446ce2794e49ba950fa29acfa69292485288f /src/Tables.zig | |
| parent | 05d03191a8bfdb7c76176a91fddd97f389ab6dc3 (diff) | |
| download | pardes-ce6ba3d8a9e1f5c1e31892639049317f6a27b1bc.tar.gz pardes-ce6ba3d8a9e1f5c1e31892639049317f6a27b1bc.zip | |
Tables 1/3: a markdown file's pipe tables laid out in their rows, cells padded with virtual width before a byte (a tab's extra cells, not a parallel map): File.rowPads under displayOffset/displayEndOffset/byteAtRowDisplay, fillBody, recolorSyntax, the pointer sweep, j/k; tree-sitter-markdown as the detector's oracle
Diffstat (limited to 'src/Tables.zig')
| -rw-r--r-- | src/Tables.zig | 641 |
1 files changed, 641 insertions, 0 deletions
diff --git a/src/Tables.zig b/src/Tables.zig new file mode 100644 index 00000000..ca4a4b57 --- /dev/null +++ b/src/Tables.zig @@ -0,0 +1,641 @@ +//! A markdown file's pipe tables (GFM), laid out in their own rows. Every +//! byte of a table stays in its row as the text it is: B1, B2, B3 and the +//! chords work on it as on any text, and nothing is drawn over it. What +//! changes is the width some bytes take. A cell narrower than its column +//! is given the cells it lacks as virtual width, a *pad*, before one of its +//! bytes (the `|` that ends it, or for a right-aligned column the first +//! byte after the `|` that starts it), so every row's `|` of a column falls +//! on the same screen column whatever the source spacing. A pad is to the +//! byte it stands before what a tab's extra cells are to the tab: drawn as +//! blanks, every one of them maps back to that byte (a click there puts +//! the caret before it), and the caret before that byte is drawn after the +//! pad, against its glyph. +//! +//! The pads are the only mapping. File.zig's pane-aware column functions +//! (`displayOffset`, `displayEndOffset`, `byteAtRowDisplay`) and the row +//! walks that draw a body (`fillBody`, `recolorSyntax`) add them, so the +//! caret, every selection, a click and a Look map between a cell's x and +//! its byte as they map a tab's. The look itself (`paint`: the `|` as rules, +//! the delimiter row as one, the header bold) restyles cells that are +//! there; it moves nothing. +//! +//! Which lines are tables is found by lines, as tree-sitter-markdown's +//! scanner finds a `pipe_table` (its PIPE_TABLE_START: a header row's cells +//! counted by its pipes, a delimiter row of `:?-+:?` cells, the same count), +//! once per revision of the text, over the whole text: the highlighter +//! parses only the lines around the view, which start mid-table as soon as +//! a long one is scrolled, and fenced code is known only from the top. The +//! grammar is the oracle in a test ("tables are the pipe_tables tree-sitter +//! finds"). +const std = @import("std"); +const panes = @import("panes.zig"); +const pardes = @import("pardes.zig"); +const colors = @import("colors.zig"); +const Surface = @import("surface.zig").Surface; +const Pardes = pardes.Pardes; +const Pane = panes.Pane; +const File = panes.File; + +const Tables = @This(); + +pub const Align = enum(u2) { left, right, center }; + +pub const Table = struct { + /// The header row's line; the delimiter row is the next. + first: u32, + /// One past the last row's line. + end: u32, + /// Where its columns' widths and alignments start in `widths`/`aligns`. + col0: u32, + /// Columns: the most cells any row ends with a `|`. + cols: u16, + /// The widest indentation before a leading `|`, in cells. + lead: u16, + /// The widest row laid out, in cells: a table wider than a wrapping + /// pane is shown as its source (`File.rowPads`). + width: u32, +}; + +/// `cells` of virtual width before the byte at `at` of its line. +pub const Pad = struct { at: u32, cells: u16 }; + +/// Columns past this many are not aligned (their pipes take no pad). +pub const max_cols = 64; +/// A centred column pads both sides of a cell, and a leading `|` its indent. +pub const max_pads = 2 * max_cols + 1; + +/// The text these tables are of: its revision, where it is and how long. +revision: ?u32 = null, +content: usize = 0, +len: usize = 0, +list: std.ArrayList(Table) = .empty, +widths: std.ArrayList(u16) = .empty, +aligns: std.ArrayList(Align) = .empty, + +pub fn deinit(t: *Tables, gpa: std.mem.Allocator) void { + t.list.deinit(gpa); + t.widths.deinit(gpa); + t.aligns.deinit(gpa); + t.* = .{}; +} + +/// Whether these tables are of `f`'s text as it is now. +pub fn current(t: *const Tables, f: *const File.State) bool { + return t.revision == f.revision and t.content == @intFromPtr(f.content.ptr) and t.len == f.content.len; +} + +/// The table `line` is a row of, if any. +pub fn find(t: *const Tables, line: usize) ?*const Table { + const items = t.list.items; + var lo: usize = 0; + var hi: usize = items.len; + while (lo < hi) { + const mid = (lo + hi) / 2; + if (items[mid].end <= line) lo = mid + 1 else hi = mid; + } + if (lo < items.len and items[lo].first <= line) return &items[lo]; + return null; +} + +/// Find the tables of `f`'s text again unless they are of it already. Only +/// a markdown file has any; on no memory there are none (the text is shown +/// as it is). +pub fn ensure(t: *Tables, gpa: std.mem.Allocator, f: *const File.State) void { + if (t.current(f)) return; + t.revision = f.revision; + t.content = @intFromPtr(f.content.ptr); + t.len = f.content.len; + t.list.clearRetainingCapacity(); + if (f.output != null or f.mini != null or !isMarkdown(f.path)) return; + scan(t, gpa, f.content) catch { + t.list.clearRetainingCapacity(); + t.widths.clearRetainingCapacity(); + t.aligns.clearRetainingCapacity(); + }; +} + +pub fn isMarkdown(path: []const u8) bool { + return std.ascii.endsWithIgnoreCase(path, ".md") or std.ascii.endsWithIgnoreCase(path, ".markdown"); +} + +/// One line of the text: its bytes and its number. +const Line = struct { text: []const u8, start: usize, n: u32 }; + +fn lineAt(content: []const u8, start: usize, n: u32) ?Line { + if (start > content.len) return null; + const end = std.mem.indexOfScalarPos(u8, content, start, '\n') orelse content.len; + const text = content[start..end]; + return .{ .text = if (text.len > 0 and text[text.len - 1] == '\r') text[0 .. text.len - 1] else text, .start = start, .n = n }; +} + +fn nextLine(content: []const u8, l: Line) ?Line { + const nl = std.mem.indexOfScalarPos(u8, content, l.start, '\n') orelse return null; + return lineAt(content, nl + 1, l.n + 1); +} + +fn indentOf(text: []const u8) usize { + var i: usize = 0; + while (i < text.len and (text[i] == ' ' or text[i] == '\t')) i += 1; + return i; +} + +fn blank(text: []const u8) bool { + return indentOf(text) == text.len; +} + +/// A fence's opener (```` ``` ```` or `~~~`, three or more, up to three +/// spaces in): its character and length. +const Fence = struct { ch: u8, len: usize }; + +fn fenceOf(text: []const u8) ?Fence { + const in = indentOf(text); + if (in > 3 or in >= text.len) return null; + const ch = text[in]; + if (ch != '`' and ch != '~') return null; + var n: usize = 0; + while (in + n < text.len and text[in + n] == ch) n += 1; + if (n < 3) return null; + // A backtick fence's info string has no backtick (CommonMark 4.5). + if (ch == '`' and std.mem.indexOfScalar(u8, text[in + n ..], '`') != null) return null; + return .{ .ch = ch, .len = n }; +} + +fn closes(text: []const u8, open: Fence) bool { + const f = fenceOf(text) orelse return false; + return f.ch == open.ch and f.len >= open.len and blank(text[indentOf(text) + f.len ..]); +} + +/// A line that ends a table's rows by starting a block of its own (what +/// the grammar's paragraph_interrupt_symbols are): a heading, a fence, a +/// quote, a list item, a thematic break, HTML. +fn interrupts(text: []const u8) bool { + const in = indentOf(text); + if (in > 3 or in >= text.len) return false; + const rest = text[in..]; + if (fenceOf(text) != null) return true; + switch (rest[0]) { + '#', '>', '<' => return true, + '-', '*', '+' => { + if (rest.len == 1 or rest[1] == ' ' or rest[1] == '\t') return true; + // A thematic break: three or more of one of -*_ and spaces. + var n: usize = 0; + for (rest) |b| { + if (b == rest[0]) n += 1 else if (b != ' ' and b != '\t') return false; + } + return n >= 3; + }, + '0'...'9' => { + var i: usize = 0; + while (i < rest.len and i < 9 and std.ascii.isDigit(rest[i])) i += 1; + return i < rest.len and (rest[i] == '.' or rest[i] == ')') and (i + 1 == rest.len or rest[i + 1] == ' '); + }, + else => return false, + } +} + +/// A row's unescaped pipes, in order, and whether the row starts with one +/// (after its indentation) and ends with one (before trailing blanks). +const Pipes = struct { + at: [max_cols + 2]u32 = undefined, + n: usize = 0, + /// Pipes past `at`'s room: counted, not kept. + more: usize = 0, + leading: bool = false, + trailing: bool = false, + + fn of(text: []const u8) Pipes { + var p: Pipes = .{}; + const in = indentOf(text); + p.leading = in < text.len and text[in] == '|'; + var last_ink: usize = text.len; + var i: usize = 0; + while (i < text.len) : (i += 1) { + const b = text[i]; + if (b == '\\' and i + 1 < text.len and std.ascii.isPrint(text[i + 1]) and !std.ascii.isAlphanumeric(text[i + 1]) and text[i + 1] != ' ') { + last_ink = i + 1; + i += 1; + continue; + } + if (b == '|') { + if (p.n < p.at.len) { + p.at[p.n] = @intCast(i); + p.n += 1; + } else p.more += 1; + } + if (b != ' ' and b != '\t') last_ink = i; + } + p.trailing = p.n > 0 and last_ink == p.at[p.n - 1] and p.more == 0; + return p; + } + + /// The cells the grammar counts: the pipes after a leading one, plus + /// the last cell when no pipe ends the row. + fn cells(p: *const Pipes) usize { + const pipes = p.n + p.more - @intFromBool(p.leading); + return pipes + @intFromBool(!p.trailing); + } + + /// The pipe that ends cell `k` (the pipes after a leading one). + fn end(p: *const Pipes, k: usize) ?usize { + const i = k + @intFromBool(p.leading); + return if (i < p.n) p.at[i] else null; + } + + /// Where cell `k` starts: after the pipe before it, or after the + /// indentation when it is the first and no pipe leads. + fn start(p: *const Pipes, k: usize) usize { + if (k == 0 and !p.leading) return 0; + return p.at[k - @intFromBool(!p.leading)] + 1; + } +}; + +/// A delimiter row's cells (`:?-+:?` between pipes), or null if `text` is +/// none: as the scanner reads one after a header. +fn delimiterCells(text: []const u8, out: *[max_cols]Align) ?usize { + var i = indentOf(text); + if (i > 3) return null; + var cells: usize = 0; + var pipes: usize = 0; + if (i < text.len and text[i] == '|') { + i += 1; + pipes += 1; + } + while (true) { + while (i < text.len and (text[i] == ' ' or text[i] == '\t')) i += 1; + if (i >= text.len) break; + if (text[i] == '|') { + cells += 1; + pipes += 1; + i += 1; + continue; + } + var left = false; + if (text[i] == ':') { + left = true; + i += 1; + if (i >= text.len or text[i] != '-') return null; + } + var dashes: usize = 0; + while (i < text.len and text[i] == '-') : (i += 1) dashes += 1; + if (dashes == 0) return null; + var right = false; + if (i < text.len and text[i] == ':') { + right = true; + i += 1; + } + if (cells < max_cols) out[cells] = if (left and right) .center else if (right) .right else .left; + cells += 1; + while (i < text.len and (text[i] == ' ' or text[i] == '\t')) i += 1; + if (i >= text.len) break; + if (text[i] != '|') return null; + pipes += 1; + i += 1; + } + if (pipes == 0) return null; + return cells; +} + +/// The display width of a cell's bytes; ASCII is a cell a byte. +fn widthOf(text: []const u8) usize { + for (text) |b| if (b < 0x20 or b >= 0x7f) return File.displayWidth(text); + return text.len; +} + +/// Find the tables of `content`, in place of the ones there were. +pub fn scan(t: *Tables, gpa: std.mem.Allocator, content: []const u8) !void { + t.list.clearRetainingCapacity(); + t.widths.clearRetainingCapacity(); + t.aligns.clearRetainingCapacity(); + var fence: ?Fence = null; + var prev_blank = true; + var line = lineAt(content, 0, 0); + while (line) |l| { + const following = nextLine(content, l); + if (fence) |open| { + if (closes(l.text, open)) fence = null; + prev_blank = fence == null; + line = following; + continue; + } + if (fenceOf(l.text)) |open| { + fence = open; + prev_blank = false; + line = following; + continue; + } + const is_blank = blank(l.text); + var aligns: [max_cols]Align = undefined; + // A header starts a block: after a blank line, a heading or a fence + // (the grammar tries PIPE_TABLE_START where a paragraph could start). + if (!is_blank and prev_blank and indentOf(l.text) <= 3 and std.mem.indexOfScalar(u8, l.text, '|') != null) { + if (following) |delimiter| if (delimiterCells(delimiter.text, &aligns)) |count| { + const header = Pipes.of(l.text); + // A header's one pipe may not be its leading one alone, + // unless one ends it too (`| a |`, not `| a`). + const lone = header.n + header.more == @intFromBool(header.leading) and !(header.leading and header.trailing); + if (!lone and header.cells() == count) { + const last = try t.add(gpa, content, l, delimiter, aligns[0..@min(count, max_cols)]); + line = nextLine(content, last); + prev_blank = false; + continue; + } + }; + } + // A heading line ends a block too: a header may follow it. + prev_blank = is_blank or std.mem.startsWith(u8, l.text[@min(indentOf(l.text), l.text.len)..], "#"); + line = following; + } +} + +/// Take the table whose header is `header`: its rows, its columns' widths +/// and its width. Returns its last row's line. +fn add(t: *Tables, gpa: std.mem.Allocator, content: []const u8, header: Line, delimiter: Line, aligns: []const Align) !Line { + var last = delimiter; + while (nextLine(content, last)) |row| { + if (blank(row.text) or interrupts(row.text)) break; + last = row; + } + const col0: u32 = @intCast(t.widths.items.len); + var table: Table = .{ .first = header.n, .end = last.n + 1, .col0 = col0, .cols = 0, .lead = 0, .width = 0 }; + // Widths: each column's widest cell, the cell's bytes up to the pipe + // that ends it; a row's last cell with no pipe after it aligns nothing. + var row: ?Line = header; + while (row) |r| : (row = if (r.n == last.n) null else nextLine(content, r)) { + const pipes = Pipes.of(r.text); + if (pipes.leading) table.lead = @max(table.lead, @as(u16, @intCast(@min(widthOf(r.text[0..pipes.at[0]]), std.math.maxInt(u16))))); + var k: usize = 0; + while (k < max_cols) : (k += 1) { + const stop = pipes.end(k) orelse break; + const w: u16 = @intCast(@min(widthOf(r.text[pipes.start(k)..stop]), std.math.maxInt(u16))); + if (k >= table.cols) { + try t.widths.append(gpa, w); + try t.aligns.append(gpa, if (k < aligns.len) aligns[k] else .left); + table.cols += 1; + } else t.widths.items[col0 + k] = @max(t.widths.items[col0 + k], w); + } + } + // The width: each row laid out, its source width and its pads. + row = header; + var buf: [max_pads]Pad = undefined; + while (row) |r| : (row = if (r.n == last.n) null else nextLine(content, r)) { + var width = widthOf(r.text); + for (t.padsOf(&table, r.text, &buf)) |pad| width += pad.cells; + table.width = @max(table.width, @as(u32, @intCast(@min(width, std.math.maxInt(u32))))); + } + try t.list.append(gpa, table); + return last; +} + +/// The pads of one of `table`'s rows, by byte, in order. No pad is ever at +/// byte 0: a row is drawn from its first byte, so there is no cell before +/// it to give. +pub fn padsOf(t: *const Tables, table: *const Table, text: []const u8, out: *[max_pads]Pad) []Pad { + const pipes = Pipes.of(text); + var n: usize = 0; + if (pipes.leading and pipes.at[0] > 0) { + const w = widthOf(text[0..pipes.at[0]]); + if (w < table.lead) { + out[n] = .{ .at = pipes.at[0], .cells = @intCast(table.lead - w) }; + n += 1; + } + } + var k: usize = 0; + while (k < table.cols) : (k += 1) { + const stop = pipes.end(k) orelse break; + const from = pipes.start(k); + const w = widthOf(text[from..stop]); + const want = t.widths.items[table.col0 + k]; + if (w >= want) continue; + const missing: u16 = @intCast(want - w); + // The first cell with no leading pipe starts at byte 0: it pads at + // its end, whatever its alignment. + const how: Align = if (from == 0) .left else t.aligns.items[table.col0 + k]; + const before: u16 = switch (how) { + .left => 0, + .right => missing, + .center => missing / 2, + }; + // An empty cell's start is its pipe: one pad there. + if (before > 0 and from < stop) { + out[n] = .{ .at = @intCast(from), .cells = before }; + n += 1; + } + const after = if (from < stop) missing - before else missing; + if (after > 0) { + out[n] = .{ .at = @intCast(stop), .cells = after }; + n += 1; + } + } + return out[0..n]; +} + +/// The cells of virtual width between byte `from` (excluded: its pad is +/// before the row's first shown byte) and byte `to` (included: its pad is +/// before its glyph), negative when `to` is before `from`. +pub fn between(pads: []const Pad, from: usize, to: usize) i32 { + const lo = @min(from, to); + const hi = @max(from, to); + var sum: i32 = 0; + for (pads) |pad| { + if (pad.at > hi) break; + if (pad.at > lo) sum += pad.cells; + } + return if (to >= from) sum else -sum; +} + +/// The byte at display column `col` of a row shown from byte `from`, its +/// pads counted: a pad's cells are its byte's, as a tab's are the tab's. +/// Past the end, a virtual column a cell (File.rawAtDisplay). +pub fn byteAt(text: []const u8, pads: []const Pad, from_raw: usize, col: usize) usize { + if (from_raw >= text.len) return from_raw +| col; + var at = @import("modal.zig").graphemeStart(text, from_raw); + var k: usize = 0; + while (k < pads.len and pads[k].at <= at) k += 1; + var used: usize = 0; + while (at < text.len) { + if (k < pads.len and pads[k].at == at) { + used += pads[k].cells; + k += 1; + if (col < used) return at; + } + const end = @import("modal.zig").nextGrapheme(text, at); + used += File.graphemeDisplayWidth(text[at..end]); + if (col < used) return at; + at = end; + } + return text.len + (col - used); +} + +// ---- tests ---- + +const testing = std.testing; +const config = @import("config.zig"); +const Key = pardes.Key; + +const sample = + "# Fruit\n" ++ + "\n" ++ + "| name | qty | note |\n" ++ + "|:-----|----:|:----:|\n" ++ + "| apple | 3 | red |\n" ++ + "| kiwi | 12 | small and fuzzy |\n" ++ + "| fig || |\n" ++ + "\n" ++ + "after\n"; + +/// A pane on `content` as a markdown file, drawn once. +fn testPane(p: *Pardes, content: []const u8, frame: std.mem.Allocator) !*Pane { + const pane = try p.setTestFile(content); + p.gpa.free(pane.file.?.path); + pane.file.?.path = try p.gpa.dupe(u8, "/notes.md"); + _ = try p.render(frame); + return pane; +} + +test "tables: a pipe table's columns, alignments and pads, by line" { + var t: Tables = .{}; + defer t.deinit(testing.allocator); + try t.scan(testing.allocator, sample); + try testing.expectEqual(@as(usize, 1), t.list.items.len); + const table = t.list.items[0]; + try testing.expectEqual(@as(u32, 2), table.first); + try testing.expectEqual(@as(u32, 7), table.end); + try testing.expectEqualSlices(u16, &.{ 7, 5, 17 }, t.widths.items); + try testing.expectEqualSlices(Align, &.{ .left, .right, .center }, t.aligns.items); + // `| fig || |`: the first cell short by 2 (left: before its `|`), the + // empty second by 5 (one pad at its pipe), the third by 16 (centred). + var buf: [max_pads]Pad = undefined; + const fig = "| fig || |"; + try testing.expectEqualSlices(Pad, &.{ + .{ .at = 6, .cells = 2 }, .{ .at = 7, .cells = 5 }, .{ .at = 8, .cells = 8 }, .{ .at = 9, .cells = 8 }, + }, t.padsOf(&table, fig, &buf)); + // `| apple | 3 | red |`: right-aligned 3 pads before its first byte. + try testing.expectEqualSlices(Pad, &.{ + .{ .at = 9, .cells = 2 }, .{ .at = 13, .cells = 6 }, .{ .at = 18, .cells = 6 }, + }, t.padsOf(&table, "| apple | 3 | red |", &buf)); + // Every row laid out is one width: the table's. + try testing.expectEqual(@as(u32, 1 + 7 + 1 + 5 + 1 + 17 + 1), table.width); + // Not tables: a fence's rows, counts that differ, a delimiter alone. + for ([_][]const u8{ + "```\n| a | b |\n|---|---|\n```\n", + "| a | b |\n|---|\n", + "|---|---|\n", + "| a\n|---\n", + }) |text| { + try t.scan(testing.allocator, text); + try testing.expectEqual(@as(usize, 0), t.list.items.len); + } +} + +test "tables: every byte's cell maps back to it, and every pad cell to the byte after it" { + var t: Tables = .{}; + defer t.deinit(testing.allocator); + try t.scan(testing.allocator, sample); + const table = &t.list.items[0]; + var lines = std.mem.splitScalar(u8, sample, '\n'); + var n: usize = 0; + while (lines.next()) |text| : (n += 1) { + if (n < table.first or n >= table.end) continue; + var buf: [max_pads]Pad = undefined; + const pads = t.padsOf(table, text, &buf); + var col: usize = 0; + for (text, 0..) |_, b| { + // The pad before b: each of its cells is b's. + const start = File.displayWidth(text[0..b]) + @as(usize, @intCast(between(pads, 0, b))); + while (col < start) : (col += 1) try testing.expectEqual(b, byteAt(text, pads, 0, col)); + try testing.expectEqual(b, byteAt(text, pads, 0, col)); + col += 1; + } + // Past the end, a virtual column a cell. + try testing.expectEqual(text.len + 2, byteAt(text, pads, 0, col + 2)); + // From a scrolled start, the pads before it are not counted. + try testing.expectEqual(@as(usize, 2), byteAt(text, pads, 2, 0)); + } +} + +test "tables: a markdown table is drawn aligned, its bytes in order, the caret and a click on each byte's cell" { + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + var frame = std.heap.ArenaAllocator.init(testing.allocator); + defer frame.deinit(); + const pane = try testPane(p, sample, frame.allocator()); + const r = p.rects[0]; + const text_x = r.x + config.GUTTER + File.gutterWidth(pane); + const body_y = p.bodyTop(pane, r); + // The k-th pipe of every row on one screen column. + var pipe_x: [4]?u16 = @splat(null); + for (2..7) |line| { + const text = File.sourceLine(pane, @intCast(line)); + var k: usize = 0; + for (text, 0..) |b, i| { + const x = text_x + @as(u16, @intCast(File.displayOffset(pane, @intCast(line), 0, @intCast(i)))); + const cell = p.surface.at(x, body_y + @as(u16, @intCast(line))); + if (b == '|') { + if (pipe_x[k]) |want| try testing.expectEqual(want, x) else pipe_x[k] = x; + try testing.expect(!std.mem.eql(u8, cell.grapheme(), " ")); + k += 1; + } else if (line != 3) try testing.expectEqualStrings(text[i .. i + 1], cell.grapheme()); + } + } + try testing.expectEqual(@as(u16, 1 + 7 + 1 + 5 + 1 + 17), pipe_x[3].? - text_x); + // B1 on any cell of `| fig || |`: the caret on the byte the cell is + // (a pad's cells are the byte after them), drawn where that byte is. + const fig: i32 = 6; + const text = File.sourceLine(pane, fig); + const y = body_y + 6; + var col: u16 = 0; + while (col < pipe_x[3].? - text_x + 1) : (col += 1) { + p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = text_x + col, .row = y } }); + p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = text_x + col, .row = y } }); + const want = File.byteAtRowDisplay(pane, fig, 0, col); + try testing.expectEqual(fig, pane.body.cur_row); + try testing.expectEqual(want, pane.body.cur_col); + try testing.expect(want < text.len); + _ = frame.reset(.retain_capacity); + _ = try p.render(frame.allocator()); + const caret = p.surface.cursor orelse return error.NoCaret; + try testing.expectEqual(text_x + @as(u16, @intCast(File.displayOffset(pane, fig, 0, want))), caret.x); + // The caret is on the cell clicked, or on the glyph after its pad. + try testing.expect(caret.x >= text_x + col); + } + // A pad cell: the empty second cell's five, all the `|` after them. + const empty_x = pipe_x[1].? - text_x + 1; + for (0..5) |i| try testing.expectEqual(@as(i32, 7), File.byteAtRowDisplay(pane, fig, 0, @intCast(empty_x + i))); +} + +test "tables: typing in a cell re-aligns the table live, and j/k keep the column shown" { + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + var frame = std.heap.ArenaAllocator.init(testing.allocator); + defer frame.deinit(); + const pane = try testPane(p, sample, frame.allocator()); + // On `3` in the apple row: insert before it. + pane.body.cur_row = 4; + pane.body.cur_col = 10; + p.update(.{ .key = .{ .cp = 'i', .text = "i" } }); + for ("123456789") |c| p.update(.{ .key = .{ .cp = c, .text = &.{c} } }); + _ = frame.reset(.retain_capacity); + _ = try p.render(frame.allocator()); + try testing.expectEqualStrings("| apple | 1234567893 | red |", File.sourceLine(pane, 4)); + // The qty column is now 12 wide in every row. + for (2..7) |line| { + const text = File.sourceLine(pane, @intCast(line)); + var k: usize = 0; + for (text, 0..) |b, i| { + if (b != '|') continue; + k += 1; + if (k == 3) try testing.expectEqual(@as(i32, 1 + 7 + 1 + 12), File.displayOffset(pane, @intCast(line), 0, @intCast(i))); + } + } + // k from the kiwi row's `and` keeps its screen column: the apple + // row's centred `red` under it. + p.update(.{ .key = .{ .cp = Key.escape } }); + pane.body.cur_row = 5; + pane.body.cur_col = @intCast(std.mem.indexOf(u8, File.sourceLine(pane, 5), "and").?); + pane.body.vsel.active = false; + pane.body.sticky_col = -1; + const shown = File.displayOffset(pane, 5, 0, pane.body.cur_col); + p.update(.{ .key = .{ .cp = 'k', .text = "k" } }); + try testing.expectEqual(@as(i32, 4), pane.body.cur_row); + try testing.expectEqual(shown, File.displayOffset(pane, 4, 0, pane.body.cur_col)); +} |
